gpt4 book ai didi

c# - 在 Python 中解密使用 .NET 加密的字符串

转载 作者:太空狗 更新时间:2023-10-29 18:29:06 28 4
gpt4 key购买 nike

我正在尝试使用 C# 加密字符串并使用 Python 解密它。加密/解密部分按预期工作(即我能够解密我最初加密的字符串)。但是Python返回的字符串开头多了2个字节,每个字符之间用空格隔开。

**Original string** (before encryption -- encrypted using C#) = "Something you want to keep private with AES"

**Decrypted string** (using Python) = "��S o m e t h i n g y o u w a n t t o k e e p p r i v a t e w i t h A E S"

为什么我会在字符串的开头得到这两个额外的字节?为什么解密字符串中有所有这些空格?知道为什么吗?

谢谢!

使用 C# 加密

public static string Encrypt<T>(string value, string password, string salt)
where T : SymmetricAlgorithm, new()
{
DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));

SymmetricAlgorithm algorithm = new T();

byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);

ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV);

using (MemoryStream buffer = new MemoryStream())
{
using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(value);
}
}

return Convert.ToBase64String(buffer.ToArray());
}
}


string plain = "Something you want to keep private with AES";
string encrypted = CipherUtility.Encrypt<AesManaged>(plain, "password", "salt");

用Python + pycrypto解密

import base64, sys
import Crypto.Cipher.AES

password = base64.b64decode('PSCIQGfoZidjEuWtJAdn1JGYzKDonk9YblI0uv96O8s=') # See rgbKey
salt = base64.b64decode('ehjtnMiGhNhoxRuUzfBOXw==') # See rgbIV
aes = Crypto.Cipher.AES.new(password, Crypto.Cipher.AES.MODE_CBC, salt)
text = base64.b64decode('QpHn/fnraLswwI2Znt1xTaBzRtDqO4V5QI78jLOlVsbvaIs0yXMUlqJhQtK+su2hYn28G2vNyLkj0zLOs+RIjElCSqJv1aK/Yu8uY07oAeStqRt4u/DVUzoWlxdrlF0u')

print aes.decrypt(text)

最佳答案

字符串使用 UTF-16 编码编码为字节。前两个字节是 BOM。然后每个字符被编码为两个字节。

来自 Encoding.Unicode 的文档:

Gets an encoding for the UTF-16 format using the little endian byte order.

要获取原始字符串,您需要将其从 UTF-16 字节解码回 Unicode 字符串。

print aes.decrypt(text).decode('utf-16')

关于c# - 在 Python 中解密使用 .NET 加密的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10565896/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com