本文整理汇总了C#中System.Security.Cryptography.RSACryptoServiceProvider类的典型用法代码示例。如果您正苦于以下问题:C# RSACryptoServiceProvider类的具体用法?C# RSACryptoServiceProvider怎么用?C# RSACryptoServiceProvider使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RSACryptoServiceProvider类属于System.Security.Cryptography命名空间,在下文中一共展示了RSACryptoServiceProvider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Decrypt
public static string Decrypt(this string stringToDecrypt, string key)
{
if (string.IsNullOrEmpty(stringToDecrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
}
//var cspp = new CspParameters { KeyContainerName = key };
var cspp = new CspParameters { KeyContainerName = key, Flags = CspProviderFlags.UseMachineKeyStore };
var rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true };
var decryptArray = stringToDecrypt.Split(new[] { "-" }, StringSplitOptions.None);
var decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));
byte[] bytes = rsa.Decrypt(decryptByteArray, true);
string result = System.Text.Encoding.UTF8.GetString(bytes);
return result;
}
示例2: DecodeToken
public IHttpActionResult DecodeToken(string access_token)
{
var tokenReceived = new JwtSecurityToken(access_token);
var publicOnly = new RSACryptoServiceProvider();
publicOnly.FromXmlString(_configuration.PublicKey.FromBase64String());
var validationParameters = new TokenValidationParameters
{
ValidIssuer = _configuration.Issuer
,ValidAudience = "http://mysite.com"
,IssuerSigningToken = new RsaSecurityToken(publicOnly)
,ValidateLifetime = true
};
var recipientTokenHandler = new JwtSecurityTokenHandler();
SecurityToken securityToken;
var claimsPrincipal = recipientTokenHandler.ValidateToken(access_token, validationParameters, out securityToken);
var currentTime = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
if (tokenReceived.Payload.Exp < currentTime)
{
throw new SecurityTokenValidationException(string.Format("Lifetime validation failed. The token is expired. ValidTo: '{0}' Current time: '{1}'.", tokenReceived.ValidTo, DateTime.UtcNow));
}
return Ok(new
{
header = tokenReceived.Header,
payload = tokenReceived.Payload,
current = currentTime
});
}
示例3: CreateToken
public async Task<IHttpActionResult> CreateToken(Token token)
{
var publicAndPrivate = new RSACryptoServiceProvider();
publicAndPrivate.FromXmlString(_configuration.PrivateKey.FromBase64String());
var jwtToken = new JwtSecurityToken(
issuer: _configuration.Issuer,
audience: "http://mysite.com"
, claims: new List<Claim>() { new Claim(ClaimTypes.Name, token.username) }
, notBefore: DateTime.UtcNow
, expires: DateTime.UtcNow.AddMinutes(1)
, signingCredentials: new SigningCredentials(
new RsaSecurityKey(publicAndPrivate)
,SecurityAlgorithms.RsaSha256Signature
,SecurityAlgorithms.Sha256Digest)
);
var tokenHandler = new JwtSecurityTokenHandler();
var tokenString = tokenHandler.WriteToken(jwtToken);
return Ok(new
{
access_token = tokenString,
expires_in = new TimeSpan(0,0, 1,0).TotalSeconds,
expires_on = (long)(DateTime.UtcNow.AddMinutes(1) - new DateTime(1970, 1, 1)).TotalSeconds
});
}
示例4: GetCryptoProviderForSha256
// Copied from ACS code
// This method returns an AsymmetricSignatureFormatter capable of supporting Sha256 signatures.
private static RSACryptoServiceProvider GetCryptoProviderForSha256(RSACryptoServiceProvider rsaProvider)
{
const int PROV_RSA_AES = 24; // CryptoApi provider type for an RSA provider supporting sha-256 digital signatures
if (rsaProvider.CspKeyContainerInfo.ProviderType == PROV_RSA_AES)
{
return rsaProvider;
}
CspParameters csp = new CspParameters
{
ProviderType = PROV_RSA_AES,
KeyContainerName = rsaProvider.CspKeyContainerInfo.KeyContainerName,
KeyNumber = (int)rsaProvider.CspKeyContainerInfo.KeyNumber
};
if (rsaProvider.CspKeyContainerInfo.MachineKeyStore)
{
csp.Flags = CspProviderFlags.UseMachineKeyStore;
}
//
// If UseExistingKey is not specified, the CLR will generate a key for a non-existent group.
// With this flag, a CryptographicException is thrown instead.
//
csp.Flags |= CspProviderFlags.UseExistingKey;
return new RSACryptoServiceProvider(csp);
}
示例5: AssignNewKey
public void AssignNewKey()
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
//in memory
publicKey = rsa.ExportParameters(false);
privateKey = rsa.ExportParameters(true);
return;
//to file
File.WriteAllText(@"C:\git\CryptographyDemo\CryptographyDemo\bin\Debug\public.txt", rsa.ToXmlString(false));
File.WriteAllText(@"C:\git\CryptographyDemo\CryptographyDemo\bin\Debug\private.txt", rsa.ToXmlString(true));
}
//To key container, stored for windows user
const int providerRsaFull = 1;
CspParameters cspParams = new CspParameters(providerRsaFull);
cspParams.KeyContainerName = "TomsContainer";
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
var rsa2 = new RSACryptoServiceProvider(cspParams);
rsa2.PersistKeyInCsp = true;
// SHOULD THEN DELETE KEY
}
示例6: EncryptSomeText
static void EncryptSomeText()
{
string dataToBeEncrypted = "My secret text!";
Console.WriteLine("Original: {0}", dataToBeEncrypted);
var encryptedData = Encrypt(dataToBeEncrypted);
Console.WriteLine("Cipher data: {0}", encryptedData.Aggregate<byte, string>("", (s, b) => s += b.ToString()));
var decryptedString = Decrypt(encryptedData);
Console.WriteLine("Decrypted:{0}", decryptedString);
// As you can see, you first need to convert the data you want to encrypt to a byte sequence.
// To encrypt the data, you need only the public key.
// You then use the private key to decrypt the data.
// Because of this, it’s important to store the private key in a secure location.
// If you would store it in plain text on disk or even in a nonsecure memory location,
// your private key could be extracted and your security would be compromised.
// The .NET Framework offers a secure location for storing asymmetric keys in a key container.
// A key container can be specific to a user or to the whole machine.
// This example shows how to configure an RSACryptoServiceProvider to use a key container for saving and loading the asymmetric key.
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes(dataToBeEncrypted);
string containerName = "SecretContainer";
CspParameters csp = new CspParameters() { KeyContainerName = containerName };
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(csp))
{
var encryptedByteData = RSA.Encrypt(dataToEncrypt, false);
}
}
示例7: GenerateKeys
/// <summary>
/// Generate keys into specified files.
/// </summary>
/// <param name="publicKeyFileName">Name of the file that will contain public key</param>
/// <param name="privateKeyFileName">Name of the file that will contain private key</param>
public void GenerateKeys(out byte[] publicKey, out byte[] privateKey)
{
// Variables
CspParameters cspParams = null;
RSACryptoServiceProvider rsaProvider = null;
try
{
// Create a new key pair on target CSP
cspParams = new CspParameters()
{
ProviderType = 1, // PROV_RSA_FULL
Flags = CspProviderFlags.UseArchivableKey, // can be exported
KeyNumber = (int)KeyNumber.Exchange // can be safely stored and exchanged
};
rsaProvider = new RSACryptoServiceProvider(cspParams);
rsaProvider.PersistKeyInCsp = false;
// Export public key only
publicKey = rsaProvider.ExportCspBlob(false);
privateKey = rsaProvider.ExportCspBlob(true);
}
catch (Exception ex)
{
Debug.Fail(string.Format("Exception occured while generating keys: {0}", ex.Message));
publicKey = null;
privateKey = null;
}
finally
{
if (rsaProvider != null) rsaProvider.PersistKeyInCsp = false;
}
}
示例8: AsymmetricCryptoKeyStoreWrapper
/// <summary>
/// Initializes a new instance of the <see cref="AsymmetricCryptoKeyStoreWrapper"/> class.
/// </summary>
/// <param name="dataStore">The data store.</param>
/// <param name="asymmetricCrypto">The asymmetric protection to apply to symmetric keys. Must include the private key.</param>
public AsymmetricCryptoKeyStoreWrapper(ICryptoKeyStore dataStore, RSACryptoServiceProvider asymmetricCrypto) {
Contract.Requires<ArgumentNullException>(dataStore != null);
Contract.Requires<ArgumentNullException>(asymmetricCrypto != null);
Contract.Requires<ArgumentException>(!asymmetricCrypto.PublicOnly);
this.dataStore = dataStore;
this.asymmetricCrypto = asymmetricCrypto;
}
示例9: btnEncrypt_Click
protected void btnEncrypt_Click(object sender, EventArgs e)
{
try
{
string dataToEncrypt = "revathis";
// byte[] inputData = null;
byte[] encryptedData;
// inputData= Convert.ToByte(dataToEncrypt);
using (RSACryptoServiceProvider rsaServiceProvider = new RSACryptoServiceProvider())
{
// dataToEncrypt
//inputData = rsaServiceProvider.
encryptedData= rsaServiceProvider.Encrypt(Encoding.ASCII.GetBytes(dataToEncrypt), false);
Response.Write("Encrypted Data: ");
foreach (byte byteItem in encryptedData)
{
Response.Write(byteItem);
}
}
}
catch (Exception)
{
throw;
}
}
示例10: GenerateFloatingLicense
/// <summary>
/// Floating 라이선스를 생성합니다.
/// 참고 : http://en.wikipedia.org/wiki/Floating_licensing
/// </summary>
/// <param name="privateKey">제품의 Private Key</param>
/// <param name="name">라이선스 명</param>
/// <param name="publicKey">제품의 Public Key</param>
/// <returns>Floating License의 XML 문자열</returns>
public static string GenerateFloatingLicense(string privateKey, string name, string publicKey) {
if(IsDebugEnabled)
log.Debug("Floating License를 생성합니다... privateKey=[{0}], name=[{1}], publicKey=[{2}]", privateKey, name, publicKey);
using(var rsa = new RSACryptoServiceProvider()) {
rsa.FromXmlString(privateKey);
var doc = new XmlDocument();
var licenseElement = doc.CreateElement(LicensingSR.FloatingLicense);
doc.AppendChild(licenseElement);
var publicKeyElement = doc.CreateElement(LicensingSR.LicenseServerPublicKey);
licenseElement.AppendChild(publicKeyElement);
publicKeyElement.InnerText = publicKey;
var nameElement = doc.CreateElement(LicensingSR.LicenseName);
licenseElement.AppendChild(nameElement);
nameElement.InnerText = name;
var signatureElement = GetXmlDigitalSignature(doc, rsa);
doc.FirstChild.AppendChild(doc.ImportNode(signatureElement, true));
using(var ms = new MemoryStream())
using(var xw = XmlWriter.Create(ms, new XmlWriterSettings
{
Indent = true,
Encoding = Encoding.UTF8
})) {
doc.Save(xw);
ms.Position = 0;
return new StreamReader(ms).ReadToEnd();
}
}
}
示例11: ProxyRsaKeyParameters
public ProxyRsaKeyParameters(RSACryptoServiceProvider proxy)
: base(false,
new Math.BigInteger(1, proxy.ExportParameters(false).Modulus),
new Math.BigInteger(1, proxy.ExportParameters(false).Exponent))
{
this.proxy = proxy;
}
示例12: AsymmetricCryptoKeyStoreWrapper
/// <summary>
/// Initializes a new instance of the <see cref="AsymmetricCryptoKeyStoreWrapper"/> class.
/// </summary>
/// <param name="dataStore">The data store.</param>
/// <param name="asymmetricCrypto">The asymmetric protection to apply to symmetric keys. Must include the private key.</param>
public AsymmetricCryptoKeyStoreWrapper(ICryptoKeyStore dataStore, RSACryptoServiceProvider asymmetricCrypto) {
Requires.NotNull(dataStore, "dataStore");
Requires.NotNull(asymmetricCrypto, "asymmetricCrypto");
Requires.True(!asymmetricCrypto.PublicOnly, "asymmetricCrypto");
this.dataStore = dataStore;
this.asymmetricCrypto = asymmetricCrypto;
}
示例13: OnConnect
protected override void OnConnect()
{
base.OnConnect();
m_rsa = new RSACryptoServiceProvider();
RSAParameters para = m_rsa.ExportParameters(false);
SendRSAKey(para.Modulus, para.Exponent);
}
示例14: 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;
}
示例15: RSAEncrypt
public static string RSAEncrypt(string source, string xmlKey) {
using (var rsa = new RSACryptoServiceProvider(1024)) {
rsa.FromXmlString(xmlKey);
var encrypted = rsa.Encrypt(Encoding.UTF8.GetBytes(source), false);
return BytesToHex(encrypted);
}
}