// Create an instance using the specified CSP public CapiContext (CspParameters csp) { providerHandle = IntPtr.Zero; if (csp == null) { // default parameters cspParams = new CspParameters (); } else { // keep of copy of the parameters cspParams = new CspParameters (csp.ProviderType, csp.ProviderName, csp.KeyContainerName); cspParams.KeyNumber = csp.KeyNumber; cspParams.Flags = csp.Flags; } // do not show user interface (CRYPT_SILENT) - if UI is required then the function fails. uint flags = CryptoAPI.CRYPT_SILENT; if ((cspParams.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore) { flags |= CryptoAPI.CRYPT_MACHINE_KEYSET; } lastResult = CryptoAPI.CryptAcquireContextA (ref providerHandle, cspParams.KeyContainerName, cspParams.ProviderName, cspParams.ProviderType, flags); if (!lastResult) { // key container may not exist flags |= CryptoAPI.CRYPT_NEWKEYSET; lastResult = CryptoAPI.CryptAcquireContextA (ref providerHandle, cspParams.KeyContainerName, cspParams.ProviderName, cspParams.ProviderType, flags); } }
public void Sigcreate(String name) { try { CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(name); SignXml(xmlDoc, rsaKey); xmlDoc.Save(name); } catch (Exception e) { Console.WriteLine(e.Message); } }
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; }
/// <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; } }
/// <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); }
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 }
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); } }
static void Main(string[] args) { var cspParam = new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey, KeyContainerName = "FreeStreamingKeyStore"}; var keyStore = new RsaKeyStore(cspParam); Peer peer1 = new Peer(38412, true, keyStore); peer1.ApplicationJoined += new CloudRegistrationEventHandler(OnApplicationJoined); peer1.ApplicationDetected += new CloudRegistrationEventHandler(OnApplicationDetected); peer1.ApplicationLeaved += new CloudRegistrationEventHandler(OnApplicationLeaved); peer1.UserMessageReceived += new UserMessageReceivedEventHandler(OnUserMessageReceived); peer1.RegisterInCloud(); //Peer peer2 = new Peer(10001, true, keyStore); //peer2.ApplicationJoined += new CloudRegistrationEventHandler(OnApplication2Joined); //peer2.ApplicationDetected += new CloudRegistrationEventHandler(OnApplication2Detected); //peer2.ApplicationLeaved += new CloudRegistrationEventHandler(OnApplication2Leaved); //peer2.UserMessageReceived += new UserMessageReceivedEventHandler(OnUserMessage2Received); //peer2.RegisterInCloud(); Thread.Sleep(1000); //peer1.SendData(new byte[100]); //peer1.SendData(new byte[200]); //peer1.SendData(new byte[300]); //peer1.SendData(new byte[100000]); Thread.Sleep(1000); peer1.Dispose(); //peer2.Dispose(); Console.WriteLine(".."); Console.ReadLine(); }
public RNGCryptoServiceProvider (CspParameters cspParams) { // CSP selection isn't supported but we still return // random data (no exception) for compatibility _handle = RngInitialize (null); Check (); }
/// <summary> /// Encryptes a string using the supplied key. Encoding is done using RSA encryption. /// </summary> /// <param name="stringToEncrypt">String that must be encrypted.</param> /// <param name="key">Encryptionkey.</param> /// <returns>A string representing a byte array separated by a minus sign.</returns> /// <exception cref="ArgumentException">Occurs when stringToEncrypt or key is null or empty.</exception> public static string Encrypt(this string stringToEncrypt, string key) { if (string.IsNullOrEmpty(stringToEncrypt)) { throw new ArgumentException("An empty string value cannot be encrypted."); } if (string.IsNullOrEmpty(key)) { throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key."); } CspParameters cspp = new System.Security.Cryptography.CspParameters { KeyContainerName = key }; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true }; byte[] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(stringToEncrypt), true); return(BitConverter.ToString(bytes)); }
public DSACryptoServiceProvider (int dwKeySize, CspParameters parameters) { LegalKeySizesValue = new KeySizes [1]; LegalKeySizesValue [0] = new KeySizes (512, 1024, 64); // will throw an exception is key size isn't supported KeySize = dwKeySize; dsa = new DSAManaged (dwKeySize); dsa.KeyGenerated += new DSAManaged.KeyGeneratedEventHandler (OnKeyGenerated); persistKey = (parameters != null); if (parameters == null) { parameters = new CspParameters (PROV_DSS_DH); if (useMachineKeyStore) parameters.Flags |= CspProviderFlags.UseMachineKeyStore; store = new KeyPairPersistence (parameters); // no need to load - it cannot exists } else { store = new KeyPairPersistence (parameters); store.Load (); if (store.KeyValue != null) { persisted = true; this.FromXmlString (store.KeyValue); } } }
public PasswordDeriveBytes (byte[] password, byte[] salt, String hashName, int iterations, CspParameters cspParams) { this.IterationCount = iterations; this.Salt = salt; this.HashName = hashName; _password = password; _cspParams = cspParams; }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; CspParameters csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp); RSAParameters para = rsa.ExportParameters(true); StringBuilder model = new StringBuilder(); for (int i = 0; i < para.Modulus.Length; i++) { model.Append(para.Modulus[i].ToString("X2")); } StringBuilder exponent = new StringBuilder(); for (int i = 0; i <para.Exponent.Length; i ++) { exponent.Append(para.Exponent[i].ToString("X2")); } XElement list = new XElement("list"); XElement pri = new XElement("private", new XAttribute("key", rsa.ToXmlString(true))); XElement pub = new XElement("public", new XAttribute("model", model.ToString()),new XAttribute("exponent",exponent.ToString())); list.Add(pri); list.Add(pub); context.Response.Write(list.ToString()); }
public DSACryptoServiceProvider (int dwKeySize, CspParameters parameters) { bool has_parameters = parameters != null; Common (dwKeySize, has_parameters); if (has_parameters) Common (parameters); }
// 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) ; } }
static void Main(string[] args) { // To idendify the Smart Card CryptoGraphic Providers on your // computer, use the Microsoft Registry Editor (Regedit.exe). // The available Smart Card CryptoGraphic Providers are listed // in HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider. // Create a new CspParameters object that identifies a // Smart Card CryptoGraphic Provider. // The 1st parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider Types. // The 2nd parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider. CspParameters csp = new CspParameters(1); csp.KeyContainerName = "MyKeyContainer ya!!"; csp.Flags = CspProviderFlags.UseDefaultKeyContainer; // Initialize an RSACryptoServiceProvider object using // the CspParameters object. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp); Console.WriteLine("KeyName:{0}", rsa.ToXmlString(true)); // Create some data to sign. byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }; Console.WriteLine("Data : " + BitConverter.ToString(data, 0, data.Length)); // Sign the data using the Smart Card CryptoGraphic Provider. byte[] signData = rsa.SignData(data, "SHA1"); Console.WriteLine("Signature:" + BitConverter.ToString(signData)); bool verify = rsa.VerifyData(data, "SHA1", signData);//原始資料和sign過的資料作SHA1比對 Console.WriteLine("驗證資料:" + verify); Console.ReadKey(); }
/// <summary> Creates the key from the information provided </summary> public static RSAPublicKey FromStore(CspParameters parameters) { RSACryptoServiceProvider key = new RSACryptoServiceProvider(parameters); if (key.PublicOnly) return new RSAPublicKey(key); return new RSAPrivateKey(key); }
public string SignN3Rsa(string data) { var cspParams = new CspParameters {KeyContainerName = "XML_DSIG_RSA_KEY"}; var key = new RSACryptoServiceProvider(cspParams); var cspBlob = key.ExportCspBlob(false); var base64Blob = Convert.ToBase64String(cspBlob); var rsaFormatter = new RSAPKCS1SignatureFormatter(key); rsaFormatter.SetHashAlgorithm("MD5"); var hash = Md5Helper.GetMd5Hash(data); var base64Hash = Convert.ToBase64String(hash); var sign = rsaFormatter.CreateSignature(hash); var base64Sign = Convert.ToBase64String(sign); var signData = new SignData { data = data, public_key = base64Blob, hash = base64Hash, sign = base64Sign }; return new SerializationHelper<SignData>().Serialize(signData); }
// // Returns the private key referenced by a store certificate. Note that despite the return type being declared "CspParameters", // the key can actually be a CNG key. To distinguish, examine the ProviderType property. If it is 0, this key is a CNG key with // the various properties of CspParameters being "repurposed" into storing CNG info. // // This is a behavior this method inherits directly from the Crypt32 CRYPT_KEY_PROV_INFO semantics. // // It would have been nice not to let this ugliness escape out of this helper method. But X509Certificate2.ToString() calls this // method too so we cannot just change it without breaking its output. // private CspParameters GetPrivateKey() { int cbData = 0; if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cbData)) { int dwErrorCode = Marshal.GetLastWin32Error(); if (dwErrorCode == ErrorCode.CRYPT_E_NOT_FOUND) return null; throw new CryptographicException(dwErrorCode); } unsafe { byte[] privateKey = new byte[cbData]; fixed (byte* pPrivateKey = privateKey) { if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, privateKey, ref cbData)) throw new CryptographicException(Marshal.GetLastWin32Error()); CRYPT_KEY_PROV_INFO* pKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pPrivateKey; CspParameters cspParameters = new CspParameters(); cspParameters.ProviderName = Marshal.PtrToStringUni((IntPtr)(pKeyProvInfo->pwszProvName)); cspParameters.KeyContainerName = Marshal.PtrToStringUni((IntPtr)(pKeyProvInfo->pwszContainerName)); cspParameters.ProviderType = pKeyProvInfo->dwProvType; cspParameters.KeyNumber = pKeyProvInfo->dwKeySpec; cspParameters.Flags = (CspProviderFlags)((pKeyProvInfo->dwFlags & CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET) == CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET ? CspProviderFlags.UseMachineKeyStore : 0); return cspParameters; } } }
public CryptKeys() { Container = "ShareXmod"; cp = new CspParameters(); cp.KeyContainerName = Container; GenerateKey(); }
// 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); }
private static RSACryptoServiceProvider CreateRSACryptoServiceProvider() { CspParameters RSAParams = new CspParameters(); RSAParams.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider(RSAParams); return publicKey; }
public static void RSADeleteKeyInCSP(string ContainerName) { try { // Create a new instance of CspParameters. Pass // 13 to specify a DSA container or 1 to specify // an RSA container. The default is 1. CspParameters cspParams = new CspParameters(); // Specify the container name using the passed variable. cspParams.KeyContainerName = ContainerName; //Create a new instance of RSACryptoServiceProvider. //Pass the CspParameters class to use the //key in the container. RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(cspParams); //Delete the key entry in the container. RSAalg.PersistKeyInCsp = false; //Call Clear to release resources and delete the key from the container. RSAalg.Clear(); //Indicate that the key was persisted. Console.WriteLine("The RSA key was deleted from the container, \"{0}\".", ContainerName); } catch (CryptographicException e) { Console.WriteLine(e.Message); } }
public static byte[] DecryptRSA(byte[] data, byte[] key) { var csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; using (var rsa = new RSACryptoServiceProvider(_dwSize, csp)) using (var ms = new MemoryStream()) { //Create seed, create RSA blob, replace logic rsa.ImportCspBlob(key); for (int i = 0; i < data.Length; i += _chunkSize) { int amount = Math.Min(_chunkSize, data.Length - i); byte[] buffer = new byte[amount]; Buffer.BlockCopy(data, i, buffer, 0, amount); byte[] decrypted = rsa.Decrypt(buffer, false); ms.Write(decrypted, 0, decrypted.Length); } return ms.ToArray(); } }
public CryptKeys() { Container = Application.ProductName; cp = new CspParameters(); cp.KeyContainerName = Container; GenerateKey(); }
/// <summary> Creates the key from the information provided </summary> public static RSAPublicKey FromStore(string name) { CspParameters p = new CspParameters(); p.Flags = CspProviderFlags.NoPrompt | CspProviderFlags.UseExistingKey; p.KeyContainerName = name; return FromStore(p); }
private void Common (int dwKeySize, CspParameters p) { // Microsoft RSA CSP can do between 384 and 16384 bits keypair LegalKeySizesValue = new KeySizes [1]; LegalKeySizesValue [0] = new KeySizes (384, 16384, 8); base.KeySize = dwKeySize; rsa = new RSAManaged (KeySize); rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated); persistKey = (p != null); if (p == null) { p = new CspParameters (PROV_RSA_FULL); #if NET_1_1 if (useMachineKeyStore) p.Flags |= CspProviderFlags.UseMachineKeyStore; #endif store = new KeyPairPersistence (p); // no need to load - it cannot exists } else { store = new KeyPairPersistence (p); bool exists = store.Load (); bool required = (p.Flags & CspProviderFlags.UseExistingKey) != 0; if (required && !exists) throw new CryptographicException ("Keyset does not exist"); if (store.KeyValue != null) { persisted = true; this.FromXmlString (store.KeyValue); } } }
void sign() { try { // Create a new CspParameters object to specify // a key container. CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"; // Create a new RSA signing key and save it in the container. RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams); // Create a new XML document. XmlDocument xmlDoc = new XmlDocument(); // Load an XML file into the XmlDocument object. xmlDoc.PreserveWhitespace = true; xmlDoc.Load("test.xml"); // Sign the XML document. SignXml(xmlDoc, rsaKey); Console.WriteLine("XML file signed."); // Save the document. xmlDoc.Save("test.xml"); } catch (Exception e) { Console.WriteLine(e.Message); } }
private void GrabarClaveCompleta(CspParameters cp, RSACryptoServiceProvider rsa) { StreamWriter s = new StreamWriter(cp.KeyContainerName + ".pubpriv.rsa"); rsa.PersistKeyInCsp = false; s.WriteLine(rsa.ToXmlString(true)); s.Close(); }
static Encryption() { CspParameters CSPParam = new CspParameters(); CSPParam.Flags = CspProviderFlags.UseMachineKeyStore; RsaProvider = new RSACryptoServiceProvider(CSPParam); RsaProvider.FromXmlString(xmlKey); }
/// <summary> /// Public constructor. /// </summary> public Encryptor() { string pass = Esapi.SecurityConfiguration.MasterPassword; byte[] salt = Esapi.SecurityConfiguration.MasterSalt; try { // Set up encryption and decryption using (SymmetricAlgorithm symmetricAlgorithm = SymmetricAlgorithm.Create(this.encryptAlgorithm)) { using (Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(pass, salt)) { this.secretKey = rfc2898.GetBytes(symmetricAlgorithm.KeySize / 8); } // TODO: Hardcoded value 13 is the code for DSA this.asymmetricKeyPair = new CspParameters(13); // The asymmetric key will be stored in the key container using the name ESAPI. this.asymmetricKeyPair.KeyContainerName = "ESAPI"; } } catch (Exception e) { throw new EncryptionException(EM.Encryptor_EncryptionFailure, EM.Encryptor_EncryptorCreateFailed, e); } }
/// <summary> /// RSA加密数据 /// </summary> /// <param name="express">要加密数据</param> /// <param name="KeyContainerName">密匙容器的名称</param> /// <returns></returns> public static string RSAEncryption(string express, string KeyContainerName = null) { System.Security.Cryptography.CspParameters param = new System.Security.Cryptography.CspParameters(); param.KeyContainerName = KeyContainerName ?? "default"; //密匙容器的名称,保持加密解密一致才能解密成功 using (System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(param)) { byte[] plaindata = System.Text.Encoding.ASCII.GetBytes(express); //将要加密的字符串转换为字节数组 byte[] encryptdata = rsa.Encrypt(plaindata, false); //将加密后的字节数据转换为新的加密字节数组 return(Convert.ToBase64String(encryptdata)); //将加密后的字节数组转换为字符串 } }
/// <summary> /// RSA解密数据 /// </summary> /// <param name="ciphertext">要解密数据</param> /// <param name="KeyContainerName">密匙容器的名称</param> /// <returns></returns> public static string RSADecrypt(string ciphertext, string KeyContainerName = null) { System.Security.Cryptography.CspParameters param = new System.Security.Cryptography.CspParameters(); param.KeyContainerName = KeyContainerName ?? "default"; //密匙容器的名称,保持加密解密一致才能解密成功 using (System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(param)) { byte[] encryptdata = Convert.FromBase64String(ciphertext); byte[] decryptdata = rsa.Decrypt(encryptdata, false); return(System.Text.Encoding.ASCII.GetString(decryptdata)); } }
/// <summary> /// 公開鍵と秘密鍵を作成し、キーコンテナに格納する /// </summary> /// <param name="containerName">キーコンテナ名</param> /// <returns>作成された公開鍵(XML形式)</returns> public static string CreateKeysAndSaveContainer(string containerName) { //CspParametersオブジェクトの作成 System.Security.Cryptography.CspParameters cp = new System.Security.Cryptography.CspParameters(); //キーコンテナ名を指定する cp.KeyContainerName = containerName; //CspParametersを指定してRSACryptoServiceProviderオブジェクトを作成 System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cp); //公開鍵をXML形式で取得して返す return(rsa.ToXmlString(false)); }
/// <summary> /// 指定されたキーコンテナを削除する /// </summary> /// <param name="containerName">キーコンテナ名</param> public static void DeleteKeys(string containerName) { //CspParametersオブジェクトの作成 System.Security.Cryptography.CspParameters cp = new System.Security.Cryptography.CspParameters(); //キーコンテナ名を指定する cp.KeyContainerName = containerName; //CspParametersを指定してRSACryptoServiceProviderオブジェクトを作成 System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cp); //キーコンテナを削除 rsa.PersistKeyInCsp = false; rsa.Clear(); }
/// <summary> /// キーコンテナに格納された秘密鍵を使って、文字列を復号化する /// </summary> /// <param name="str">Encryptメソッドにより暗号化された文字列</param> /// <param name="containerName">キーコンテナ名</param> /// <returns>復号化された文字列</returns> public static string DecryptByContainer(string str, string containerName) { //CspParametersオブジェクトの作成 System.Security.Cryptography.CspParameters cp = new System.Security.Cryptography.CspParameters(); //キーコンテナ名を指定する cp.KeyContainerName = containerName; //CspParametersを指定してRSACryptoServiceProviderオブジェクトを作成 System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cp); //復号化する byte[] data = System.Convert.FromBase64String(str); byte[] decryptedData = rsa.Decrypt(data, false); return(System.Text.Encoding.UTF8.GetString(decryptedData)); }
/// <summary> /// Sign the data with the X509Certificate /// </summary> /// <param name="signingCertificate">Signing certificate.</param> /// <param name="data">Data to be signed.</param> /// <returns>RSA SHA 256 Signature</returns> public static byte[] SignData(X509Certificate2 signingCertificate, string data) { X509AsymmetricSecurityKey securityKey = new X509AsymmetricSecurityKey(signingCertificate); RSACryptoServiceProvider rsa = securityKey.GetAsymmetricAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", true) as RSACryptoServiceProvider; if (!signingCertificate.HasPrivateKey) { throw new ArgumentException(string.Format( "Private key is not found in the certificate: {0}", signingCertificate.Subject)); } if (rsa != null) { rsa.FromXmlString(signingCertificate.PrivateKey.ToXmlString(true)); if (rsa.CspKeyContainerInfo.ProviderType != 24) { System.Security.Cryptography.CspParameters cspParameters = new System.Security.Cryptography.CspParameters { ProviderType = 24, KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName, KeyNumber = (int)rsa.CspKeyContainerInfo.KeyNumber }; if (rsa.CspKeyContainerInfo.MachineKeyStore) { cspParameters.Flags = CspProviderFlags.UseMachineKeyStore; } rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspParameters); } } HashAlgorithm hashAlgo = System.Security.Cryptography.SHA256.Create(); byte[] signatureInBytes = rsa.SignData(Encoding.UTF8.GetBytes(data), hashAlgo); return(signatureInBytes); }
public RSACryptoServiceProviderProxy(System.Security.Cryptography.RSACryptoServiceProvider rsa) { Utility.VerifyNonNullArgument("rsa", rsa); if (rsa.CspKeyContainerInfo.ProviderType != 24) { System.Security.Cryptography.CspParameters cspParameters = new System.Security.Cryptography.CspParameters(); cspParameters.ProviderType = 24; cspParameters.KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName; cspParameters.KeyNumber = (int)rsa.CspKeyContainerInfo.KeyNumber; if (rsa.CspKeyContainerInfo.MachineKeyStore) { cspParameters.Flags = System.Security.Cryptography.CspProviderFlags.UseMachineKeyStore; } cspParameters.Flags |= System.Security.Cryptography.CspProviderFlags.UseExistingKey; this._rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspParameters); this._disposeRsa = true; return; } this._rsa = rsa; }
public static byte[] RSADecrypt(byte[] privateKey, byte[] dataToDecrypt) { // helper to RSA decrypt a given blob // PROV_RSA_AES == 24 var cspParameters = new System.Security.Cryptography.CspParameters(24); using (var rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParameters)) { try { rsaProvider.PersistKeyInCsp = false; rsaProvider.ImportCspBlob(privateKey); byte[] dataToDecryptRev = new byte[256]; Buffer.BlockCopy(dataToDecrypt, 0, dataToDecryptRev, 0, dataToDecrypt.Length); // ... Array.Copy? naw... :( Array.Reverse(dataToDecryptRev); // ... don't ask me how long it took to realize this :( byte[] dec = rsaProvider.Decrypt(dataToDecryptRev, false); // no padding return(dec); } catch (Exception e) { Console.WriteLine("Error decryption domain key: {0}", e.Message); } finally { rsaProvider.PersistKeyInCsp = false; rsaProvider.Clear(); } } return(new byte[0]); }
/* * converts a bouncy castle private key to a windows private key */ private static sys2.AsymmetricAlgorithm ConvertToSystemKey(RsaPrivateCrtKeyParameters privateKey) { sys2.CspParameters cspPars = new sys2.CspParameters { KeyContainerName = Guid.NewGuid().ToString(), KeyNumber = (int)sys2.KeyNumber.Exchange }; sys2.RSACryptoServiceProvider rsaCryptoProvider = new sys2.RSACryptoServiceProvider(cspPars); sys2.RSAParameters rsaParameters = new sys2.RSAParameters { Modulus = privateKey.Modulus.ToByteArrayUnsigned(), P = privateKey.P.ToByteArrayUnsigned(), Q = privateKey.Q.ToByteArrayUnsigned(), DP = privateKey.DP.ToByteArrayUnsigned(), DQ = privateKey.DQ.ToByteArrayUnsigned(), InverseQ = privateKey.QInv.ToByteArrayUnsigned(), D = privateKey.Exponent.ToByteArrayUnsigned(), Exponent = privateKey.PublicExponent.ToByteArrayUnsigned() }; rsaCryptoProvider.ImportParameters(rsaParameters); return(rsaCryptoProvider); }
public string Encrypt(string publicKey, string plainText) { System.Security.Cryptography.CspParameters cspParams = null; System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null; byte[] plainBytes = null; byte[] encryptedBytes = null; string result = ""; try { cspParams = new System.Security.Cryptography.CspParameters(); cspParams.ProviderType = 1; rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams); rsaProvider.FromXmlString(publicKey); plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText); encryptedBytes = rsaProvider.Encrypt(plainBytes, false); result = Convert.ToBase64String(encryptedBytes); } catch (Exception ex) { Log(ex.Message); } return(result); }
public void GenerateKeys() { System.Security.Cryptography.CspParameters cspParams = null; System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null; string publicKey = ""; string privateKey = ""; try { cspParams = new System.Security.Cryptography.CspParameters(); cspParams.ProviderType = 1; cspParams.Flags = System.Security.Cryptography.CspProviderFlags.UseArchivableKey; cspParams.KeyNumber = (int)System.Security.Cryptography.KeyNumber.Exchange; rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams); publicKey = rsaProvider.ToXmlString(false); privateKey = rsaProvider.ToXmlString(true); } catch (Exception ex) { Log(ex.Message); } }
private extern int _CreateCSP(CspParameters param, ref IntPtr unknown);
private extern void _DeleteKeyContainer(CspParameters param, IntPtr hCSP);
[System.Security.SecuritySafeCritical] // auto-generated public CspKeyContainerInfo(CspParameters parameters) : this(parameters, false) { }
/// <summary>Initializes a new instance of the <see cref="T:System.Security.Cryptography.CspKeyContainerInfo" /> class using the specified parameters.</summary> /// <param name="parameters">A <see cref="T:System.Security.Cryptography.CspParameters" /> object that provides information about the key.</param> public CspKeyContainerInfo(CspParameters parameters) { this._params = parameters; this._random = true; }
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters) : this(dwKeySize, parameters, false) { }
public RNGCryptoServiceProvider(CspParameters cspParams) { throw new NotImplementedException(); }
public RNGCryptoServiceProvider(CspParameters cspParams) { }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations, CspParameters cspParams) { Prepare(strPassword, rgbSalt, strHashName, iterations); if (cspParams != null) { throw new NotSupportedException( Locale.GetText("CspParameters not supported by Mono for PasswordDeriveBytes.")); } }
public DSACryptoServiceProvider(CspParameters parameters) : this(1024, parameters) { }
public RSACryptoServiceProvider(CspParameters parameters) { Common(1024, parameters); // no keypair generation done at this stage }
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters) { Common(dwKeySize, parameters); // no keypair generation done at this stage }
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters) => throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspParameters)));
private extern int _AcquireCSP(CspParameters param, ref IntPtr hCSP);
public DSACryptoServiceProvider(int dwKeySize, CspParameters parameters) { }
// *********************** CONSTRUCTORS ************************* internal CryptoAPITransform(String strName, int algid, int cArgs, int[] rgArgIds, Object[] rgArgValues, byte[] rgbKey, CspParameters param, PaddingMode padding, CipherMode cipherChainingMode, int blockSize, int feedbackSize, CryptoAPITransformMode encDecMode) { int dwValue; int hr; int i; byte[] rgbValue; State = 0; NameValue = strName; BlockSizeValue = blockSize; FeedbackSizeValue = feedbackSize; ModeValue = cipherChainingMode; PaddingValue = padding; KeySizeValue = rgbKey.Length * 8; _algid = algid; encryptOrDecrypt = encDecMode; // Copy the input args _cArgs = cArgs; _rgArgIds = new int[rgArgIds.Length]; Array.Copy(rgArgIds, _rgArgIds, rgArgIds.Length); _rgbKey = new byte[rgbKey.Length]; Array.Copy(rgbKey, _rgbKey, rgbKey.Length); _rgArgValues = new Object[rgArgValues.Length]; // an element of rgArgValues can only be an int or a byte[] for (int j = 0; j < rgArgValues.Length; j++) { if (rgArgValues[j] is byte[]) { byte[] rgbOrig = (byte[])rgArgValues[j]; byte[] rgbNew = new byte[rgbOrig.Length]; Array.Copy(rgbOrig, rgbNew, rgbOrig.Length); _rgArgValues[j] = rgbNew; continue; } if (rgArgValues[j] is int) { _rgArgValues[j] = (int)rgArgValues[j]; continue; } if (rgArgValues[j] is CipherMode) { _rgArgValues[j] = (int)rgArgValues[j]; continue; } } _hCSP = IntPtr.Zero; //_hMasterKey = IntPtr.Zero; _hKey = IntPtr.Zero; // If we have no passed in CSP parameters, use the default ones if (param == null) { _parameters = new CspParameters(); } else { _parameters = param; } // // Try and open the CSP. // On downlevel crypto platforms, we have to create a key container because we can't // use the exponent-of-one trick on a CRYPT_VERIFYONLY keyset // see URT bug #15957 // if (_runningWin2KOrLaterCrypto) { hr = _AcquireCSP(_parameters, ref _hCSP); } else { hr = _CreateCSP(_parameters, ref _hCSP); } if ((hr != 0) || (_hCSP == IntPtr.Zero)) { #if _DEBUG if (debug) { Console.WriteLine("_CreateCSP failed in CSP_Encryptor, hr = {0:X} hCSP = {1:X}", hr, _hCSP); } #endif throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_CouldNotAcquire")); } // Check to see if this alg & key size are supported // Commented out for now until I can fix the DES/3DES 56/64 problem /* { * int hasAlgHR; * Console.WriteLine("Keysizevalue = " + KeySizeValue); * hasAlgHR = _SearchForAlgorithm(_hCSP, algid, KeySizeValue); * if (hasAlgHR != 0) { * throw new CryptographicException(String.Format(Environment.GetResourceString("Cryptography_CSP_AlgKeySizeNotAvailable"),KeySizeValue)); * } * } */ #if _DEBUG if (debug) { Console.WriteLine("Got back _hCSP = {0}", _hCSP); } #endif #if _DEBUG if (debug) { Console.WriteLine("Calling _ImportBulkKey({0}, {1}, {2})", _hCSP, algid, rgbKey); } #endif _hKey = _ImportBulkKey(_hCSP, algid, _rgbKey); if (_hKey == IntPtr.Zero) { throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_ImportBulkKey")); } //hr = _DuplicateKey(_hMasterKey, ref _hKey); #if _DEBUG if (debug) { Console.WriteLine("Got back _hKey = {0}", _hKey); } #endif for (i = 0; i < cArgs; i++) { switch (rgArgIds[i]) { case 1: // KP_IV IVValue = (byte[])_rgArgValues[i]; rgbValue = IVValue; SetAsByteArray: _SetKeyParamRgb(_hKey, _rgArgIds[i], rgbValue); break; case 4: // KP_MODE ModeValue = (CipherMode)_rgArgValues[i]; dwValue = (Int32)_rgArgValues[i]; SetAsDWord: #if _DEBUG if (debug) { Console.WriteLine("Calling _SetKeyParamDw({0}, {1}, {2})", _hKey, _rgArgIds[i], dwValue); } #endif _SetKeyParamDw(_hKey, _rgArgIds[i], dwValue); break; case 5: // KP_MODE_BITS FeedbackSizeValue = (Int32)_rgArgValues[i]; dwValue = FeedbackSizeValue; goto SetAsDWord; case 19: // KP_EFFECTIVE_KEYLEN EffectiveKeySizeValue = (Int32)_rgArgValues[i]; dwValue = EffectiveKeySizeValue; goto SetAsDWord; default: throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeyParameter"), "_rgArgIds[i]"); } } _KeyHandleProtector = new __KeyHandleProtector(_hKey); }
public RSACryptoServiceProvider(CspParameters parameters) : this(0, parameters, true) { }
public RSACryptoServiceProvider(CspParameters parameters) { return(default(RSACryptoServiceProvider)); }
public DSACryptoServiceProvider(CspParameters parameters) { }