use*_*567 6 c# java porting rsa bouncycastle
我正在尝试将以下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);
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我设法使用.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);
}
Run Code Online (Sandbox Code Playgroud)
但是,即使使用相同的参数调用,这两种方法也会产生不同的结果.出于测试目的,我使用以下公共RSA密钥:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLCZahTj/oz8mL6xsIfnX399Gt6bh8rDHx2ItTMjUhQrE/9kGznP5PVP19vFkQjHhcBBJ0Xi1C1wPWMKMfBsnCPwKTF/g4yga6yw26awEy4rvfjTCuFUsrShSPOz9OxwJ4t0ZIjuKxTRCDVUO7d/GZh2r7lx4zJCxACuHci0DvTQIDAQAB
Run Code Online (Sandbox Code Playgroud)
你能帮我成功移植Java代码或者建议一个替代方案来在C#中获得相同的结果吗?
EDIT1:每次运行程序时,Java中的输出都不同.我不认为任何填充是指定的,所以我不明白是什么使输出随机.
EDIT2:Java默认使用PKCS1,因此在C#cipher初始化中指定它就足以获得相同的加密类型(虽然结果不一样,但此时无关紧要).