2009/04/03

RSA String Encryption/Decryption

Same with the TripleDES, here is what I use to encrypt/decrypt string (not a good idea to encrypt files). Here is the encryption:
public byte[] RSAEncryptString(string data, string xmlKeyString)
{
  try
  {
    RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
    oRSA.FromXmlString(xmlKeyString);
    return oRSA.Encrypt(Encoding.UTF8.GetBytes(data), false);
  }
  catch (CryptographicException cex)
  {
    throw cex;
  }
}
Here is the decryption:
public string RSADecryptString(byte[] data, string xmlKeyString)
{
  try
  {
    RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
    oRSA.FromXmlString(xmlKeyString);
    return Encoding.UTF8.GetString(oRSA.Decrypt(data, false));
  }
  catch (CryptographicException cex)
  {
    throw cex;
  }
}
It's better to use RSA to generate the public/private key pair:
public List<string> RSAKeypairGenerator()
{
  List<string> lstResult = new List<string>();
  RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
  //public key
  lstResult.Add(oRSA.ToXmlString(false));
  //private key
  lstResult.Add(oRSA.ToXmlString(true));
  oRSA.Clear();
  return lstResult;
}

No comments:

Post a Comment