Sampath R
Sampath R

Reputation: 1

How to achieve Xamarin.Android Asymmetric Encryption of RSA key?

Here's the code that i have implemented. Click here for errors. Do i have to import any nuget? Help

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)", "");
        }

Upvotes: 0

Views: 1028

Answers (1)

nyconing
nyconing

Reputation: 1136

Your codes is in , however, Xamarin using

Please use C# way to do RSA encryption.

If you dont mind, use mine

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));
}

Usage:

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);

Note, this class use 2048 bits and Pkcs1 padding as default, you can change it according to your flavor.

Upvotes: 2

Related Questions