go - 解密不稳定,有时会得到密码:消息身份验证失败

标签 go encryption

我正在尝试为我的软件创建E2E加密,但是解密非常不稳定,有时可以成功解密,有时得到cipher: message authentication failed,这是我的加密和解密代码

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
}

加密的二进制值通过http传输:
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    return nil, err
}

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

我已经尝试检查的是ioutil.ReadAll是否正确读取了内容,或者解密程序出了点问题

最佳答案

抱歉,问题不在加密/解密中,而是在用于传输Chipertext的http服务器中,并且现在已经修复https://github.com/codenoid/GoTral-Server/commit/493c7f654753cae36f074c1c5f382953e227d295

关于go - 解密不稳定,有时会得到密码:消息身份验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58537035/

相关文章:

pointers - 如果我将成员函数指针放在指针实例范围之外,是否有任何问题

swift - 使用安全框架快速加密

php - 在PHP openssl_encrypt和golang河豚中匹配河豚加密

go - 为什么 slice 长度大于容量会导致运行时错误?

docker - 如何解决使用docker安装go的app出现 "undefined: math.Round"的问题

linux - Golang os.Create 权限被拒绝

interface - 如何实现可以接受可以在 golang 中进行相等性测试的任何类型的链表?

javascript - 测试所有可能的加密 key 需要多少时间?

java - 如何在 Android 上使用 Java BouncyCaSTLe API 使用明文 key 对字符串进行 RSA 加密

java - SHA 算法每次为相同的 key 生成唯一的哈希字符串