本文整理汇总了C#中System.Security.Cryptography.RSACryptoServiceProvider.Encrypt方法的典型用法代码示例。如果您正苦于以下问题:C# RSACryptoServiceProvider.Encrypt方法的具体用法?C# RSACryptoServiceProvider.Encrypt怎么用?C# RSACryptoServiceProvider.Encrypt使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.RSACryptoServiceProvider
的用法示例。
在下文中一共展示了RSACryptoServiceProvider.Encrypt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EncryptionKeyRequest
public static void EncryptionKeyRequest(MinecraftClient client, IPacket _packet)
{
var packet = (EncryptionKeyRequestPacket)_packet;
var random = RandomNumberGenerator.Create();
client.SharedSecret = new byte[16];
random.GetBytes(client.SharedSecret); // Generate a secure AES key
if (packet.ServerId != "-") // Online mode
{
// Authenticate with minecraft.net
var data = Encoding.ASCII.GetBytes(packet.ServerId)
.Concat(client.SharedSecret)
.Concat(packet.PublicKey).ToArray();
var hash = Cryptography.JavaHexDigest(data);
var webClient = new WebClient();
string result = webClient.DownloadString("http://session.minecraft.net/game/joinserver.jsp?user=" +
Uri.EscapeUriString(client.Session.Username) +
"&sessionId=" + Uri.EscapeUriString(client.Session.SessionId) +
"&serverId=" + Uri.EscapeUriString(hash));
if (result != "OK")
LogProvider.Log("Unable to verify session: " + result);
}
var parser = new AsnKeyParser(packet.PublicKey);
var key = parser.ParseRSAPublicKey();
// Encrypt shared secret and verification token
var crypto = new RSACryptoServiceProvider();
crypto.ImportParameters(key);
var encryptedSharedSecret = crypto.Encrypt(client.SharedSecret, false);
var encryptedVerification = crypto.Encrypt(packet.VerificationToken, false);
var response = new EncryptionKeyResponsePacket(encryptedSharedSecret, encryptedVerification);
client.SendPacket(response);
}
示例2: btnAsimEncriptar_Click
/// <summary>
/// Genera _bytEncriptado: Es unByte[] con el contenido de llavePublica RSA encriptada (bytes) y contenido Encriptado Simetrico
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAsimEncriptar_Click(object sender, EventArgs e)
{
byte[] _bytEncriptado = null;
System.Security.Cryptography.CspParameters csp = new CspParameters();
csp.KeyContainerName = "pepe";
//Creamos una instancia del encritador publico
RSACryptoServiceProvider _objEncriptadorPublicoRSA = new RSACryptoServiceProvider(csp);
//Le asignamos la llave genarada
_objEncriptadorPublicoRSA.FromXmlString(this.txtAsimLlavePublica.Text);
if (this.chkSimetrica.Checked)
{
//Se declara la memoria para almacenar la llave utilizada por nuestro Rijndael personalizado
byte[] _bytKey = (Rijndael.Create()).Key;
//Se encripta el texto y se obtiene la llave que se utilizó para la encriptación
byte[] _contenidoEncriptadoSimetrico = MiRijndael.Encriptar(this.txtAsimAEncriptar.Text, _bytKey);
//Se encripta la llave con el algoritmo RSA
byte[] llaveEncriptadaRSA = _objEncriptadorPublicoRSA.Encrypt(_bytKey, false);
#region Se copia en un vector la llave encriptada y el contenido encriptado Simetrico (Rijndael)
_bytEncriptado = new byte[llaveEncriptadaRSA.Length + _contenidoEncriptadoSimetrico.Length];
llaveEncriptadaRSA.CopyTo(_bytEncriptado, 0);
_contenidoEncriptadoSimetrico.CopyTo(_bytEncriptado, llaveEncriptadaRSA.Length);
#endregion
}
else
{
_bytEncriptado = _objEncriptadorPublicoRSA.Encrypt(System.Text.Encoding.UTF8.GetBytes(this.txtAsimAEncriptar.Text), false);
}
this.txtAsimEncriptado.Text = Convert.ToBase64String(_bytEncriptado);
}
示例3: HandlePacket
public override void HandlePacket(Proxy proxy)
{
// Interact with the remote server
proxy.RemoteSharedKey = new byte[16];
RandomNumberGenerator random = RandomNumberGenerator.Create();
random.GetBytes(proxy.RemoteSharedKey);
AsnKeyParser keyParser = new AsnKeyParser(PublicKey);
var key = keyParser.ParseRSAPublicKey();
var cryptoService = new RSACryptoServiceProvider();
cryptoService.ImportParameters(key);
byte[] encryptedSharedSecret = cryptoService.Encrypt(proxy.RemoteSharedKey, false);
byte[] encryptedVerify = cryptoService.Encrypt(VerifyToken, false);
// Construct an 0xFC packet to send the server
proxy.RemoteEncryptionResponse = new byte[] { 0xFC }
.Concat(DataUtility.CreateInt16((short)encryptedSharedSecret.Length))
.Concat(encryptedSharedSecret)
.Concat(DataUtility.CreateInt16((short)encryptedVerify.Length))
.Concat(encryptedVerify).ToArray();
if (ServerId != "-")
{
// Generate session hash
byte[] hashData = Encoding.ASCII.GetBytes(ServerId)
.Concat(proxy.RemoteSharedKey)
.Concat(PublicKey).ToArray();
var hash = Cryptography.JavaHexDigest(hashData);
var webClient = new WebClient();
string result = webClient.DownloadString("http://session.minecraft.net/game/joinserver.jsp?user=" +
Uri.EscapeUriString(proxy.Settings.Username) +
"&sessionId=" + Uri.EscapeUriString(proxy.Settings.UserSession) +
"&serverId=" + Uri.EscapeUriString(hash));
if (result != "OK")
Console.WriteLine("Warning: Unable to login as user " + proxy.Settings.Username + ", expect mixed results.");
}
// Interact with the local client
var verifyToken = new byte[4];
var csp = new RNGCryptoServiceProvider();
csp.GetBytes(verifyToken);
AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(Proxy.ServerKey);
// Construct an 0xFD to send the client
byte[] localPacket = new[] { PacketId }
.Concat(DataUtility.CreateString("-"))
.Concat(DataUtility.CreateInt16((short)encodedKey.GetBytes().Length))
.Concat(encodedKey.GetBytes())
.Concat(DataUtility.CreateInt16((short)verifyToken.Length))
.Concat(verifyToken).ToArray();
proxy.LocalSocket.BeginSend(localPacket, 0, localPacket.Length, SocketFlags.None, null, null);
base.HandlePacket(proxy);
}
示例4: RSAEncrypt
/// <summary>
/// 由于RSA的rgb参数不能超过字符串长度为117,进行分截加密,获取公钥
/// </summary>
/// <param name="str">The STR.</param>
/// <returns></returns>
public static string RSAEncrypt(string str, string publcikeypath)
{
string ls_str = string.Empty;
string ls_temp = string.Empty;
string ls_encrypt_str = string.Empty;
string publickey;
byte[] byte_encrypt;
int ll_num = 0;
ls_str = str;
System.Text.Encoding utf8 = new System.Text.UTF8Encoding();
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
try
{
StreamReader reader = new StreamReader(publcikeypath);
publickey = reader.ReadToEnd();
RSA.FromXmlString(publickey);
}
catch (Exception ex)
{
MessageBox.Show("加密文件没有在当前执行目录:" + ex.Message);
return string.Empty;
}
if (ls_str == string.Empty || ls_str == "")
return ls_encrypt_str;
do
{
if (ls_str.Length > 100)
{
ls_temp = ls_str.Substring(0, 100);
ls_str = ls_str.Substring(100);
byte_encrypt = utf8.GetBytes(ls_temp);
byte_encrypt = RSA.Encrypt(byte_encrypt, false);
ls_temp = System.Convert.ToBase64String(byte_encrypt);
ll_num = ll_num + 1;
ls_encrypt_str = ls_encrypt_str + "<" + ll_num.ToString() + ">" + ls_temp + "</" + ll_num.ToString() + ">";
}
else
{
ls_temp = ls_str;
byte_encrypt = utf8.GetBytes(ls_temp);
byte_encrypt = RSA.Encrypt(byte_encrypt, false);
ls_temp = System.Convert.ToBase64String(byte_encrypt);
ll_num = ll_num + 1;
ls_encrypt_str = ls_encrypt_str + "<" + ll_num.ToString() + ">" + ls_temp + "</" + ll_num.ToString() + ">";
break;
}
} while (2 > 1);
return ls_encrypt_str;
}
示例5: EncryptCode
public static NCryptoParms EncryptCode(string decData, string spKey) {
NCryptoParms parms = new NCryptoParms();
ICryptoTransform encryptor;
CryptoStream cStream;
MemoryStream mStream = new MemoryStream();
try {
// Generate a new RSA public/private key pair
// This key will be used to signature the DES IV and Key.
RSACryptoServiceProvider jRsa = new RSACryptoServiceProvider();
byte[] signature = jRsa.SignData(sign, new MD5CryptoServiceProvider());
parms.jpbkey =
Convert.ToBase64String(Encoding.ASCII.GetBytes(jRsa.ToXmlString(false)));
parms.jprkey =
Convert.ToBase64String(Encoding.ASCII.GetBytes(jRsa.ToXmlString(true)));
parms.signature = Convert.ToBase64String(signature);
jRsa.Clear();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(
Encoding.ASCII.GetString(Convert.FromBase64String(spKey)));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.GenerateIV();
des.GenerateKey();
parms.key = Convert.ToBase64String(rsa.Encrypt(des.Key, false));
parms.iv = Convert.ToBase64String(rsa.Encrypt(des.IV, false));
encryptor = des.CreateEncryptor(des.Key, des.IV);
cStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write);
byte[] bytesIn = Encoding.ASCII.GetBytes(decData);
cStream.Write(bytesIn, 0, bytesIn.Length);
cStream.FlushFinalBlock();
cStream.Close();
byte[] bytesOut = mStream.ToArray();
mStream.Close();
parms.enc = Convert.ToBase64String(bytesOut);
} catch {
mStream.Close();
}
return parms;
}
示例6: DoEncryption
public void DoEncryption()
{
// create a symmetric encryptor
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider ();
// create IV and Key need for symmetric encryption
TDES.GenerateIV();
TDES.GenerateKey();
// create an asymmetric encryptor
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider ();
string AsymKeys = RSA.ToXmlString (true);
// export the public and private keys to a file
WriteKeyToFile(AsymKeys);
// asymmetric encryption is good for
// small data, hence, we use it to encrypted
// IV and Key for symmetric encryption
byte[] encryptedIV = RSA.Encrypt(TDES.IV, false);
byte[] encryptedKey = RSA.Encrypt(TDES.Key, false);
// convert the length of IV and Key (e.g. number of bytes used)
// into a byte, e.g. 4 to 0000 0100
// as default length of a Integer in .NET is 32,
// the result byte length should be 4 bytes, i.e. 32/8
byte[] IVSize = BitConverter.GetBytes(encryptedIV.Length);
byte[] keySize = BitConverter.GetBytes(encryptedKey.Length);
// write out the IV length, the key length,
// the encrypted iv, the encrypted key and the actual
// date to a file using the symmetric encryptor.
using(FileStream ostream = new FileStream("encrypted.enc", FileMode.Create)){
ostream.Write(IVSize, 0, IVSize.Length);
ostream.Write(keySize, 0, keySize.Length);
ostream.Write(encryptedIV, 0, encryptedIV.Length);
ostream.Write(encryptedKey, 0, encryptedKey.Length);
CryptoStream cstream = new CryptoStream(ostream,
TDES.CreateEncryptor(),
CryptoStreamMode.Write);
// encrypt the data using the crypto stream
EncryptFile(cstream);
// close streams
cstream.Close();
ostream.Close();
}
}
示例7: EncryptString
public string EncryptString(string inputString, int dwKeySize,
string xmlString)
{
RSACryptoServiceProvider rsaCryptoServiceProvider =
new RSACryptoServiceProvider(dwKeySize);
rsaCryptoServiceProvider.FromXmlString(xmlString);
int keySize = dwKeySize / 8;
byte[] bytes = Encoding.UTF32.GetBytes(inputString);
int maxLength = keySize - 42;
int dataLength = bytes.Length;
int iterations = dataLength / maxLength;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i <= iterations; i++)
{
byte[] tempBytes = new byte[
(dataLength - maxLength * i > maxLength) ? maxLength :
dataLength - maxLength * i];
Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0,
tempBytes.Length);
byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes,
true);
Array.Reverse(encryptedBytes);
stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
}
return stringBuilder.ToString();
}
示例8: MainAsync
static async Task MainAsync(string[] args)
{
var keyClient = new KeyVaultClient((authority, resource, scope) =>
{
var adCredential = new ClientCredential(applicationId, applicationSecret);
var authenticationContext = new AuthenticationContext(authority, null);
return authenticationContext.AcquireToken(resource, adCredential).AccessToken;
});
// Get the key details
var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784";
var key = await keyClient.GetKeyAsync(keyIdentifier);
var publicKey = Convert.ToBase64String(key.Key.N);
using (var rsa = new RSACryptoServiceProvider())
{
var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E };
rsa.ImportParameters(p);
var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
// Encrypt and Decrypt
var encryptedText = rsa.Encrypt(byteData, true);
var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText);
var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);
// Sign and Verify
var hasher = new SHA256CryptoServiceProvider();
var digest = hasher.ComputeHash(byteData);
var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result);
}
}
示例9: RSAEncrypt
static public byte[] RSAEncrypt(int bits, byte[] dataToEncrypt, RSAParameters rsaKeyInfo, bool doOAEPPadding)
{
try
{
byte[] encryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (var rsa = new RSACryptoServiceProvider(bits))
{
//Import the RSA Key information. This only needs
//toinclude the public key information.
rsa.ImportParameters(rsaKeyInfo);
var rsaExportParameters = rsa.ExportParameters(true);
var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
rsaFormatter.SetHashAlgorithm("SHA256");
//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
encryptedData = rsa.Encrypt(dataToEncrypt, doOAEPPadding);
}
return encryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
示例10: EncryptString
public string EncryptString( string inputString, int dwKeySize, string xmlString )
{
// TODO: Add Proper Exception Handlers
RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider( dwKeySize );
rsaCryptoServiceProvider.FromXmlString( xmlString );
int keySize = dwKeySize / 8;
byte[] bytes = Encoding.UTF32.GetBytes( inputString );
// The hash function in use by the .NET RSACryptoServiceProvider here is SHA1
// int maxLength = ( keySize ) - 2 - ( 2 * SHA1.Create().ComputeHash( rawBytes ).Length );
int maxLength = keySize - 42;
int dataLength = bytes.Length;
int iterations = dataLength / maxLength;
StringBuilder stringBuilder = new StringBuilder();
for( int i = 0; i <= iterations; i++ )
{
byte[] tempBytes = new byte[ ( dataLength - maxLength * i > maxLength ) ? maxLength : dataLength - maxLength * i ];
Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, tempBytes.Length );
byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes, true );
// Be aware the RSACryptoServiceProvider reverses the order of encrypted bytes after encryption and before decryption.
// If you do not require compatibility with Microsoft Cryptographic API (CAPI) and/or other vendors.
// Comment out the next line and the corresponding one in the DecryptString function.
Array.Reverse( encryptedBytes );
// Why convert to base 64?
// Because it is the largest power-of-two base printable using only ASCII characters
stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) );
}
return stringBuilder.ToString();
}
示例11: AsymetriycCrypt
/// <summary>
/// Metoda za asimetrično kriptiranje
/// </summary>
/// <param name="file"></param>
public void AsymetriycCrypt(string file)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader streamReader = new StreamReader("javni_kljuc.txt");
string publicKey = streamReader.ReadToEnd();
rsa.FromXmlString(publicKey);
streamReader.Close();
string record = file + ".rsa";
FileStream fstreamU = File.OpenRead(file),
fstreamO = new FileStream(record, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fstreamO);
BinaryReader binReader = new BinaryReader(fstreamU);
byte[] bytes = binReader.ReadBytes((int)fstreamU.Length);
binReader.Close();
byte[] crypt = rsa.Encrypt(bytes, false);
bw.Write(crypt);
bw.Flush();
bw.Close();
bw.Dispose();
fstreamU.Close();
fstreamU.Dispose();
}
示例12: Encrypt
//static RSACryptoServiceProvider RSA;
//public static void ExportParameters()
//{
// var publicKey = RSA.ExportParameters(false);
// // +Exponent { byte[3]}
// //+Modulus { byte[256]}
//}
public async Task<byte[]> Encrypt(byte[] Exponent, byte[] Modulus)
{
// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201503/20150323
// encrypted state sharing.
// what about import?
// http://bouncy-castle.1462172.n4.nabble.com/Interoperability-issue-with-SunJCE-OAEP-td4656157.html
// http://www.w3.org/TR/WebCryptoAPI/#rsa-oaep
// RSA/ECB/OAEPWithSHA-1AndMGF1Padding
// X:\jsc.svn\examples\java\hybrid\JVMCLRCryptoKeyExport\JVMCLRCryptoKeyExport\Program.cs
//var n = new RSACryptoServiceProvider(2048);
var n = new RSACryptoServiceProvider();
// can we import in java android?
n.ImportParameters(
new RSAParameters { Exponent = Exponent, Modulus = Modulus }
);
// http://stackoverflow.com/questions/9839274/rsa-encryption-by-supplying-modulus-and-exponent
var value = n.Encrypt(
Encoding.UTF8.GetBytes("hello from server"), fOAEP: true
);
//Array.Reverse(value);
return value;
}
示例13: Test
public static Boolean Test(int keySize)
{
Boolean bRes = true;
Byte[] abPlain = { 0, 1, 2, 3, 4, 5, 6, 7 };
Byte[] abCipher = null;
int kl = keySize;
try
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(kl))
{
abCipher = rsa.Encrypt(abPlain);
Log.Comment("Cipher is : ");
PrintByteArray(abCipher);
abCipher = rsa.Decrypt(abCipher);
}
Log.Comment("Decrypted plaintext is : ");
PrintByteArray(abCipher);
if (!Compare(abPlain, abCipher))
{
bRes = false;
Log.Comment("Failed to decrypt to the original plaintext");
}
}
catch (Exception e)
{
Log.Comment("Exception ocured :\n" + e.ToString());
bRes = false;
}
return bRes;
}
示例14: Encript
// 暗号化
public static byte[] Encript(String publicKey, byte[] src)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
return rsa.Encrypt(src, false);
}
示例15: EncryptString
/// <summary>
/// RSA 加密
/// </summary>
/// <param name="sSource" >明文</param>
/// <param name="sPublicKey" >公钥</param>
public static string EncryptString(string sSource, string sPublicKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string plaintext = sSource;
rsa.FromXmlString(sPublicKey);
byte[] cipherbytes;
byte[] byteEn = rsa.Encrypt(Encoding.UTF8.GetBytes("a"), false);
cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(plaintext), false);
StringBuilder sbString = new StringBuilder();
for (int i = 0; i < cipherbytes.Length; i++)
{
sbString.Append(cipherbytes[i] + ",");
}
return sbString.ToString();
}