0

我正在编写一个 Go 脚本,它将解密一些用EVP_aes_256_cbcRSA 公钥加密的遗留数据。

在 C 中,这将类似于:

key_size = EVP_OpenInit(&ctx, EVP_aes_256_cbc(), evp_key, eklen, iv, pkey);
//...
EVP_OpenUpdate(&ctx, destination, &len_out, buffer_in, buffer_size)
//...
EVP_OpenFinal(&ctx, destination+len_out, &len_out);

我在 Go 中有evp_keyiv字节数组等价物,但我必须承认 EVP 在 OpenSSL 中的工作顺序让我难以理解(我在 C 语言中相当胜任,但我无法掌握这种解密发生的过程查看 OpenSSL 源代码。)

在 Go 中,我可以做到这一点:

pKey := //rsa.PrivateKey
eklen := 32
evpKey := "// hidden 32 byte array"
iv := "// hidden 16 byte array"

c, err := aes.NewCipher(iv)
cbc := cipher.NewCBCDecrypter(c, iv)

这就是我迷路的地方。我有一个evpKeypKey,但我不知道如何从这里解密数据。OpenSSL 使用RSA_decrypt_old或类似的东西,但我无法追查这实际上意味着什么。

是否有 Go 等价物,或者我是否需要摆脱过于昂贵的cgo包裹并卷起袖子?

更新(分辨率):

对于希望在 Go 中复制 EVP 行为或只是想知道 EVP 是如何工作的任何人,以下是细分。如果您知道 C(或 Java 或任何 OpenSSL 实现)正在使用以下内容进行加密:

// pseudo-code: don't copypasta and expect amazing
EVP_PKEY_assign_RSA(pkey, public_key);
EVP_CIPHER_CTX_init(&ctx);
EVP_SealInit(&ctx, EVP_aes_256_cbc(), &evp_key, &evp_key_len, iv, &pkey, 1);
EVP_SealUpdate(&ctx, buffer_out, &encrypt_len, (unsigned char*)buffer_in, len);
EVP_SealFinal(&ctx, buffer_out+encrypt_len, &encrypt_len);

“印章”实际上只是用 RSA 公钥加密密钥。

在 Go 中解密类似的内容:

evpKeyBytes := "// the rsa.PublicKey encoded evpKey"
evpKey, err := rsa.DecryptPKCS1v15(rand.Reader, PrivateKeyRSA, evpKeyBytes)
c, err := aes.NewCipher(evpKey)
cbc := cipher.NewCBCDecrypter(c, iv)
decryptedDataBytes := make([]bytes, 2048) // some message size
cbc.CryptBlocks(decryptedDataBytes, encryptedDataBytes)
data = string(decryptedDataBytes)
// data should have the expected decrypted result.
4

1 回答 1

2

NewCipher期望密钥不是 iv,并且由于您传递的是 128 位 iv,因此它可以用作 aes128cbc。

于 2014-09-03T23:53:19.177 回答