本文整理汇总了C#中System.Security.Cryptography.RSACryptoServiceProvider.FromXmlString方法的典型用法代码示例。如果您正苦于以下问题:C# RSACryptoServiceProvider.FromXmlString方法的具体用法?C# RSACryptoServiceProvider.FromXmlString怎么用?C# RSACryptoServiceProvider.FromXmlString使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.RSACryptoServiceProvider
的用法示例。
在下文中一共展示了RSACryptoServiceProvider.FromXmlString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: client_OnSymmetricAuthenticate
private static void client_OnSymmetricAuthenticate(ISocketConnection connection, out System.Security.Cryptography.RSACryptoServiceProvider serverKey)
{
//----- Using string!
//----- You must get the public key xml from the ALAZ certificate in you server machine.
//----- Uncomment the following lines to get the public key from certificate.
//---- Get certificate!
// X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
// store.Open(OpenFlags.ReadOnly);
// X509Certificate2 certificate = store.Certificates.Find(X509FindType.FindBySubjectName, "ALAZ Library", true)[0];
//---- Get public key string!
// string publicKey = certificate.PrivateKey.ToXmlString(false);
serverKey = new RSACryptoServiceProvider();
//----- Using string!
if (connection.Context.Host.Context.HostType == HostType.htClient)
{
serverKey.FromXmlString("<RSAKeyValue><Modulus>z2ksxSTLHSBjY4+IEz7TZU5EclOql5pphA9+xyNQ6c1rYW6VPAmXmiXZKmsza8N++YVLAGnzR95iYyr4oL+mBz8lbhjDH2iqyQL7utbW1s87WaDC2o+82dLnLvwEqBhWpnz4tC0v0kCKayH6Jj+30l3xLdgDwReWF7YEvp6yq6nGxHOeSiioPpTtJzNhWjKGnK6oSZqthfWHewlRl2hVIrewD+JbP5JYTp/7iYptOiCwNAUZEBxODR2743D56J1AeHNc8VpZNvE3ZozIoRFhnxZw0ZpvMbgPliKPyjPeOvOFeqZUJ2zkQ7sH+gnqt67QzkOzznfuFPmTpBo0tMheyw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");
}
else
{
serverKey.FromXmlString("<RSAKeyValue><Modulus>z2ksxSTLHSBjY4+IEz7TZU5EclOql5pphA9+xyNQ6c1rYW6VPAmXmiXZKmsza8N++YVLAGnzR95iYyr4oL+mBz8lbhjDH2iqyQL7utbW1s87WaDC2o+82dLnLvwEqBhWpnz4tC0v0kCKayH6Jj+30l3xLdgDwReWF7YEvp6yq6nGxHOeSiioPpTtJzNhWjKGnK6oSZqthfWHewlRl2hVIrewD+JbP5JYTp/7iYptOiCwNAUZEBxODR2743D56J1AeHNc8VpZNvE3ZozIoRFhnxZw0ZpvMbgPliKPyjPeOvOFeqZUJ2zkQ7sH+gnqt67QzkOzznfuFPmTpBo0tMheyw==</Modulus><Exponent>AQAB</Exponent><P>7IhXSag5zlV+Ary/KDsMinK2Jah/WdTov6Z2XAAPHB4zOGEbhCXdgTEkIrOJNpyobF6L7mR9sTnuV5pr+vWklKkYMbxUEK+KRYo4knUvxx5ED4lFE3KUGeVz6jJ1LY5FqmQT4RTtfwZa6dxRPSgn19/k6sOqyPnnalPz30CYFAk=</P><Q>4Hs/u3UIH+CB3yf2gpupXw5yxl82YX/GuB+ZIAYopM65UlukzFl8eW1iEu42gG/UOpjfmDje+wEvIZ5gcKGjGdDgRmEbAYKNt7X6LqkhIMQqUHt0vAsNrYDXgRFVHdd8YisZ62DzAyMM9nu6v0jPTmhlJSDJwpH3s9XbVy0rmTM=</Q><DP>IF7UW087ggJvOV6tZosWP0hNpz+1Fg0uQTQ91H9pkfaMGfYoNuCbvNeF033wlFnCLvqNefWkwgFknfaTOogtmu69UektNA9iA/xTm6+P91csB1hI7M1seVLOl0mKgc6LuDL0CYS8r/qlrIWrVIxPT5rjkEFw+QpCYmnU4UPMzEk=</DP><DQ>jy7OBfmuBvcin35UBBbZv6Htn45Xl3TzAbpV51FGV2jsWBXQVe+2L5WPeteqt92clwuvgt6zi5LDx0PH68+NwweyJfIGUb4+OrG+NEj4snetLcyxNsguHz8RNmghzHkIA23OiI48MwIGYKmnAh+k6zQ3X6k8R/jm8DQ2RbKwHnU=</DQ><InverseQ>Jrbm5MzTpYI9f0jQKBFzdEdI4DeUFou4BrFpJaheh/+jhzogia+0VsK1CfuXbXgFLPV2aXpQeZYZTX/ANJEymJsp9kAELknq8O+qz6QFyfY0F4Q5H6SVuI/U40XlstYZ2ZEvjGMhXpSAnQUIZ8HJQf8nFOSoAK+HyDwPdvn5RlE=</InverseQ><D>L5hkBK1nyrxG8m7afAgbvJCUVmPqrrVpZzujDRGGnNBdxtL4ffl5h48N4ZUODLmk5p920ZZ+lExs6XLP8Rtpfxo3fadDB28eWdhMadipHkwZw3yHml4HqTijgn2kl+pV4Ainjbkc0zOqT+FRJPvUM/sIwEtkuSevcqt7NT73ozp9roswv0QHBrclCVIN0uiCqPEsfTaLeVEpg48dOh8as6l1XDlgnDGTFjkj2AgFfD27POPE3n4pJSaYJc5zNijbwrjyz8qa1nr+xBQ+yvteNDOg/1LAczP1xrypDgsl/bRHmkljYhPj40SXwK2jwyicgfgCbE3wi6O9t52D8koacQ==</D></RSAKeyValue>");
}
}
示例2: Decrypt
// Decrypt method
public string Decrypt( string b64String )
{
try
{
byte[] ciphertext = Convert.FromBase64String(b64String);
CspParameters RSAParams = new CspParameters();
RSAParams.Flags = CspProviderFlags.UseMachineKeyStore;
//create new instance of RSACryptoServiceProvider
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(RSAParams);
//import public and private RSA parameters from Xml file
//StreamReader reader = new StreamReader("PublicPrivateKey.xml");
//string publicPrivateKeyXml = reader.ReadToEnd();
//reader.Close();
rsa.FromXmlString(this.publicPrivateKeyXml);
//read ciphertext, decrypt it to plaintext
byte[] plainbytes = rsa.Decrypt( ciphertext, false); //fOAEP needs high encryption pack
return Encoding.ASCII.GetString(plainbytes) ;
}
catch ( CryptographicException cx )
{
throw new CryptographicException( cx.Message) ;
}
}
示例3: DecryptString
public static string DecryptString(string inputString, int dwKeySize,
string xmlString)
{
// TODO: Add Proper Exception Handlers
RSACryptoServiceProvider rsaCryptoServiceProvider
= new RSACryptoServiceProvider(dwKeySize);
rsaCryptoServiceProvider.FromXmlString(xmlString);
int base64BlockSize = ((dwKeySize / 8) % 3 != 0) ?
(((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;
int iterations = inputString.Length / base64BlockSize;
ArrayList arrayList = new ArrayList();
for (int i = 0; i < iterations; i++)
{
byte[] encryptedBytes = Convert.FromBase64String(
inputString.Substring(base64BlockSize * i, base64BlockSize));
// 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
// EncryptString function.
Array.Reverse(encryptedBytes);
arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(
encryptedBytes, true));
}
return Encoding.UTF32.GetString(arrayList.ToArray(
Type.GetType("System.Byte")) as byte[]);
}
示例4: EncryptRSA
/// <summary>
/// 公钥加密
/// </summary>
/// <param name="publichKey"></param>
/// <param name="strData"></param>
public static string EncryptRSA(string publicKey, string strData)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
byte[] dataRSAed = rsa.Encrypt(Encoding.UTF8.GetBytes(strData), false);
return CommonHelper.ByteArrayToString(dataRSAed);
}
示例5: 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);
}
示例6: RSADecrypt
/// <summary>
/// decrypts a string with a key inside the xmlstring
/// </summary>
/// <param name="DataToDecrypt">data to decrypt</param>
/// <param name="xml">xmlstring taken from an RSACryptoServiceProvider object</param>
/// <returns>decrypted string</returns>
public static string RSADecrypt(string DataToDecrypt, string xml)
{
try
{
byte[] decryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(xml);
//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
decryptedData = RSA.Decrypt(Convert.FromBase64String(DataToDecrypt), false);
}
return Encoding.UTF8.GetString(decryptedData);
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}
示例7: 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
});
}
示例8: 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();
}
}
}
示例9: VerifyDigitalSignature
/// <summary>
/// Metoda za verifikaciju ispravnosti digitalnog potpisa dokumenta
/// </summary>
/// <param name="file"></param>
public void VerifyDigitalSignature(string file)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader streamReader = new StreamReader("javni_kljuc.txt");
string publicKey = streamReader.ReadToEnd();
rsa.FromXmlString(publicKey);
streamReader.Close();
streamReader.Dispose();
FileStream dat = new FileStream(file, FileMode.Open, FileAccess.Read);
BinaryReader binReader = new BinaryReader(dat);
byte[] data = binReader.ReadBytes((int)dat.Length);
string nameP = file + ".dp";
TextReader streamreader = new StreamReader(nameP);
string sign = streamreader.ReadLine();
streamreader.Close();
streamreader.Dispose();
if (rsa.VerifyData(data, "SHA1", Convert.FromBase64String(sign)))
{
MessageBox.Show("Datoteka je ispravno potpisana", "My Application",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
MessageBox.Show("Datoteka nije ispravno potpisana", "My Application", MessageBoxButtons.OK, MessageBoxIcon.Warning);
binReader.Close();
binReader.Dispose();
dat.Close();
dat.Dispose();
}
示例10: MakeDigitalSignature
/// <summary>
/// Metoda za digitalno potpisivanje dokumenta
/// </summary>
/// <param name="file"></param>
public void MakeDigitalSignature(string file)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader streamReader = new StreamReader("privatni_kljuc.txt");
string publicOnlyKeyXml = streamReader.ReadToEnd();
rsa.FromXmlString(publicOnlyKeyXml);
streamReader.Close();
streamReader.Dispose();
FileStream dat = new FileStream(file, FileMode.Open, FileAccess.Read);
BinaryReader binReader = new BinaryReader(dat);
byte[] data = binReader.ReadBytes((int)dat.Length);
byte[] sign = rsa.SignData(data, "SHA1");
binReader.Close();
binReader.Dispose();
dat.Close();
dat.Dispose();
string datName = file + ".dp";
TextWriter tw = new StreamWriter(datName);
tw.WriteLine(Convert.ToBase64String(sign));
tw.Close();
tw.Dispose();
}
示例11: EncryptData
public string EncryptData(string data2Encrypt, string strPublicKey)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(strPublicKey);
byte[] bytes = Encoding.UTF8.GetBytes(data2Encrypt);
return Convert.ToBase64String(provider.Encrypt(bytes, false));
}
示例12: GetPublicKey
/// <summary>
/// Getting public key
/// </summary>
/// <param name="strPrivateKey"></param>
/// <returns>Return Pubic Key</returns>
public static String GetPublicKey(String strPrivateKey)
{
//Extract the public key from the public/private key pair
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(strPrivateKey);
return rsa.ToXmlString(false);
}
示例13: Decrypt
/// <summary>
/// 解密数据
/// </summary>
/// <param name="base64code">传入加密数据</param>
/// <returns>返回解密数据</returns>
static public string Decrypt(string base64code)
{
var a = new FileInfo("E:/100115_SignKey.pub").OpenRead();
var b = new BufferedStream(a);
//string c =
try
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString("");
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Exponent = Convert.FromBase64String("AQAB");
rsaParameters.Modulus =
Convert.FromBase64String(
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyq3xJ3jtuWSWk4nCCgysplqV3DyFGaF7iP7PO2vEUsgEq+vqKr+frlwji2n7A1TbpV7KhEGJIT9LW/9WCdBhlu6gnBdErtAA4Or43ol2K1BnY6VBcLWccloMd3YFHG8gOohCVIDbw863Wg0FNS27SM25U+XQfrNFaqBIa093WgAbwRIK06uzC01sW+soutvk+yAYBtbH7I7/1/dFixHKS2KN/7y3pvmXYBIRuBvn35IqwY3Gk0duEfbEr9F6wm2VKhS1zQG760FrHfhbXR+IN5nSTQBHBkw4QukLLvUqueKYfVdp2/2RCnY/At0bbOcA2tAPohDAfUDRdOZsFiTIMQID");
byte[] encryptedData;
byte[] decryptedData;
encryptedData = Convert.FromBase64String(base64code);
decryptedData = RSADeCrtypto(encryptedData, rsaParameters, true);
return ByteConverter.GetString(decryptedData);
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
示例14: RSACryptoServiceProviderTest
public RSACryptoServiceProviderTest ()
{
sha1OID = CryptoConfig.MapNameToOID ("SHA1");
disposed = new RSACryptoServiceProvider (minKeySize);
disposed.FromXmlString ("<RSAKeyValue><Modulus>vtXAf62+o50prNCTiVGTMzdhm4sMjK0QVDkKQLFGu2fJQCULt9NZBab14PiWfG1t</Modulus><Exponent>AQAB</Exponent><P>5y2AHOzIhTChIFzLsgZQAGfy3U8OPwFh</P><Q>01NUVJJv+hhIsnbFiSi24FLRrfr/qYuN</Q><DP>HKLAOdUCyazKaK3V9Yleo448wTkntJpB</DP><DQ>AH5MTxo8arAN02TVlzliG+n1lVtlp2at</DQ><InverseQ>ZpgJwTxSYpT81sQCuVUvX0AYrvSziNIw</InverseQ><D>CStiJYBmsZvincAj5qw5w3M8yGmE/9ls4yv7wenozzC4kZshpI2MuON0d2Z8f4aB</D></RSAKeyValue>");
disposed.Clear ();
}
示例15: Run
public void Run()
{
var _exportKey = new RSACryptoServiceProvider();
string publicKeyXML = _exportKey.ToXmlString(false);
string privateKeyXML = _exportKey.ToXmlString(true);
var ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes("My Secret Data!");
byte[] encryptedData;
using (var RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(publicKeyXML);
encryptedData = RSA.Encrypt(dataToEncrypt, false);
}
byte[] decryptedData;
using (var RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(privateKeyXML);
decryptedData = RSA.Decrypt(encryptedData, false);
}
string decryptedString = ByteConverter.GetString(decryptedData);
Console.WriteLine(decryptedString); // Displays: My Secret Data! }
}
开发者ID:rrsc,项目名称:ProgrammingInCSharp,代码行数:26,代码来源:UsingAPublicAndPrivateKeyToEncryptAndDecryptData.cs