我试图解密使用pgcrypto加密的数据。我没有使用IV,因为它只是一个测试,但我无法用C#解密数据。解密通过pgcrypto加密的数据(使用C#)
加密在POSTGRES:
enc_key := '\\xAACE38F289EC3EA209B48D';
-- Time insertions
ts_start := clock_timestamp();
FOR i IN 1..num_loops LOOP
-- The text to insert and its key
plaintext := 'Number: ' || i;
plaintext_pk := gen_random_uuid();
plaintext_pk_as_text := plaintext_pk::text;
-- The ref entries
user_pk := gen_random_uuid();
user_ref_pk := encrypt(plaintext_pk_as_text::bytea, enc_key, 'aes');
-- Add the enries
INSERT INTO "Text" VALUES(plaintext_pk, plaintext);
INSERT INTO "User" VALUES(user_ref_pk, user_pk);
END LOOP;
ts_end := clock_timestamp();
elapsed_raw := cast(extract(epoch from (ts_end - ts_start)) as numeric(18,3));
解密在C#:
// The decryption key
byte[] enc_key = new byte[] { 0xAA, 0xCE, 0x38, 0xF2, 0x89, 0xEC, 0x3E, 0xA2, 0x09, 0xB4, 0x8D,
0x00, 0x00, 0x00, 0x00, 0x00 };
public static string AESDecryptByteArray(byte [] encoded_data, byte [] key)
{
string result = "";
byte [] result_ba = new byte[64];
using (Aes myAes = Aes.Create())
{
if (myAes == null)
{
throw new Exception("Failed to create AES object.");
}
myAes.Key = key;
myAes.Mode = CipherMode.CBC;
myAes.Padding = PaddingMode.PKCS7;
MemoryStream streamMem = new MemoryStream(encoded_data);
byte[] IV = new byte[16];
// streamMem.Read(IV, 0, 16);
for (int i = 0; i < 16; ++i)
{
IV[i] = 0;
}
myAes.IV = IV;
int iNumBytes = 0;
var decryptor = myAes.CreateDecryptor();
using (CryptoStream streamCrypt = new CryptoStream(streamMem, decryptor, CryptoStreamMode.Read))
{
iNumBytes = streamCrypt.Read(result_ba, 0, 48);
}
result = System.Text.Encoding.ASCII.GetString(result_ba);
}
return result;
} // AESDecryptByteArray
我从行之一,并且二进制密钥复制的产生的加密数据,但C#代码保持与吹CryptographicException(“填充无效且无法移除”)异常。我的理解是,pgcrypto的encrypt()默认为cbc \ pkcs。很明显,我错过了一些东西。
任何帮助感激地收到。
亚当。
也许你可以尝试使用C#函数对数据进行加密,并尝试使加密数据与PostGres数据匹配100%。一旦匹配,您应该能够找到两个系统之间的断开连接。 –
谢谢,迈克尔 - 很好的建议。我会试试看。或者甚至确保我只能在C#中进行加密和解密才能开始。 –