/// <summary>バイト配列を暗号化する</summary> /// <param name="source">暗号化するバイト配列</param> /// <param name="publicKey">暗号化に使用する公開鍵</param> /// <returns>非対称アルゴリズムで暗号化されたバイト配列</returns> public static byte[] EncryptBytes(byte[] source, string publicKey) { // RSACryptoServiceProviderオブジェクトの作成 RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create(); // devps(1703) // 公開鍵 rsa.FromXmlString(publicKey); // 暗号化する byte[] temp = rsa.Encrypt(source, false); rsa.Clear(); // devps(1725) return(temp); }
/// <summary>暗号化されたバイト配列を復号化する</summary> /// <param name="source">暗号化されたバイト配列</param> /// <param name="privateKey">復号化に使用する秘密鍵</param> /// <returns>非対称アルゴリズムで復号化されたバイト配列</returns> public static byte[] DecryptBytes(byte[] source, string privateKey) { // RSACryptoServiceProviderオブジェクトの作成 RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create(); // devps(1703) // 秘密鍵 rsa.FromXmlString(privateKey); // 復号化 byte[] temp = rsa.Decrypt(source, false); rsa.Clear(); // devps(1725) return(temp); }
public byte[] UDPRecivedToDecrypt(RSAParameters parametres, byte[] data) { byte[] dataToEncrypt = data; byte[] decryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.Clear(); RSA.ImportParameters(parametres); decryptedData = RSADecrypt(dataToEncrypt, RSA.ExportParameters(true), false); } return(decryptedData); }
public static void Main(String[] args) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); string xsl = @" <xs:transform xmlns:xs='http://www.w3.org/1999/XSL/Transform' version='1.0'> <xs:template match='/'> <xs:apply-templates/> </xs:template> <xs:template match='ElementToTransform'> <transformedElement/> </xs:template> </xs:transform>"; try { // Create an XML file to sign. CreateSomeXml("Example.xml"); Console.WriteLine("New XML file created."); // Sign the XML that was just created and save it in a // new file. SignXmlFile("Example.xml", "SignedExample.xml", Key, xsl); Console.WriteLine("XML file signed."); // Verify the signature of the signed XML. Console.WriteLine("Verifying signature..."); bool result = VerifyXmlFile("SignedExample.xml"); // Display the results of the signature verification to \ // the console. if (result) { Console.WriteLine("The XML signature is valid."); } else { Console.WriteLine("The XML signature is not valid."); } } catch (CryptographicException e) { Console.WriteLine(e.Message); } finally { Key.Clear(); } }
static byte[] EncryptUsingContainer(string value, string containerName) { CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = containerName; using (var rsa = new RSACryptoServiceProvider(cspParams)) { byte[] encodedData = System.Text.Encoding.Default.GetBytes(value); byte[] encryptedData = rsa.Encrypt(encodedData, true); rsa.Clear(); return(encryptedData); } }
static string DecryptUsingContainer(byte[] encryptedData, string container) { CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = container; using (var rsa = new RSACryptoServiceProvider(cspParams)) { byte[] decryptedData = rsa.Decrypt(encryptedData, true); string decryptedValue = Encoding.Default.GetString(decryptedData); rsa.Clear(); return(decryptedValue); } }
/// <summary> /// Takes a string and creates a signed hash of it /// </summary> /// <param name="Input">Input string</param> /// <param name="Key">Key to encrypt/sign with</param> /// <param name="Hash">This will be filled with the unsigned hash</param> /// <param name="EncodingUsing">Encoding that the input is using (defaults to UTF8)</param> /// <returns>A signed hash of the input (64bit string)</returns> public override string SignHash(string Input, string Key, out string Hash, Encoding EncodingUsing = null) { Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(Key), "Key"); Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(Input), "Input"); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(Key); var HashBytes = Input.ToByteArray(EncodingUsing).Hash(); var SignedHash = RSA.SignHash(HashBytes, CryptoConfig.MapNameToOID("SHA1")); RSA.Clear(); Hash = HashBytes.ToString(Base64FormattingOptions.None); return(SignedHash.ToString(Base64FormattingOptions.None)); } }
private string Encrypt(out RSAParameters privateKey) { var textAsBites = Encoding.UTF8.GetBytes(text); var rsa = new RSACryptoServiceProvider(keySize); privateKey = rsa.ExportParameters(true); var encryptedText = rsa.Encrypt(textAsBites, rsaPadding); rsa.Clear(); return(Convert.ToBase64String(encryptedText, 0, encryptedText.Length)); }
public void DeleteKeyFromContainer(string containerName) { var cp = new CspParameters { KeyContainerName = containerName }; var rsa = new RSACryptoServiceProvider(cp) { PersistKeyInCsp = false }; rsa.Clear(); }
/// <summary> /// 删除密钥 /// </summary> /// <param name="containerName"></param> public void DeleteKeyFromContainer(string containerName) { var cp = new CspParameters { KeyContainerName = containerName }; var rsa = new RSACryptoServiceProvider(cp) { // Delete the key entry in the container. PersistKeyInCsp = false }; // Call Clear to release resources and delete the key from the container. rsa.Clear(); }
public void DeleteKeyInCsp() { var cspParameters = new CspParameters { KeyContainerName = containerName, }; using var rsaProvider = new RSACryptoServiceProvider(cspParameters) { PersistKeyInCsp = false, }; rsaProvider.Clear(); }
public void GenerateRsa(string privateKeyPath, string publicKeyPath, int size) { //stream to save the keys FileStream fs = null; StreamWriter sw = null; //create RSA provider RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(size); try { //save private key fs = new FileStream(privateKeyPath, FileMode.Create, FileAccess.Write); sw = new StreamWriter(fs); sw.Write(rsa.ToXmlString(true)); sw.Flush(); } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Close(); } } try { //save public key fs = new FileStream(publicKeyPath, FileMode.Create, FileAccess.Write); sw = new StreamWriter(fs); sw.Write(rsa.ToXmlString(false)); sw.Flush(); } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Close(); } } rsa.Clear(); }
public void DeleteKeyFromContainer(string ContainerName) { CspParameters cp = new CspParameters(); cp.KeyContainerName = ContainerName; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp); rsa.PersistKeyInCsp = false; rsa.Clear(); Console.WriteLine("Key deleted."); }
public override XmlNode Decrypt(XmlNode encryptedNode) { XmlDocument xmlDocument = new XmlDocument(); EncryptedXml exml = null; RSACryptoServiceProvider rsa = GetCryptoServiceProvider(false, true); xmlDocument.PreserveWhitespace = true; ProtectedConfigurationProvider.LoadXml(xmlDocument, encryptedNode.OuterXml); exml = new FipsAwareEncryptedXml(xmlDocument); exml.AddKeyNameMapping(_KeyName, rsa); exml.DecryptDocument(); rsa.Clear(); return(xmlDocument.DocumentElement); }
/// <summary> /// 非对称加密字符串数据,返回加密后的数据 /// </summary> /// <param name="publicKey">公钥</param> /// <param name="originalString">待加密的字符串</param> /// <returns>加密后的数据</returns> public static string RSAEncrypt(string publicKey, string originalString) { //byte[] PlainTextBArray; //byte[] CypherTextBArray; //string Result; //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); //rsa.FromXmlString(publicKey); //PlainTextBArray = (new UnicodeEncoding()).GetBytes(originalString); //CypherTextBArray = rsa.Encrypt(PlainTextBArray, false); //Result = Convert.ToBase64String(CypherTextBArray); //return Result; //分段加密方法 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(publicKey); byte[] originalBytes = (new UnicodeEncoding()).GetBytes(originalString); //实现分段 int keySize = rsa.KeySize / 8; int bufferSize = keySize - 11; byte[] buffer = new byte[bufferSize]; MemoryStream msInput = new MemoryStream(originalBytes); MemoryStream msOutput = new MemoryStream(); int readLen = msInput.Read(buffer, 0, bufferSize); while (readLen > 0) { byte[] dataToEnc = new byte[readLen]; Array.Copy(buffer, 0, dataToEnc, 0, readLen); byte[] encData = rsa.Encrypt(dataToEnc, false); msOutput.Write(encData, 0, encData.Length); readLen = msInput.Read(buffer, 0, bufferSize); } msInput.Close(); byte[] result = msOutput.ToArray(); var strResult = Convert.ToBase64String(result); //得到加密结果 msOutput.Close(); rsa.Clear(); return(strResult); }
protected override void OnLoad(EventArgs e) { if (PowerWebPartHelper.IsPowerUser == false) { throw new SecurityException("Just for Farm Administrators!"); } store = PowerWebPartStore.Current; if (IsPostBack == false) { txtPowerLibraryUrl.Text = store.PowerLibraryUrl; impersonatePowerLibraryUser.Checked = store.PowerLibraryImpersonate; } btnSave.Click += new EventHandler(btnSave_Click); btnExportKey.Click += new EventHandler(btnExportKey_Click); btnCreateKey.Click += new EventHandler(btnCreateKey_Click); if (String.IsNullOrEmpty(txtPowerLibraryUrl.Text) == false) { ValidateDocumentLibrary(); } store.PowerLibraryUrl = txtPowerLibraryUrl.Text; if (uploadKey.HasFile) { RSACryptoServiceProvider rsaAlg = CreateRsa(); try { string fileAsString = Encoding.UTF8.GetString(uploadKey.FileBytes); rsaAlg.FromXmlString(fileAsString); store.SigningKey = fileAsString; } catch (Exception ex) { throw new Exception("Not a valid key file!"); } finally { if (rsaAlg != null) { rsaAlg.Clear(); } } } base.OnLoad(e); }
static void Main(string[] args) { string KeyContainerName = "MyKeyContainer";//Usamos container para armazenar nossas chaves de texto puro string clearText = "This is the data we want to encrypt!"; CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = KeyContainerName; RSAParameters publicKey; RSAParameters privateKey; string publicKeyXML = null; string privateKeyXML = null; using (var rsa = new RSACryptoServiceProvider(cspParams)) { rsa.PersistKeyInCsp = true; publicKey = rsa.ExportParameters(false); //se for false chave publica privateKey = rsa.ExportParameters(true); //Se for verdadeiro cria um RSAParamters privado publicKeyXML = rsa.ToXmlString(false); privateKeyXML = rsa.ToXmlString(true); rsa.Clear(); } byte[] encrypted = EncryptUsingRSAParam(clearText, publicKey); string decrypted = DecryptUsingRSAParam(encrypted, privateKey); Console.WriteLine("Asymmetric RSA - Using RSA Params"); Console.WriteLine("Encrypted:{0}", Convert.ToBase64String(encrypted)); Console.WriteLine("Decrypted:{0}", decrypted); Console.WriteLine("\n"); Console.WriteLine("Asymmetric RSA - Using Persistent Key Container"); encrypted = EncryptUsingContainer(clearText, cspParams); decrypted = DecryptUsingContainer(encrypted, cspParams); Console.WriteLine("Encrypted:{0}", Convert.ToBase64String(encrypted)); Console.WriteLine("Decrypted:{0}", decrypted); Console.WriteLine("\n"); Console.WriteLine("Asymmetric RSA - Using Xml"); encrypted = EncryptUsingXML(clearText, publicKeyXML); decrypted = DecryptUsingXML(encrypted, privateKeyXML); Console.WriteLine("Encrypted:{0}", Convert.ToBase64String(encrypted)); Console.WriteLine("Decrypted:{0}", decrypted); Console.ReadLine(); }
static byte[] DecryptData(byte[] ciphertext) { byte[] plainBytes; using (var rsa = new RSACryptoServiceProvider(2048)) { rsa.PersistKeyInCsp = false; rsa.ImportParameters(privateKey); plainBytes = rsa.Decrypt(ciphertext, true); rsa.Clear(); } return(plainBytes); }
/// <summary> /// Verifies a signed hash against the unsigned version /// </summary> /// <param name="Hash">The unsigned hash (should be 64bit string)</param> /// <param name="SignedHash">The signed hash (should be 64bit string)</param> /// <param name="Key">The key to use in decryption</param> /// <returns>True if it is verified, false otherwise</returns> public override bool VerifyHash(string Hash, string SignedHash, string Key) { Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(Key), "Key"); Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(Hash), "Hash"); Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(SignedHash), "SignedHash"); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(Key); var InputArray = SignedHash.FromBase64(); var HashArray = Hash.FromBase64(); var Result = RSA.VerifyHash(HashArray, CryptoConfig.MapNameToOID("SHA1"), InputArray); RSA.Clear(); return(Result); } }
public static string RSASign(this string plaintext, RSAParameters rsaKey) { if (string.IsNullOrEmpty(plaintext)) { throw new ArgumentNullException("plaintext", "Cannot sign an empty string."); } byte[] plainTextBuffer = UTF8Encoding.UTF8.GetBytes(plaintext); var rsaProvider = new RSACryptoServiceProvider(); rsaProvider.ImportParameters(rsaKey); byte[] signedHashBuffer = rsaProvider.SignData(plainTextBuffer, new SHA1CryptoServiceProvider()); rsaProvider.Clear(); return(Convert.ToBase64String(signedHashBuffer)); }
public RSAParameters GenerateKey() { using (var csp = new RSACryptoServiceProvider(AlgorithmConstants.KeySize)) { try { return(csp.ExportParameters(true)); } finally { csp.PersistKeyInCsp = false; csp.Clear(); } } }
static string DecryptData(byte[] bCipherText) { // Initializing the RSA Cryptography Service Provider (CSP) RSACryptoServiceProvider objRSAProvider = new RSACryptoServiceProvider(); //Set the Load the private key objRSAProvider.FromXmlString(strPriKey); // Encrypting the data recived string strRtnData = objUtf8.GetString(objRSAProvider.Decrypt(bCipherText, false)); objRSAProvider.Clear(); return(strRtnData); }
/// <summary> /// Verifies a signed hash against the unsigned version /// </summary> /// <param name="Hash">The unsigned hash (should be 64bit string)</param> /// <param name="SignedHash">The signed hash (should be 64bit string)</param> /// <param name="Key">The key to use in decryption</param> /// <returns>True if it is verified, false otherwise</returns> public static bool VerifyHash(string Hash, string SignedHash, string Key) { Hash.ThrowIfNullOrEmpty("Hash"); SignedHash.ThrowIfNullOrEmpty("SignedHash"); Key.ThrowIfNullOrEmpty("Key"); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(Key); byte[] InputArray = SignedHash.FromBase64(); byte[] HashArray = Hash.FromBase64(); bool Result = RSA.VerifyHash(HashArray, CryptoConfig.MapNameToOID("SHA1"), InputArray); RSA.Clear(); return(Result); } }
/// <summary> /// Verifies a signed hash against the unsigned version /// </summary> /// <param name="hash">The unsigned hash (should be 64bit string)</param> /// <param name="signedHash">The signed hash (should be 64bit string)</param> /// <param name="key">The key to use in decryption</param> /// <returns>True if it is verified, false otherwise</returns> public static bool VerifyHash(string hash, string signedHash, string key) { Guard.NotEmpty(hash, "hash"); Guard.NotEmpty(signedHash, "signedHash"); Guard.NotEmpty(key, "key"); using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(key); byte[] inputArray = signedHash.FromBase64(); byte[] hashArray = hash.FromBase64(); bool result = rsa.VerifyHash(hashArray, CryptoConfig.MapNameToOID("SHA1"), inputArray); rsa.Clear(); return(result); } }
/// <summary> /// Removes a key container from machine keystore. /// </summary> /// <param name="containerName">container name to remove.</param> public static void Delete(string containerName) { var cspParams = new CspParameters { KeyContainerName = containerName, Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey }; var csp = new RSACryptoServiceProvider(cspParams) { PersistKeyInCsp = false }; csp.Clear(); }
public static void DeleteKey(string containerName) { var parameters = new CspParameters { KeyContainerName = containerName }; using (var rsa = new RSACryptoServiceProvider(parameters) { PersistKeyInCsp = false }) { rsa.Clear(); } }
public static void Test() { var cspParams = new CspParameters { KeyContainerName = "Machine Level Key", Flags = CspProviderFlags.UseMachineKeyStore }; var rsa = new RSACryptoServiceProvider(cspParams); Console.WriteLine(rsa.ToXmlString(false)); rsa.PersistKeyInCsp = true; rsa.Clear(); }
/// <summary> /// 形成并保存公开密钥和私有密钥 /// </summary> /// <param name="p_currentBitStrength">密钥大小</param> static void SaveKey(int p_currentBitStrength) { RSACryptoServiceProvider RSAProvider = new RSACryptoServiceProvider(p_currentBitStrength); string publicAndPrivateKeys = "<BitStrength>" + p_currentBitStrength.ToString() + "</BitStrength>" + RSAProvider.ToXmlString(true); string justPublicKey = "<BitStrength>" + p_currentBitStrength.ToString() + "</BitStrength>" + RSAProvider.ToXmlString(false); RSAProvider.Clear(); if (saveFile("Save public static/Private Keys As", "public static/Private Keys Document( *.cyh_primarykey )|*.cyh_primarykey", publicAndPrivateKeys)) { while (!saveFile("Save public static Key As", "public static Key Document( *.cyh_publickey )|*.cyh_publickey", justPublicKey)) { ; } } }
private void DeleteKey(string keyContainerName) { //コンテナー名の指定 CspParameters parameters = new CspParameters() { KeyContainerName = keyContainerName }; //キーコンテナーから鍵を削除 using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider(parameters)) { csp.PersistKeyInCsp = false; csp.Clear(); } }
/// <summary> /// Genera la clau que conté el parell de clau privada i pública utilitzant 1024 bytes. Guarda el conjunt de claus en els fitxers private.xml i public.xml. /// </summary> public static void GenerateKeys() { // Variables d'aces a fitxers. FileStream fs = null; StreamWriter sw = null; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024); try { // Guarda la clau privada fs = new FileStream(keysPath + privateKey, FileMode.Create, FileAccess.Write); sw = new StreamWriter(fs); sw.Write(rsa.ToXmlString(true)); sw.Flush(); } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Close(); } } try { // Guarda la clau publica fs = new FileStream(keysPath + publicKey, FileMode.Create, FileAccess.Write); sw = new StreamWriter(fs); sw.Write(rsa.ToXmlString(false)); sw.Flush(); } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Close(); } } rsa.Clear(); }
public static string Encrypt(string toEncrypt) { RSACryptoServiceProvider CSPRSA = null; string result; try { CSPRSA = new RSACryptoServiceProvider(); CSPRSA.FromXmlString(SAFSecurityKeys.loadKeysFromFile()); byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt); result = Convert.ToBase64String(CSPRSA.Decrypt(toEncryptArray, false)); } catch { result = null; } finally { if (CSPRSA != null) { CSPRSA.Clear(); } } return result; }
private static void RSATest() { var publicPrivateRsa = new RSACryptoServiceProvider ( new CspParameters() { KeyContainerName = "PublicPrivateKeys", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true, }; var publicRsa = new RSACryptoServiceProvider( new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true }; //Export the key. publicRsa.ImportParameters(publicPrivateRsa.ExportParameters(false)); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); //Dispose those two CSPs. using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); } //Retrieve keys publicPrivateRsa = new RSACryptoServiceProvider( new CspParameters() { KeyContainerName = "PublicPrivateKeys", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); publicRsa = new RSACryptoServiceProvider( new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); } }