来自NodeJS的Golang Decrypt AES 256 CBC base64

时间:2017-09-28 17:34:54

标签: node.js go encryption

这就是我在Node.js中所拥有的:

w2f0vBP2hRfgVqssqOluk68Qxkc9LXFESc0ZGzPBq3p6f/x/LbwBbg1XOoRr7I/DAtESJGdweKG6nL9m8RfewA==

返回:package main import ( "crypto/aes" "crypto/cipher" "encoding/base64" "fmt" ) // decrypt from base64 to decrypted string func decrypt(key []byte, iv []byte, cryptoText string) string { ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText) block, err := aes.NewCipher(key) if err != nil { panic(err) } if len(ciphertext) < aes.BlockSize { panic("ciphertext too short") } ciphertext = ciphertext[aes.BlockSize:] stream := cipher.NewCFBDecrypter(block, iv) stream.XORKeyStream(ciphertext, ciphertext) return fmt.Sprintf("%s", ciphertext) } func main() { encKey := "NFd6N3v1nbL47FK0xpZjxZ7NY4fYpNYd" iv := "TestingIV1234567" stringtodecrypt := "w2f0vBP2hRfgVqssqOluk68Qxkc9LXFESc0ZGzPBq3p6f/x/LbwBbg1XOoRr7I/DAtESJGdweKG6nL9m8RfewA==" stringtodecrypt = decrypt([]byte(encKey), []byte(iv), stringtodecrypt) fmt.Println(string(stringtodecrypt)) }

这就是我在Go中所拥有的:

_▒▒▒6▒▒d,O▒ob"▒

最终返回hex.DecodeString

很多Go代码来自https://gist.github.com/manishtpatel/8222606

我也尝试了这个:How do I decrypt an AES256 bit cipher in golang that was encrypted in nodejs?(在这种情况下,panic: crypto/cipher: input not full blocks没有必要进行一些修改)但会引发错误func main() { encKey := "NFd6N3v1nbL47FK0xpZjxZ7NY4fYpNYd" iv := "TestingIV1234567" stringtodecrypt := "w2f0vBP2hRfgVqssqOluk68Qxkc9LXFESc0ZGzPBq3p6f/x/LbwBbg1XOoRr7I/DAtESJGdweKG6nL9m8RfewA==" block, err := aes.NewCipher([]byte(encKey)) if err != nil { panic(err) } mode := cipher.NewCBCDecrypter(block, []byte(iv)) mode.CryptBlocks([]byte(stringtodecrypt), []byte(stringtodecrypt)) fmt.Println(string(stringtodecrypt)) }

当我尝试这个时,这是我的代码:

Mockito

我经常搜索,我似乎无法解决这个问题。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

你的第二次尝试更接近,但你没有先解码base64字符串。

如果你通过密码包中的CBCDecrypter example,你会有这样的事情:

encKey := "NFd6N3v1nbL47FK0xpZjxZ7NY4fYpNYd"
iv := "TestingIV1234567"
ciphertext, err := base64.StdEncoding.DecodeString("w2f0vBP2hRfgVqssqOluk68Qxkc9LXFESc0ZGzPBq3p6f/x/LbwBbg1XOoRr7I/DAtESJGdweKG6nL9m8RfewA==")
if err != nil {
    panic(err)
}

block, err := aes.NewCipher([]byte(encKey))
if err != nil {
    panic(err)
}

if len(ciphertext)%aes.BlockSize != 0 {
    panic("ciphertext is not a multiple of the block size")
}

mode := cipher.NewCBCDecrypter(block, []byte(iv))
mode.CryptBlocks(ciphertext, ciphertext)

fmt.Printf("%s\n", ciphertext)

https://play.golang.org/p/16wV2UJ5Iw