本文整理汇总了C#中System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters方法的典型用法代码示例。如果您正苦于以下问题:C# RSACryptoServiceProvider.ImportParameters方法的具体用法?C# RSACryptoServiceProvider.ImportParameters怎么用?C# RSACryptoServiceProvider.ImportParameters使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.RSACryptoServiceProvider
的用法示例。
在下文中一共展示了RSACryptoServiceProvider.ImportParameters方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateTokenWithTimeRemaining
public static D2LSecurityToken CreateTokenWithTimeRemaining(
TimeSpan remaining,
Guid? id = null
) {
id = id ?? Guid.NewGuid();
var validTo = DateTime.UtcNow + remaining;
var validFrom = validTo - TimeSpan.FromHours( 1 );
RSAParameters privateKey;
using( var csp = new RSACryptoServiceProvider( Keys.Constants.GENERATED_RSA_KEY_SIZE ) {
PersistKeyInCsp = false
} ) {
privateKey = csp.ExportParameters( includePrivateParameters: true );
}
return new D2LSecurityToken(
id.Value,
validFrom,
validTo,
keyFactory: () => {
var csp = new RSACryptoServiceProvider() { PersistKeyInCsp = false };
csp.ImportParameters( privateKey );
var key = new RsaSecurityKey( csp );
return new Tuple<AsymmetricSecurityKey, IDisposable>( key, csp );
}
);
}
示例2: 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);
}
示例3: Encrpyt
private readonly static RSAParameters PrivateParams = Rsa.ExportParameters(true); //Complete key pairs.
/// <summary>
/// Encrypt an input string
/// </summary>
/// <param name="input">the input string to be encrpty</param>
/// <param name="signature">the private key signature</param>
/// <returns>A Base 64 encrypted string or empty if can't encrpyt</returns>
public static string Encrpyt(string input, out byte[] signature)
{
signature = null;
try
{
if (string.IsNullOrEmpty(input)) return string.Empty;
var provider = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore });
provider.ImportParameters(PublicParams);
var buffer = Encoding.ASCII.GetBytes(input);
var encryptedbuffer = provider.Encrypt(buffer, false);
var hash = new SHA1Managed();
provider.ImportParameters(PrivateParams);
var hashedData = hash.ComputeHash(encryptedbuffer);
signature = provider.SignHash(hashedData, CryptoConfig.MapNameToOID("SHA1"));
var stringBuilder = new StringBuilder();
stringBuilder.Append(Convert.ToBase64String(encryptedbuffer));
return stringBuilder.ToString();
}
catch
{
return string.Empty;
}
}
示例4: rsa2
public static RSAViewModel rsa2(RSAViewModel model)
{
try
{
int keySize = 1024;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize);
RSAParameters publickey = rsa.ExportParameters(false); // don't export private key
RSAParameters privatekey = rsa.ExportParameters(true); // export private key
//\b 123\b0
model.PublicKey = "e=" + ByteToString(publickey.Exponent) + Environment.NewLine + "n=" + ByteToString(publickey.Modulus);
model.PrivateKey = "d=" + ByteToString(privatekey.D) + Environment.NewLine + "n=" + ByteToString(publickey.Modulus);
rsa.ImportParameters(publickey);
byte[] encryptedData = rsa.Encrypt(StringToByte(model.PlainText), true);
model.CipherText=ByteToString(encryptedData);
rsa.ImportParameters(privatekey);
byte[] decryptedData = rsa.Decrypt(encryptedData, true);
model.DecryptedText = ByteToAscii(decryptedData);
}
catch (CryptographicException ex)
{
}
return model;
}
示例5: DecryptPublicRSA
public static string DecryptPublicRSA(string input, string key, bool KeyIsPublic)
{
SysCrypt.RSACryptoServiceProvider rsa = new SysCrypt.RSACryptoServiceProvider();
if (!KeyIsPublic)
{
rsa.ImportParameters(GetPrivateKeyParams(key));
SysCrypt.RSAParameters p = rsa.ExportParameters(false);
rsa.ImportParameters(p);
}
else
rsa.ImportParameters(GetPublicKeyParams(key));
return DoDecrypt(input, rsa);
}
示例6: EncryptData
public string EncryptData(string data)
{
try
{
//initialze the byte arrays to the public key information.
byte[] PublicKey = _publicKey.ToArray();
byte[] Exponent = _exponent.ToArray();
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Create a new instance of RSAParameters.
RSAParameters RSAKeyInfo = new RSAParameters();
//Set RSAKeyInfo to the public key values.
RSAKeyInfo.Modulus = PublicKey;
RSAKeyInfo.Exponent = Exponent;
//Import key parameters into RSA.
RSA.ImportParameters(RSAKeyInfo);
var dataBytes = ASCIIEncoding.ASCII.GetBytes(data);
var encryptedBytes = RSA.Encrypt(dataBytes, false);
var encryptedValue = BitConverter.ToString(encryptedBytes).Replace("-", "").ToLower();
return encryptedValue;
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
return null;
}
示例7: Encrypt
public override void Encrypt()
{
//RSA Rsa = new RSA();
//base.Component.Text = Rsa.encode(base.Component.tp.Text);
try
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] encryptedData;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.ImportParameters(RSA.ExportParameters(false));
byte[] Data = ByteConverter.GetBytes(base.Component.tp.Text.ToString());
encryptedData = RSA.Encrypt(Data , false);
}
base.Component.Text = ByteConverter.GetString(encryptedData);
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
base.Component.Text = base.Component.tp.Text.ToString();
}
}
示例8: SignData
public static string SignData(byte[] message, RSAParameters privateKey)
{
//// The array to store the signed message in bytes
byte[] signedBytes;
using (var rsa = new RSACryptoServiceProvider())
{
byte[] originalData = message;
try
{
//// Import the private key used for signing the message
rsa.ImportParameters(privateKey);
//// Sign the data, using SHA512 as the hashing algorithm
signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
//// Set the keycontainer to be cleared when rsa is garbage collected.
rsa.PersistKeyInCsp = false;
}
}
//// Convert the a base64 string before returning
return Convert.ToBase64String(signedBytes);
}
示例9: RSADecrypt
static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
byte[] decryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);
//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
return decryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}
示例10: ToPEM
public static string ToPEM (RSAKeyPair RSAKeyPair) {
var Provider = RSAKeyPair.Provider;
Assert.Null(Provider, NoProviderSpecified.Throw);
var RSAParameters = Provider.ExportParameters(true);
Assert.Null(RSAParameters, PrivateKeyNotAvailable.Throw);
var NewProvider = new RSACryptoServiceProvider();
NewProvider.ImportParameters(RSAParameters);
RSAParameters.Dump();
var RSAPrivateKey = new RSAPrivateKey(RSAParameters);
var Builder = new StringBuilder();
Builder.Append("-----BEGIN RSA PRIVATE KEY-----");
var KeyDER = RSAPrivateKey.DER();
Builder.AppendBase64(KeyDER);
Builder.Append("\n-----END RSA PRIVATE KEY-----\n");
return Builder.ToString();
}
示例11: 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);
}
}
示例12: Main
static void Main(string[] args)
{
// Create message and signature on your end
string message = "Here is the license message";
var secret = "wangchunlei";
var converter = new ASCIIEncoding();
byte[] plainText = converter.GetBytes(secret);
var rsaWrite = new RSACryptoServiceProvider();
var privateParams = rsaWrite.ExportParameters(true);
// Generate the public key / these can be sent to the user.
var publicParams = rsaWrite.ExportParameters(false);
byte[] signature =
rsaWrite.SignData(plainText, new SHA1CryptoServiceProvider());
// Verify from the user's side. Note that only the public parameters
// are needed.
var rsaRead = new RSACryptoServiceProvider();
rsaRead.ImportParameters(publicParams);
if (rsaRead.VerifyData(plainText,
new SHA1CryptoServiceProvider(),
signature))
{
Console.WriteLine("Verified!");
}
else
{
Console.WriteLine("NOT verified!");
}
}
示例13: verify
public bool verify(byte[] sig)
{
m_cs.Close();
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.ImportParameters(m_RSAKeyInfo);
RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA);
RSADeformatter.SetHashAlgorithm("SHA1");
long i = 0;
long j = 0;
byte[] tmp;
if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0)
{
long i1 = (sig[i++] << 24) & 0xff000000;
long i2 = (sig[i++] << 16) & 0x00ff0000;
long i3 = (sig[i++] << 8) & 0x0000ff00;
long i4 = (sig[i++]) & 0x000000ff;
j = i1 | i2 | i3 | i4;
i += j;
i1 = (sig[i++] << 24) & 0xff000000;
i2 = (sig[i++] << 16) & 0x00ff0000;
i3 = (sig[i++] << 8) & 0x0000ff00;
i4 = (sig[i++]) & 0x000000ff;
j = i1 | i2 | i3 | i4;
tmp = new byte[j];
Array.Copy(sig, i, tmp, 0, j);
sig = tmp;
}
return RSADeformatter.VerifySignature(m_sha1, sig);
}
示例14: btnOK_Click
private void btnOK_Click(object sender, EventArgs e)
{
try
{
using (MemoryStream mS = new MemoryStream(Encoding.UTF8.GetBytes(txtRSAKey.Text)))
{
_parameters = PEMFormat.ReadRSAPrivateKey(mS);
}
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(_parameters);
if (rsa.KeySize < 4096)
{
MessageBox.Show("The RSA private key must be at least 4096-bit. The current key is " + rsa.KeySize + "-bit.", "Short RSA Private Key", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
catch
{
MessageBox.Show("Error in reading PEM format. Please make sure you have pasted the RSA private key in a proper PEM format.", "Invalid PEM Format", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例15: IsValid
/// <summary>
/// Проверяет, действительна ли лицензия.
/// Это включает проверку подписи на ней,
/// а также сроков ее действия.
/// </summary>
/// <param name="license">Лицензия</param>
/// <returns>true если лицензия действительна. Иначе false.</returns>
public bool IsValid(LicenseInfo license)
{
if (license == null)
throw new ArgumentNullException("license cannot be null");
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(_publicKey);
if (!rsa.VerifyData(
GetBytesToSign(license),
"SHA1",
license.Signature
)
)
return false;
if (!(license.IssueDate <= DateTime.Now &&
DateTime.Now <= license.IssueDate + license.Duration)
)
return false;
}
catch
{
return false;
}
return true;
}