From 7147980eac19672653a4cd2dc6ec16d2e6103388 Mon Sep 17 00:00:00 2001 From: Zack Scholl Date: Mon, 24 Sep 2018 12:52:19 -0700 Subject: [PATCH] encryption faster with simpler marshaling --- src/crypt/crypt.go | 26 ++++++++++++++++++++++++++ src/recipient/recipient.go | 3 +-- src/sender/sender.go | 6 +----- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/crypt/crypt.go b/src/crypt/crypt.go index 0f1915b..7160ad5 100644 --- a/src/crypt/crypt.go +++ b/src/crypt/crypt.go @@ -5,6 +5,9 @@ import ( "crypto/cipher" "crypto/rand" "crypto/sha256" + "encoding/base64" + "errors" + "strings" "golang.org/x/crypto/pbkdf2" ) @@ -16,6 +19,29 @@ type Encryption struct { IV []byte `json:"i"` } +func (e Encryption) Bytes() []byte { + return []byte(base64.StdEncoding.EncodeToString(e.Encrypted) + "-" + base64.StdEncoding.EncodeToString(e.Salt) + "-" + base64.StdEncoding.EncodeToString(e.IV)) +} + +func FromBytes(b []byte) (enc Encryption, err error) { + enc = Encryption{} + items := strings.Split(string(b), "-") + if len(items) != 3 { + err = errors.New("not valid") + return + } + enc.Encrypted, err = base64.StdEncoding.DecodeString(items[0]) + if err != nil { + return + } + enc.Salt, err = base64.StdEncoding.DecodeString(items[1]) + if err != nil { + return + } + enc.IV, err = base64.StdEncoding.DecodeString(items[2]) + return +} + // Encrypt will generate an encryption func Encrypt(plaintext []byte, passphrase []byte, dontencrypt ...bool) Encryption { if len(dontencrypt) > 0 && dontencrypt[0] { diff --git a/src/recipient/recipient.go b/src/recipient/recipient.go index d2b7e92..42b5833 100644 --- a/src/recipient/recipient.go +++ b/src/recipient/recipient.go @@ -133,8 +133,7 @@ func receive(forceSend int, serverAddress, serverTCP string, isLocal bool, c *we // unmarshal the file info log.Debugf("[%d] recieve file info", step) // do decryption on the file stats - var enc crypt.Encryption - err = json.Unmarshal(message, &enc) + enc, err := crypt.FromBytes(message) if err != nil { return err } diff --git a/src/sender/sender.go b/src/sender/sender.go index 19f5d6f..6977e71 100644 --- a/src/sender/sender.go +++ b/src/sender/sender.go @@ -193,12 +193,8 @@ func send(forceSend int, serverAddress, serverTCP string, isLocal bool, c *webso } // encrypt the file meta data enc := crypt.Encrypt(fstatsBytes, sessionKey) - encBytes, err := json.Marshal(enc) - if err != nil { - return err - } // send the file meta data - c.WriteMessage(websocket.BinaryMessage, encBytes) + c.WriteMessage(websocket.BinaryMessage, enc.Bytes()) case 4: spin.Stop()