如何实现 Xamarin.Android 对 RSA 密钥的非对称加密?



这是我实现的代码。单击此处查看错误。我必须导入任何金块吗?帮助

public string EncryptRSA(string plainText, string publicKeyString)
{
byte[] cipherText = null;
String strEncryInfoData = "";
try
{
KeyFactory keyFac = KeyFactory.getInstance("RSA");
KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(publicKeyString.trim().getBytes(), Base64.DEFAULT));
Key publicKey = keyFac.generatePublic(keySpec);
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance("RSA");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
cipherText = cipher.doFinal(text.getBytes());
strEncryInfoData = new String(Base64.encode(cipherText, Base64.DEFAULT));
}
catch (Exception e)
{
}
return strEncryInfoData.replaceAll("(\r|\n)", "");
}

你的代码是用java的,但是,Xamarin使用c#

请使用 C# 方式进行 RSA 加密。

如果你不介意,用我的

public class RSA {
public RSA() => Provider = new RSACryptoServiceProvider(2048);
public RSA(string key) {
Provider = new RSACryptoServiceProvider(2048);
Provider.FromXmlString(Encoding.UTF8.GetString(Convert.FromBase64String(key)));
}
public RSACryptoServiceProvider Provider;
public string PublicKey() => Convert.ToBase64String(Encoding.UTF8.GetBytes(Provider.ToXmlString(false)));
public string PrivateKey() => Convert.ToBase64String(Encoding.UTF8.GetBytes(Provider.ToXmlString(true)));
public string Encrypt(string meta) => Convert.ToBase64String(Provider.Encrypt(Encoding.UTF8.GetBytes(meta), RSAEncryptionPadding.Pkcs1));
public string Decrypt(string meta) => Encoding.UTF8.GetString(Provider.Decrypt(Convert.FromBase64String(meta), RSAEncryptionPadding.Pkcs1));
}

用法:

var rsa = new RSA();
var generatePrivateKey = rsa.PrivateKey();
var generatePublicKey = rsa.PublicKey();
var encryted = new RSA(yourKey).Encrypt(yourText);
var decrypted = new RSA(yourKey).Decrypt(yourText);

请注意,此类默认使用2048位和 Pkcs1 填充,您可以根据自己的口味进行更改。

最新更新