标签:
public static string RsaEncrypt(string publickey, string content) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(publickey); cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherbytes); } public static string RSADecrypt(string privatekey, string content) { var rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(privatekey); cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false); return Encoding.UTF8.GetString(cipherbytes); }
生成key:
string _publicKey; string _privateKey; RSACryptoServiceProvider _rsaService; _rsaService = new RSACryptoServiceProvider(); _publicKey = _rsaService.ToXmlString(false); _privateKey = _rsaService.ToXmlString(true);
可java一起用:
public static string RSAEncryptSpilt(string publickey, string content) { //公钥 //publickey = _publickey; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] byteArray = Encoding.UTF8.GetBytes(content); //byte[] byteArray = System.Text.Encoding.Default.GetBytes(content); content = Convert.ToBase64String(byteArray); rsa.FromXmlString(publickey); byte[] OriginalData = Convert.FromBase64String(content); if (OriginalData == null || OriginalData.Length <= 0) { throw new NotSupportedException(); } if (rsa == null) { throw new ArgumentNullException(); } int bufferSize = (rsa.KeySize / 8) - 37; byte[] buffer = new byte[bufferSize]; using (MemoryStream input = new MemoryStream(OriginalData)) using (MemoryStream ouput = new MemoryStream()) { while (true) { int readLine = input.Read(buffer, 0, bufferSize); if (readLine <= 0) { break; } byte[] temp = new byte[readLine]; Array.Copy(buffer, 0, temp, 0, readLine); byte[] encrypt = rsa.Encrypt(temp, false); ouput.Write(encrypt, 0, encrypt.Length); } return Convert.ToBase64String(ouput.ToArray()); } } public static string RSADecryptSpilt(string privatekey, string content) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] EncryptDada = Convert.FromBase64String(content); if (EncryptDada == null || EncryptDada.Length <= 0) { throw new NotSupportedException(); } //私钥 //privatekey = _privatekey; rsa.FromXmlString(privatekey); int keySize = rsa.KeySize / 8; byte[] buffer = new byte[keySize]; using (MemoryStream input = new MemoryStream(EncryptDada)) using (MemoryStream output = new MemoryStream()) { while (true) { int readLine = input.Read(buffer, 0, keySize); if (readLine <= 0) { break; } byte[] temp = new byte[readLine]; Array.Copy(buffer, 0, temp, 0, readLine); byte[] decrypt = rsa.Decrypt(temp, false); output.Write(decrypt, 0, decrypt.Length); } return Encoding.UTF8.GetString(output.ToArray()); } }
标签:
原文地址:http://www.cnblogs.com/ly7454/p/4546424.html