如何在Go中解密由固定盐生成的字符串?

时间:2019-07-18 01:05:19

标签: go encryption

我有大量用Jasypt加密的数据,我需要在Go上解密。既有固定盐也有随机盐。

我发现this repo的工作端口为BasicTextEncryptor。对于我用密码和随机盐加密的数据,它可以正常工作。

我尝试用固定的字符串替换随机盐,虽然我没有遇到任何错误,但它没有返回实际的加密内容。

func FDecrypt(password, cipherText, salt string, obtenationIterations int) (string, error) {
    msgBytes, err := base64.StdEncoding.DecodeString(cipherText)
    if err != nil {
        return "", err
    }

    //salt := msgBytes[:8]
    encText := msgBytes[8:]

    dk, iv := getDerivedKey(password, salt, obtenationIterations)
    block, err := des.NewCipher(dk)

    if err != nil {
        return "", err
    }

    decrypter := cipher.NewCBCDecrypter(block, iv)
    decrypted := make([]byte, len(encText))
    decrypter.CryptBlocks(decrypted, encText)

    decryptedString := strings.TrimRight(string(decrypted), "\x01\x02\x03\x04\x05\x06\x07\x08")

    return decryptedString, nil
}

func getDerivedKey(password string, salt string, count int) ([]byte, []byte) {
    key := md5.Sum([]byte(password + salt))
    for i := 0; i < count - 1; i++ {
        key = md5.Sum(key[:])
    }
    return key[:8], key[8:]
}

我(在Jasypt中)加密了以下内容进行测试:

  • 内容:encryption test
  • 密码:password
  • 盐:fixed_salt

加密结果为:IcszAY8NRJf6ANt152Fifg==

使用上述代码在Go上解密时,我得到:�p�=��

有什么提示吗?

1 个答案:

答案 0 :(得分:0)

很抱歉回答我自己的问题!

之前,我将Github repository与我用来解决问题的代码链接在一起。正如Markus在评论中所建议的那样,我在那里打开了一个问题。回购所有者(Lucas Sloan)给了我一些提示。在检查了jasypt源代码并弄乱了我先前发布的代码之后,我终于找到了解决方案。

这是工作代码:

func Decrypt(password, cipherText, fixedSalt string, obtenationIterations int) (string, error) {
    msgBytes, err := base64.StdEncoding.DecodeString(cipherText)
    if err != nil {
        return "", err
    }

    salt := make([]byte, 8)
    copy(salt[:], fixedSalt)
    encText := msgBytes[:]

    dk, iv := getDerivedKey(password, salt, obtenationIterations)
    block, err := des.NewCipher(dk)

    if err != nil {
        return "", err
    }

    decrypter := cipher.NewCBCDecrypter(block, iv)
    decrypted := make([]byte, len(encText))
    decrypter.CryptBlocks(decrypted, encText)

    decryptedString := strings.TrimRight(string(decrypted), "\x01\x02\x03\x04\x05\x06\x07\x08")

    return decryptedString, nil
}

func getDerivedKey(password string, salt string, count int) ([]byte, []byte) {
    key := md5.Sum([]byte(password + salt))
    for i := 0; i < count - 1; i++ {
        key = md5.Sum(key[:])
    }
    return key[:8], key[8:]
}

我错过了两个要点:

  1. Jasypt将盐修剪为8个字节的数组:
salt := make([]byte, 8)
copy(salt[:], fixedSalt)
  1. 使用固定盐加密时,盐不会附加到结果中,因此解密时需要获取全部内容:
encText := msgBytes[:]

我对该存储库进行了PR,因此您可以根据需要使用它。该软件包还具有加密功能(具有固定盐和随机盐):https://github.com/LucasSloan/passwordbasedencryption