我正在尝试将以下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);
}到目前为止,我使用C#的BouncyCastle库为.NET编写了以下内容:
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);
}然而,这两种方法产生不同的结果,即使使用相同的参数调用。为了测试目的,我使用了以下公钥RSA:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLCZahTj/oz8mL6xsIfnX399Gt6bh8rDHx2ItTMjUhQrE/9kGznP5PVP19vFkQjHhcBBJ0Xi1C1wPWMKMfBsnCPwKTF/g4yga6yw26awEy4rvfjTCuFUsrShSPOz9OxwJ4t0ZIjuKxTRCDVUO7d/GZh2r7lx4zJCxACuHci0DvTQIDAQAB请您帮助我成功地移植Java代码,或者建议在C#中获得相同结果的替代方案?
EDIT1:每次运行程序时,Java的输出都是不同的。我认为没有指定任何填充,所以我不明白是什么使输出随机。
EDIT2:Java默认使用PKCS1,因此只要在C#密码初始化中指定PKCS1就可以获得相同的加密类型(尽管结果与此无关)。
发布于 2013-08-21 18:59:49
据我所知,我认为Java添加了随机填充来创建更强的加密。
大多数实际的RSA实现都是这样做的,正如维基所说.
因为RSA加密是一种确定性加密算法--即没有随机成分--攻击者可以通过在公钥下加密可能的明文并测试它们是否等于密文,成功地发起针对该密码系统的选择明文攻击。如果攻击者无法区分两种加密,即使攻击者知道(或选择)相应的明文,则称为语义安全。如上所述,没有填充的RSA在语义上是不安全的。
这可能是您的两个方法不能输出相同的原因。
https://stackoverflow.com/questions/11042742
复制相似问题