Created
March 29, 2017 11:22
-
-
Save VictorZhang2014/4938b9b5a2872aecaf3a0261375a5a46 to your computer and use it in GitHub Desktop.
RSACryptoGraphy, a set of methods was written by C#.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Create public key/private key file, actually, the original certificates was modified to a XML file | |
/// 创建公钥/私钥文件,其实就是把原有的证书的内容修改成XML格式的 | |
/// </summary> | |
public static void CreateCertificateKeyXML(string path, string key) | |
{ | |
try | |
{ | |
FileStream keyxml = new FileStream(path, FileMode.Create); | |
StreamWriter sw = new StreamWriter(keyxml); | |
sw.WriteLine(key); | |
sw.Close(); | |
keyxml.Close(); | |
} | |
catch | |
{ | |
throw; | |
} | |
} | |
/// <summary> | |
/// Read public key/private key in terms of XML formation | |
/// 读取公钥/私钥,以XML的形式 | |
/// </summary> | |
public static string ReadCertificateKey(string path) | |
{ | |
StreamReader reader = new StreamReader(path); | |
string key = reader.ReadToEnd(); | |
reader.Close(); | |
return key; | |
} | |
/// <summary> | |
/// RSA Encryption | |
/// </summary> | |
/// <param name="xmlPublicKey">public key</param> | |
/// <param name="m_strEncryptString">unencrypted string</param> | |
/// <returns>encrypted string</returns> | |
public static 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 Decryption | |
/// </summary> | |
/// <param name="xmlPrivateKey">private key</param> | |
/// <param name="m_strDecryptString">undecrypted string</param> | |
/// <returns>decrypted result</returns> | |
public static 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; | |
} |
Author
VictorZhang2014
commented
Mar 29, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment