gpt4 book ai didi

c# - 将RSA加密Java代码移植到C#

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:33:27 25 4
gpt4 key购买 nike

我正在尝试将以下 Java 代码移植到 C# 等效代码:

public static String encrypt(String value, String key) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] bytes = value.getBytes(Charset.forName("UTF-8"));
X509EncodedKeySpec x509 = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(key));
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey publicKey = factory.generatePublic(x509);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
bytes = cipher.doFinal(bytes);
return DatatypeConverter.printBase64Binary(bytes);
}

到目前为止,我使用 .NET 的 BouncyCaSTLe 库在 C# 中成功编写了以下内容:

public static string Encrypt(string value, string key)
{
var bytes = Encoding.UTF8.GetBytes(value);
var publicKeyBytes = Convert.FromBase64String(key);
var asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);
var rsaKeyParameters = (RsaKeyParameters) asymmetricKeyParameter;
var cipher = CipherUtilities.GetCipher("RSA");
cipher.Init(true, rsaKeyParameters);
var processBlock = cipher.DoFinal(bytes);
return Convert.ToBase64String(processBlock);
}

但是,即使使用相同的参数调用,这两种方法也会产生不同的结果。出于测试目的,我使用以下公共(public) RSA key :

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLCZahTj/oz8mL6xsIfnX399Gt6bh8rDHx2ItTMjUhQrE/9kGznP5PVP19vFkQjHhcBBJ0Xi1C1wPWMKMfBsnCPwKTF/g4yga6yw26awEy4rvfjTCuFUsrShSPOz9OxwJ4t0ZIjuKxTRCDVUO7d/GZh2r7lx4zJCxACuHci0DvTQIDAQAB

能否请您帮助我成功移植 Java 代码或建议一个替代方案以在 C# 中获得相同的结果?

EDIT1:每次运行程序时,Java 的输出都不同。我认为没有指定任何填充,所以我不明白是什么使输出随机。

EDIT2:Java 默认使用 PKCS1,因此在 C# 密码初始化中指定它就足以获得相同的加密类型(尽管结果不同,此时无关紧要) .

最佳答案

作为有根据的猜测,我会说 Java 添加了随机填充以创建更强大的加密。

RSA 的大多数实际实现都是这样做的,并且作为 wiki把它...

Because RSA encryption is a deterministic encryption algorithm – i.e., has no random component – an attacker can successfully launch a chosen plaintext attack against the cryptosystem, by encrypting likely plaintexts under the public key and test if they are equal to the ciphertext. A cryptosystem is called semantically secure if an attacker cannot distinguish two encryptions from each other even if the attacker knows (or has chosen) the corresponding plaintexts. As described above, RSA without padding is not semantically secure.

这可能是您的两种方法输出不同的原因。

关于c# - 将RSA加密Java代码移植到C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11042742/

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