本文整理汇总了C#中RSACryptoServiceProvider.Encrypt方法的典型用法代码示例。如果您正苦于以下问题:C# RSACryptoServiceProvider.Encrypt方法的具体用法?C# RSACryptoServiceProvider.Encrypt怎么用?C# RSACryptoServiceProvider.Encrypt使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RSACryptoServiceProvider
的用法示例。
在下文中一共展示了RSACryptoServiceProvider.Encrypt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EncryptRSA
/// <summary>
/// A string extension method that encrypts the string.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="key">The key.</param>
/// <returns>The encrypted string.</returns>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_String_EncryptRSA
/// {
/// [TestMethod]
/// public void EncryptRSA()
/// {
/// // Type
/// string @this = "Fizz";
///
/// // Examples
/// string value = @this.EncryptRSA("Buzz"); // return Encrypted string;
///
/// // Unit Test
/// Assert.AreEqual("Fizz", value.DecryptRSA("Buzz"));
/// }
/// }
/// }
/// </code>
/// </example>
public static string EncryptRSA(this string @this, string key) {
var cspp = new CspParameters {KeyContainerName = key};
var rsa = new RSACryptoServiceProvider(cspp) {PersistKeyInCsp = true};
byte[] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(@this), true);
return BitConverter.ToString(bytes);
}
示例2: Encrypt
private static byte[] Encrypt(string publicKeyXml, byte[] bytes, RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048)
{
byte[] encryptedBytes;
using (var RSA = new RSACryptoServiceProvider((int) rsaKeyLength))
{
RSA.FromXmlString(publicKeyXml);
encryptedBytes = RSA.Encrypt(bytes, DoOAEPPadding);
}
return encryptedBytes;
}
示例3: RSAEncrypt
public static string RSAEncrypt(string plaintext)
{
CspParameters param = new CspParameters();
param.KeyContainerName = "PowerGridIndia";
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
{
byte[] plaindata = System.Text.Encoding.Default.GetBytes(plaintext);
byte[] encryptdata = rsa.Encrypt(plaindata, false);
string encryptstring = Convert.ToBase64String(encryptdata);
return encryptstring;
}
}
示例4: Main
public static void Main(String[] args) {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 128; // 192;
aes.Key = new byte[] {0xC7, 0x42, 0xD1, 0x37, 0x4B, 0xAC, 0xFE, 0x94,
0x9D, 0x59, 0x79, 0x92, 0x71, 0x48, 0xD6, 0x8E};
// ,1,2,3,4,5,6,7,8};
byte[] aesKey = aes.Key;
if (args.Length > 0) {
FileStream fs = new FileStream(args[0], FileMode.Open);
StreamReader sr = new StreamReader(fs);
String xmlString = sr.ReadToEnd();
rsa.FromXmlString(xmlString);
} else {
FileStream fs = new FileStream("rsa.xml", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.Write(rsa.ToXmlString(true));
sw.Close();
}
Console.WriteLine("RSA Key is:\n"+rsa.ToXmlString(true));
Console.WriteLine("AES Key is:");
PrintByteArray(aesKey);
byte[] encryptedKey1 = rsa.Encrypt(aesKey, true);
Console.WriteLine("Encrypted AES Key is:");
PrintByteArray(encryptedKey1);
byte[] decryptedKey1 = rsa.Decrypt(encryptedKey1, true);
Console.WriteLine("Decrypted AES Key is:");
PrintByteArray(decryptedKey1);
byte[] encryptedKey2 = rsa.Encrypt(aesKey, false);
Console.WriteLine("Encrypted2 AES Key is:");
PrintByteArray(encryptedKey2);
byte[] decryptedKey2 = rsa.Decrypt(encryptedKey2, false);
Console.WriteLine("Decrypted AES Key is:");
PrintByteArray(decryptedKey2);
}
示例5: RsaCryptRoundtrip
public static void RsaCryptRoundtrip()
{
byte[] crypt;
byte[] output;
using (var rsa = new RSACryptoServiceProvider())
{
crypt = rsa.Encrypt(TestData.HelloBytes, true);
output = rsa.Decrypt(crypt, true);
}
Assert.NotEqual(crypt, output);
Assert.Equal(TestData.HelloBytes, output);
}
示例6: RsaDecryptAfterExport
public static void RsaDecryptAfterExport()
{
byte[] output;
using (var rsa = new RSACryptoServiceProvider())
{
byte[] crypt = rsa.Encrypt(TestData.HelloBytes, true);
// Export the key, this should not clear/destroy the key.
RSAParameters ignored = rsa.ExportParameters(true);
output = rsa.Decrypt(crypt, true);
}
Assert.Equal(TestData.HelloBytes, output);
}
示例7: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
var code = Request.QueryString["code"];
//send request to github server to get access token
HttpWebRequest req = WebRequest.Create("https://github.com/login/oauth/access_token?client_id=TODO:<your own client id>&client_secret=TODO:<your own client secret>&code=" + code) as HttpWebRequest;
req.Method = "POST";
HttpWebResponse rsps = req.GetResponse() as HttpWebResponse;
var str = new StreamReader(rsps.GetResponseStream()).ReadToEnd();
Match m = Regex.Match(str, "access_token=([^&]+)&token_type=([^&]+)");
//RSA encrypt access token with public key from browser side
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters publicKey = new RSAParameters();
publicKey.Modulus = literal2bytes(Request.Cookies["modulus"].Value);
publicKey.Exponent = literal2bytes(Request.Cookies["exponent"].Value);
rsa.ImportParameters(publicKey);
byte[] result = rsa.Encrypt(Encoding.UTF8.GetBytes(m.Groups[1].ToString()), false);
StringBuilder access_token = new StringBuilder();
for (var i = 0; i < result.Length; i++)
{
access_token.Append(result[i].ToString("x2"));
}
//write encrypted access_token back into cookie
HttpCookie cookie = new HttpCookie("access_token");
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(0, 0, 0, 0);
cookie.Expires = dt.Add(ts);
cookie.Value = access_token.ToString();
Response.AppendCookie(cookie);
cookie = new HttpCookie("token_type");
dt = DateTime.Now;
ts = new TimeSpan(0, 0, 0, 0);
cookie.Expires = dt.Add(ts);
cookie.Value = m.Groups[2].ToString();
Response.AppendCookie(cookie);
//now jump back, only the browser side could decrypt the access_token from cookie
Response.Redirect("TODO:<your own address>");
}
示例8: EncryptString
/// <summary>
/// 字符串加密
/// </summary>
/// <param name="source">源字符串 明文</param>
/// <param name="publicKey">公匙或私匙</param>
/// <returns>加密遇到错误将会返回原字符串</returns>
public static string EncryptString(string source, string key)
{
string encryptString = string.Empty;
try
{
if (!CheckSourceValidate(source))
{
throw new Exception("source string too long");
}
RSACryptoServiceProvider.UseMachineKeyStore = true;
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
rsaProvider.FromXmlString(FromBase64Key(key));
byte[] data = rsaProvider.Encrypt(System.Text.Encoding.ASCII.GetBytes(source), false);
encryptString = BytesToHexString(data);
}
catch{ }
return encryptString;
}
示例9: RSAEncrypt
public static byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo)
{
try
{
byte[] encryptedData;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.ImportParameters(RSAKeyInfo);
encryptedData = RSA.Encrypt(DataToEncrypt, false);
}
return encryptedData;
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
示例10: RSAEncrypt
private byte[] RSAEncrypt( byte [] PlainText )
{
string n =
"59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUtwC" +
"5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDR" +
"KSKv6kDqnw4UwPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuB" +
"OitnZ/bDzPHrTOZz0Dew0uowxf/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJ" +
"Q+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/UAaHqn9JdsBWLUEpVviYnh" +
"imNVvYFZeCXg/IdTQ+x4IRdiXNv5hEew==";
string e = "AQAB";
RSAParameters key = new RSAParameters();
key.Modulus = Convert.FromBase64String( n );
key.Exponent = Convert.FromBase64String( e );
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters( key );
return rsa.Encrypt( PlainText, true );
}
示例11: UnusualExponentCryptRoundtrip
public static void UnusualExponentCryptRoundtrip()
{
byte[] crypt;
byte[] output;
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(TestData.UnusualExponentParameters);
crypt = rsa.Encrypt(TestData.HelloBytes, true);
output = rsa.Decrypt(crypt, true);
}
Assert.NotEqual(crypt, output);
Assert.Equal(TestData.HelloBytes, output);
}
示例12: EncryptByPublicKey
/// <summary>
/// 通过公钥加密
/// </summary>
/// <param name="dataStr">待加密字符串</param>
/// <returns>加密结果</returns>
public static string EncryptByPublicKey(string dataStr)
{
//取得公钥参数
RSAParameters rsaparameters = ConvertFromPemPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8eWx4ZoUw3IOnVJ3Uu7N2fnj/CCoBNsMy7rXkwgpzkWM6apBEmZWaTkG888s8vJ16e0dUvTroQ6jc3kHZrnY9C+caIQWDwG9Msty/o8YZqvtmPQvSUPXg+I4KTSY7Gt53Rjpr5C8XaH8KTEXPWddg4xTWzWM4vRyNH4cP8K8kgQIDAQAB");
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.ImportParameters(rsaparameters);
byte[] bytes = new UnicodeEncoding().GetBytes(dataStr);
string str2 = Convert.ToBase64String(RSA.Encrypt(bytes, false));
return HttpUtility.UrlEncode(str2);
}
示例13: LargeKeyCryptRoundtrip
public static void LargeKeyCryptRoundtrip()
{
byte[] output;
using (var rsa = new RSACryptoServiceProvider())
{
try
{
rsa.ImportParameters(TestData.RSA16384Params);
}
catch (CryptographicException)
{
// The key is pretty big, perhaps it was refused.
return;
}
byte[] crypt = rsa.Encrypt(TestData.HelloBytes, true);
Assert.Equal(rsa.KeySize, crypt.Length * 8);
output = rsa.Decrypt(crypt, true);
}
Assert.Equal(TestData.HelloBytes, output);
}
示例14: Encrypt
/// <summary>
/// Encrypt an arbitrary string of data under the supplied public key
/// </summary>
/// <param name="publicKey">The public key to encrypt under</param>
/// <param name="data">The data to encrypt</param>
/// <param name="length">The bit length or strength of the public key: 1024, 2048 or 4096 bits. This must match the
/// value actually used to create the publicKey</param>
/// <returns></returns>
public static string Encrypt(string publicKey, string data, RsaKeyLengths length = RsaKeyLengths.Bit2048)
{
// full array of bytes to encrypt
byte[] bytesToEncrypt;
// worker byte array
byte[] block;
// encrypted bytes
byte[] encryptedBytes;
// length of bytesToEncrypt
var dataLength = 0;
// number of bytes in key
var keySize = 0;
// maximum block length to encrypt
var maxLength = 0;
// how many blocks must we encrypt to encrypt entire message?
var iterations = 0;
// the encrypted data
var encryptedData = new StringBuilder();
// instantiate the crypto provider with the correct key length
var rsaCryptoServiceProvider = new RSACryptoServiceProvider((int)length);
// initialize the RSA object from the given public key
rsaCryptoServiceProvider.FromXmlString(publicKey);
// convert data to byte array
bytesToEncrypt = Encoding.Unicode.GetBytes(data);
// get length of byte array
dataLength = bytesToEncrypt.Length;
// convert length of key from bits to bytes
keySize = (int)length / 8;
// .NET RSACryptoServiceProvider uses SHA1 Hash function
// use this to work out the maximum length to encrypt per block
maxLength = ((keySize - 2) - (2 * SHA1.Create().ComputeHash(bytesToEncrypt).Length));
// how many blocks do we need to encrypt?
iterations = dataLength / maxLength;
// encrypt block by block
for (int index = 0; index <= iterations; index++)
{
// is there more than one full block of data left to encrypt?
if ((dataLength - maxLength * index) > maxLength)
{
block = new byte[maxLength];
}
else
{
block = new byte[dataLength - maxLength * index];
}
// copy the required number of bytes from the array of bytes to encrypt to our worker array
Buffer.BlockCopy(bytesToEncrypt, maxLength * index, block, 0, block.Length);
// encrypt the current worker array block of bytes
encryptedBytes = rsaCryptoServiceProvider.Encrypt(block, true);
// RSACryptoServiceProvider reverses the order of encrypted bytesToEncrypt after encryption and before decryption.
// Undo this reversal for compatibility with other implementations
Array.Reverse(encryptedBytes);
// convert to base 64 string
encryptedData.Append(Convert.ToBase64String(encryptedBytes));
}
return encryptedData.ToString();
}
示例15: StartListening
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[16000];
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
// Console.ReadLine();
string answer = null;
byte[] aesKey = null;
answer = Console.ReadLine();
if (answer == "gen")
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
string rsaKey = rsa.ToXmlString(true);
File.WriteAllText("c:\\private.txt", rsaKey);
Console.Write("Ключи RSA были успешно сгенерированы и сохранены.\n\n");
}
Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
answer = Console.ReadLine();
if (answer == "enc")
{
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Ожидание соединения...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
Console.Write("Нажмите Enter, чтобы выбрать файл для отправки");
Console.Read();
OpenFileDialog dlg = new OpenFileDialog();
dlg.AddExtension = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
{
myAes.KeySize = 256;
myAes.GenerateKey();
// myAes.Padding = PaddingMode.None;
aesKey = myAes.Key;
Console.WriteLine(dlg.FileName);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(File.ReadAllText("c:\\private.txt"));
byte[] df = rsa.Encrypt(myAes.Key, false);
byte[] mes = Encoding.ASCII.GetBytes("{Key}");
byte[] newArray = new byte[df.Length + mes.Length];
Array.Copy(mes, 0, newArray, 0, mes.Length);
Array.Copy(df, 0, newArray, mes.Length, df.Length);
handler.Send(newArray);
}
}
Thread.Sleep(1000);
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
if (data.IndexOf("Ключ") > -1)
{
Console.Write("\nКлюч был успешно отправлен!\n");
byte[] encMes = EncryptFile(dlg.FileName, aesKey);
handler.Send(encMes);
Console.Write("\nФайл был успешно зашифрован и отправлен!\n");
handler.Shutdown(SocketShutdown.Both);
handler.Close();
break;
}
}
//Thread.Sleep(1000);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("\nНажмите Enter для продолжения\n");
Console.Read();
}