gpt4 book ai didi

C# 中的 Java AES/CBC/PKCS5Padding

转载 作者:行者123 更新时间:2023-12-01 22:12:05 26 4
gpt4 key购买 nike

我收到了需要转换为 C# 的 Java 加密代码。我想我已经很接近了...但我不知道如何复制 IV 计算...有什么帮助吗?

Java 代码:

    public static string getAESencodingResult(String sSrc, String encrypt_key)
{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = encrypt_key.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(encrypt_key.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);
}

C# 代码:

    static string EncryptStringToBytes(string plainText, byte[] key)
{
byte[] encrypted;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = key;
// rijAlg.IV = ???
rijAlg.GenerateIV();
rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.Mode = CipherMode.CBC;
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{

swEncrypt.Write(plainText);
if (plainText.Length < 16)
{
for (int i = plainText.Length; i < 16; i++)
swEncrypt.Write((byte)0x0);
}
swEncrypt.Flush();
csEncrypt.FlushFinalBlock();
encrypted = msEncrypt.ToArray();
}
}
return Convert.ToBase64String(encrypted);
}

最佳答案

如果我没有误解 Java 代码,您只需将键值分配给 IV:

rijAlg.Key = key;
rijAlg.IV = key;

并删除GenerateIV行:

rijAlg.GenerateIV();

我知道您无法控制 Java 代码,因此您无法修复此问题,但对于 future 的读者:您不应该在每次加密某些内容时都使用相同的 IV。请参阅this question了解更多信息。

关于C# 中的 Java AES/CBC/PKCS5Padding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58653218/

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