Created
November 13, 2014 02:29
-
-
Save jemygraw/fcfe9d60d3b920d903ee to your computer and use it in GitHub Desktop.
C# RSA-OAEP Encrypt
This file contains 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
using System; | |
using System.Text; | |
using System.Security.Cryptography; | |
using System.Security.Cryptography.X509Certificates; | |
namespace Qiniu.Util | |
{ | |
public static class Base64URLSafe | |
{ | |
public static string Encode (string text) | |
{ | |
if (String.IsNullOrEmpty (text)) | |
return ""; | |
byte[] bs = Encoding.UTF8.GetBytes (text); | |
string encodedStr = Convert.ToBase64String (bs); | |
encodedStr = encodedStr.Replace ('+', '-').Replace ('/', '_'); | |
return encodedStr; | |
} | |
/// <summary> | |
/// string扩展方法,生成base64UrlSafe | |
/// </summary> | |
/// <param name="str"></param> | |
/// <returns></returns> | |
public static string ToBase64URLSafe (string str) | |
{ | |
return Encode (str); | |
} | |
public static string Encode (byte[] bs) | |
{ | |
if (bs == null || bs.Length == 0) | |
return ""; | |
string encodedStr = Convert.ToBase64String (bs,Base64FormattingOptions.None); | |
encodedStr = encodedStr.Replace ('+', '-').Replace ('/', '_'); | |
return encodedStr; | |
} | |
static readonly string publickey = @"<RSAKeyValue><Modulus>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAygGoUiTD+LjwZIgwFZyjiibWNQ2LM9xZ2pjKQGP8iUBtAuAW629/Ofw8qxToMyixPrG4A7j8+KOPwYrWPGV6Og//4zm3cG+1hQvnNUWtMjHHBY8OByUPQ6/T8XHER1DxFBfnWfFLZ1yFX6oNNuvtLgOreI6ehehJd5IB/4mOjMvFEBgOEejado2n55VNdcFpdQ3RcvGV+f/rl/lsIM08QvL3lc5gqawj53sW9YZi1DL/uN48R+ghvAYhtx2jpHDBvlH1NCF1rU6CynYsgV9QIksv0ihwl4T+k5F9ir0uv0WIS6kKKS1SRpAprRKunos4PlE8l2+jC6LaJUPhDZlj/wID</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; | |
/// <summary> | |
/// RSA加密 | |
/// </summary> | |
/// <param name="content"></param> | |
/// <returns></returns> | |
public static string RSAEncrypt(string content) | |
{ | |
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) | |
{ | |
byte[] cipherbytes; | |
rsa.FromXmlString(publickey); | |
byte[] contentBytes = UTF8Encoding.UTF8.GetBytes(content); | |
cipherbytes = rsa.Encrypt(contentBytes, true); //以RSA的OAEP加密方式 | |
string encodedStr = Encode(cipherbytes); | |
return encodedStr; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment