Skip to content

Instantly share code, notes, and snippets.

@njmube
Forked from sdhjl2000/gist:4223018
Last active August 29, 2015 14:23
Show Gist options
  • Save njmube/b60ed654e3b20e7a83db to your computer and use it in GitHub Desktop.
Save njmube/b60ed654e3b20e7a83db to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using APSP.Form.Model;
using NHibernateRepository;
using NUnit.Framework;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace APSPTest
{
public class RSAHelper
{
/// <summary>
/// 生成公钥、私钥
/// </summary>
/// <param name="PrivateKeyPath">私钥文件保存路径,包含文件名</param>
/// <param name="PublicKeyPath">公钥文件保存路径,包含文件名</param>
public void RSAKey(string PrivateKeyPath, string PublicKeyPath)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
SaveKey(PrivateKeyPath, provider.ToXmlString(true));//保存私钥文件
SaveKey(PublicKeyPath, provider.ToXmlString(false));//保存公钥文件
}
/// <summary>
/// 保存公钥/私钥文件
/// </summary>
/// <param name="path">公钥/私钥文件保存路径</param>
/// <param name="publickey">公钥/私钥值</param>
public void SaveKey(string path, string key)
{
FileStream stream = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine(key);
sw.Close();
stream.Close();
}
/// <summary>
/// RSA加密
/// </summary>
/// <param name="xmlPublicKey">公钥</param>
/// <param name="m_strEncryptString">需要加密的数据</param>
/// <returns>RSA公钥加密后的数据</returns>
public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
{
string str2;
try
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(xmlPublicKey);
byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);
str2 = Convert.ToBase64String(provider.Encrypt(bytes, false));
}
catch (Exception exception)
{
throw exception;
}
return str2;
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="xmlPrivateKey">私钥</param>
/// <param name="m_strDecryptString">需要解密的数据</param>
/// <returns>解密后的数据</returns>
public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
{
string str2;
try
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(xmlPrivateKey);
byte[] rgb = Convert.FromBase64String(m_strDecryptString);
byte[] buffer2 = provider.Decrypt(rgb, false);
str2 = new UnicodeEncoding().GetString(buffer2);
}
catch (Exception exception)
{
throw exception;
}
return str2;
}
}
[TestFixture]
public class oratest
{
[Test]
public void t1()
{
RSAHelper rh = new RSAHelper();
string privatesave="private.txt";
string publicsave="public.txt";
rh.RSAKey(privatesave,publicsave);
string enstr= rh.RSAEncrypt(APSP.Common.FileHelper.ReadFile(publicsave), "oatest1111");
Console.WriteLine(enstr);
string destr = rh.RSADecrypt(APSP.Common.FileHelper.ReadFile(privatesave), enstr);
Console.WriteLine(destr);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment