go – unstable decryption, sometimes got cipher: message authentication failed-ThrowExceptions

Exception or error:

I’m trying to create E2E Encryption for my software, but the decryption are very unstable, sometime can successfully decrypt, sometime got cipher: message authentication failed, here’s my encrypt & decrypt code

func Encrypt(data []byte, passphrase string) ([]byte, error) {
    // create aes.NewCipher from hashed md5 passphrase
    block, _ := aes.NewCipher([]byte(createHash(passphrase)))
    //  NewGCM returns the given 128-bit, block cipher wrapped in
    // Galois Counter Mode with the standard nonce length.
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }
    // initialize slice with length of nonce that must be passed to Seal and Open.
    nonce := make([]byte, gcm.NonceSize())
    if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
        return nil, err
    }

    ciphertext := gcm.Seal(nonce, nonce, data, nil)
    return ciphertext, nil
}

func Decrypt(data []byte, passphrase string) ([]byte, error) {
    // create md5 byte slice
    key := []byte(createHash(passphrase))
    // just `reverse` algorithm with passphrase until return
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }
    nonceSize := gcm.NonceSize()
    nonce, ciphertext := data[:nonceSize], data[nonceSize:]
    plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
    if err != nil {
        return nil, err
    }
    return plaintext, nil
}

the encrypted binary value are transferred via http :

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    return nil, err
}

decrypt, err := Decrypt(body, r.Passphrase)

what i already try is to check, is ioutil.ReadAll read content correctly, or something wrong with decryptor

How to solve:

sorry, the problem was not in encryption/decryption, but in http server for transferring the chipertext, and already fixes now https://github.com/codenoid/GoTral-Server/commit/493c7f654753cae36f074c1c5f382953e227d295

Leave a Reply

Your email address will not be published. Required fields are marked *