RSA加密算法:Java到C#代码转换
Java RSA加密代码转换为C#代码
本文提供将Java中使用RSA公钥加密的代码转换为C#代码的示例。
Java代码:
public static String encrypt(String str, String publicKey) throws Exception{
//base64编码的公钥
byte[] decoded = new BASE64Decoder().decodeBuffer(publicKey);
X509EncodedKeySpec x509Key = new X509EncodedKeySpec(decoded);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(x509Key);
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return new BASE64Encoder().encode(cipher.doFinal(str.getBytes("UTF-8")));
}
C#代码:
public static string Encrypt(string str, string publicKey)
{
byte[] decoded = Convert.FromBase64String(publicKey);
var rsa = RSA.Create();
rsa.ImportSubjectPublicKeyInfo(decoded, out _);
var encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(str), RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(encryptedData);
}
代码解释:
- 解码公钥: Java代码使用
BASE64Decoder
解码公钥,C# 代码使用Convert.FromBase64String
实现相同功能。 - 创建RSA对象: C# 使用
RSA.Create()
创建 RSA 对象,并使用ImportSubjectPublicKeyInfo
导入公钥信息。 - 加密数据: Java代码使用
Cipher
类进行加密,C# 代码使用rsa.Encrypt
方法实现。 - 编码密文: Java代码使用
BASE64Encoder
编码密文,C# 代码使用Convert.ToBase64String
实现相同功能。
注意: 以上示例使用了 .NET Framework 的 System.Security.Cryptography
命名空间中的 RSA 类。
通过以上示例,开发者可以方便地将 Java 代码中的 RSA 公钥加密功能移植到 C# 代码中,实现跨语言的加密功能。

原文地址: http://www.cveoy.top/t/topic/p3bL 著作权归作者所有。请勿转载和采集!