Reputation: 2331
I am trying to convert the logic of Crypt Lib in js I have existing android application and the API is in c sharp and I want to convert encrypt and decrypt logic.
I have tried multiple variations you can check the code: Tried code
I have a sample data which I want to decrypt and the data is:
{"Data":"bvtkHfZiTsY0CX6QmHhCboBwXeY9RZVPpdhhdIy6aSwCTVI7YiEGha1aXTIKY4BocGdNIbWkreQHZcTk4WE6F2tQLoVyWERYCGZotbDzxxs=","IV":"Vmr-uU5mA2_Zr_13"}
Here I have the encrypted data in Data and IV so when I am trying to decrypt this data I can't find any solution. All the encrypt and decrypt function is in csharp and android code. But I want to convert the same logic in golang.
The logic in Node
I have tried this code:
iv := []byte("Vmr-uU5mA2_Zr_13")
key := []byte("<Secret_Key")
text := []byte("bvtkHfZiTsY0CX6QmHhCboBwXeY9RZVPpdhhdIy6aSwCTVI7YiEGha1aXTIKY4BocGdNIbWkreQHZcTk4WE6F2tQLoVyWERYCGZotbDzxxs=")
cipherBlock, err := aes.NewCipher(key)
if err != nil {
log.Fatal(err)
}
cipher.NewCBCDecrypter(cipherBlock, iv).CryptBlocks(text, text)
fmt.Println(string(text))
Full link to the code and I am getting error:
crypto/aes: invalid key size 64
Upvotes: 1
Views: 574
Reputation: 1163
It looks like you need to decode your key
and text
strings properly into byte slices, not just cast them. The code below works, although I am not sure what the decoded message should look like...
package main
import (
"encoding/hex"
"encoding/base64"
"crypto/cipher"
"crypto/sha256"
"crypto/aes"
)
func main() {
iv := "Vmr-uU5mA2_Zr_13"
key := "<Secret_Key>"
ciphertext := "bvtkHfZiTsY0CX6QmHhCboBwXeY9RZVPpdhhdIy6aSwCTVI7YiEGha1aXTIKY4BocGdNIbWkreQHZcTk4WE6F2tQLoVyWERYCGZotbDzxxs="
hash := sha256.Sum256([]byte(key))
key = hex.EncodeToString(hash[:])[:32]
btext, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
println("Error decoding cipertext: ", err.Error())
return
}
aesCipher, err := aes.NewCipher([]byte(key))
if err != nil {
println("Error creating cipher: ", err.Error())
return
}
cipher.NewCBCDecrypter(aesCipher, []byte(iv)).
CryptBlocks(btext, btext)
println("Result: ", string(btext))
}
Upvotes: 2