public async Task UpdateKeyProtectorAsync(IPrivateKey currentKeyProtector, IPublicKey newKeyProtector) { if (currentKeyProtector == null) { throw new ArgumentNullException("currentKeyProtector"); } if (currentKeyProtector.KeyId != _encryptedKey.KeyId) { throw new ArgumentException(string.Format("currentKeyProtector.KeyId '{0}' does not match encryptedKey.KeyId '{1}'.", currentKeyProtector.KeyId, _encryptedKey.KeyId)); } if (newKeyProtector == null) { throw new ArgumentNullException("newKeyProtector"); } // decrypt the key and populate to the x509 var asymEnc = new AsymmetricEncryptor(); var decrypted = await asymEnc.DecryptObjectAsync(_encryptedKey, currentKeyProtector); var pfxBytes = decrypted as byte[]; if (pfxBytes == null || !pfxBytes.Any()) { throw new CryptographicException(string.Format("encryptedKey successfull decrypted but was not a valid PFX byte array. Type was '{0}'.", decrypted.GetType().FullName)); } // re-encrypt the key var newAsymEncObj = await asymEnc.EncryptObjectAsync(pfxBytes, newKeyProtector); _encryptedKey = newAsymEncObj; }
public void TestProtectPassword() { var cert2 = LoadCertificate(); var publicKey = new X509CertificatePublicKey(cert2); var privateKey = new X509Certificate2KeyEncryptionKey(cert2); int length = 100; var rand = new RandomGenerator(); for (int i = 0; i < length; i++) { using (var password = rand.RandomSecureStringPassword(10, 50)) { var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; // base 64 var encryptedBase64 = AesEncryptor.Encrypt1000(stringToEncrypt, password); var decryptedBase64 = AesEncryptor.Decrypt(encryptedBase64, password); Assert.AreEqual(stringToEncrypt, decryptedBase64); // base 36 var encryptedBase36 = AesEncryptor.Encrypt1000(stringToEncrypt, password, true); var decryptedBase36 = AesEncryptor.Decrypt(encryptedBase36, password, true); Assert.AreEqual(stringToEncrypt, decryptedBase36); var protectedPwStr = AsymmetricEncryptor.EncryptToBase64StringAsync(password, publicKey).GetAwaiter().GetResult(); var unprotectedPwdStr = AsymmetricEncryptor.DecryptFromBase64StringAsync(protectedPwStr, privateKey).GetAwaiter().GetResult(); var decryptedString = AesEncryptor.Decrypt(encryptedBase64, unprotectedPwdStr); Assert.AreEqual(stringToEncrypt, decryptedString); } } }
/// <summary> /// Returns an encrypted string given an RSACryptoServiceProvider and a /// plaintext string. /// </summary> public static string AsymmetricEncrypt(RSACryptoServiceProvider rsa, string data) { ValidateParameters(rsa, data); AsymmetricEncryptor encryptor = new AsymmetricEncryptor(rsa, data); return(encryptor.GetEncryptedString()); }
/// <summary> /// Returns an encrypted byte array given an RSACryptoServiceProvider and /// an unencrypted byte array. /// </summary> public static byte[] AsymmetricEncrypt(RSACryptoServiceProvider rsa, byte[] data) { ValidateParameters(rsa, data); AsymmetricEncryptor encryptor = new AsymmetricEncryptor(rsa, data); return(encryptor.GetEncryptedBytes()); }
public void TestAes1000WithCertificateAndSerialization() { var cert2 = LoadCertificate(); var publicKey = new X509CertificatePublicKey(cert2); var privateKey = new X509Certificate2KeyEncryptionKey(cert2); var rand = new RandomGenerator(); //for (int i = 0; i < length; i++) //{ // var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; // var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000); // var asymObj = asymEnc.EncryptObject(stringToEncrypt, cert2.Thumbprint.ToString().ToLower(), publicKey); // var decrypted = asymEnc.DecryptObject(asymObj, privateKey); // Assert.AreEqual(stringToEncrypt, decrypted); //} var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; var encryptor = new AsymmetricEncryptor() { AsymmetricStrategy = AsymmetricStrategyOption.Aes256_1000 }; var asymEncObj = encryptor.EncryptObjectAsync(stringToEncrypt, publicKey).GetAwaiter().GetResult(); asymEncObj.PublicMetadata = new Dictionary <string, string>(); asymEncObj.PublicMetadata["keyA"] = "valueA"; asymEncObj.PublicMetadata["keyB"] = "valueB"; asymEncObj.KeyId = cert2.Thumbprint.ToLower(); var asymEncObjDirectSerializedBytes = Serializer.SerializeToByteArray(asymEncObj); // deserialize var asymEncObj2 = Serializer.DeserializeFromByteArray(asymEncObjDirectSerializedBytes) as AsymmetricallyEncryptedObject; Assert.IsNotNull(asymEncObj); Assert.IsTrue(!string.IsNullOrEmpty(asymEncObj.KeyId)); var asymEncObjBytes2 = asymEncObj.ToByteArray(); var asymEncObj3 = new AsymmetricallyEncryptedObject(); asymEncObj3.LoadFromByteArray(asymEncObjBytes2); var decrypted = encryptor.DecryptObject(asymEncObj3, privateKey) as string; Assert.AreEqual(decrypted, stringToEncrypt); // test deserializing with direct var asymEncObj4 = new AsymmetricallyEncryptedObject(); asymEncObj4.LoadFromByteArray(asymEncObjDirectSerializedBytes); var decrypted2 = encryptor.DecryptObject(asymEncObj4, privateKey) as string; Assert.AreEqual(decrypted2, stringToEncrypt); }
public void AsymmetricEncryptTest() { var keys = AsymmetricEncryptor.MakeKeys(RSAKeySize.Key4096); string data = "The quick brown fox jumped over the lazy dog"; string encrypted = AsymmetricEncryptor.Encrypt(data, keys.pk); string decrypted = AsymmetricEncryptor.Decrypt(encrypted, keys.sk); Assert.IsTrue(data == decrypted); }
public void SignTest() { var keys = AsymmetricEncryptor.MakeKeys(RSAKeySize.Key4096); var data = new byte[] { 0x00, 0x34, 0x56, 0x19 }; byte[] sig = AsymmetricEncryptor.SignWithSHA256(data, keys.sk); bool verified = AsymmetricEncryptor.VerifyWithSHA256(data, sig, keys.pk); Assert.IsTrue(verified); }
public async Task <IPrivateKey> ToKeyEncyrptionKeyAsync(IPrivateKey keyProtector) { if (keyProtector == null) { throw new ArgumentNullException("keyProtector"); } if (keyProtector.KeyId != _encryptedKey.KeyId) { throw new ArgumentException(string.Format("keyProtector.KeyId '{0}' does not match encryptedKey.KeyId '{1}'.", keyProtector.KeyId, _encryptedKey.KeyId)); } // decrypt the key and populate to the x509 var asymEnc = new AsymmetricEncryptor(); var decrypted = await asymEnc.DecryptObjectAsync(_encryptedKey, keyProtector); var pfxBytes = (byte[])decrypted; if (decrypted == null || !pfxBytes.Any()) { throw new CryptographicException(string.Format("encryptedKey successfull decrypted but was not a valid PFX byte array. Type was '{0}'.", decrypted.GetType().FullName)); } IPrivateKey protectedKeyAsKeyEncryptionKey; try { var x509 = new X509Certificate2(pfxBytes); if (x509.Thumbprint.ToLower() != this.KeyId.ToLower()) { throw new System.Security.SecurityException(string.Format("The original KeyId '{0}' does not match the certificate thumbprint '{1}'.", this.KeyId, x509.Thumbprint)); } if (x509.HasPrivateKey && x509.PrivateKey == null) { var csp = x509.PrivateKey as RSACryptoServiceProvider; if (csp == null) { throw new NotImplementedException(string.Format("encryptedKey does not have a valid RSACryptoServiceProvider private key. Type was '{0}'.", x509.PrivateKey.GetType().FullName)); } if (csp.CspKeyContainerInfo.Exportable) { throw new System.Security.SecurityException("The decrypted X509Certificate2 was marked as exportable in the CspKeyContainerInfo. This is not permitted on a protected key."); } } protectedKeyAsKeyEncryptionKey = Utilities.X509CertificateHelper.GetKeyEncryptionKey(x509); } catch (Exception ex) { throw new InvalidOperationException(string.Format("X509Certificate2 could not be validated. Thumbprint '{0}'. See inner exception for details.", ex)); } return(protectedKeyAsKeyEncryptionKey); }
//private X509Certificate2 _x5092; #region properties #endregion #region .ctors #endregion #region methods public async Task <ProtectedX509Certificate2> IssueNewCertificateAsync(IPublicKey keyProtector, ICertificatePolicy certificatePolicy) { if (keyProtector == null) { throw new ArgumentNullException("keyProtectorPublicKey"); } //if (keyProtector.PublicKey == null) //{ // throw new ArgumentNullException("keyProtectorPublicKey.PublicKey"); //} //var publicKeyProvider = keyProtector.PublicKey.Key as RSACryptoServiceProvider; //if (publicKeyProvider == null) //{ // throw new NotImplementedException("keyProtectorPublicKey.PublicKey.Key must be a valid RSACryptoServiceProvider"); //} string thumbprint; string pemPublicCert; byte[] pkcs12Data; System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2; GenerateSigningCertificate(certificatePolicy, out thumbprint, out pemPublicCert, out pkcs12Data, out x509Certificate2); // encrypt the password using our primary certificate var encryptor = new AsymmetricEncryptor() { AsymmetricStrategy = AsymmetricStrategyOption.Aes256_1000 }; var asymEncObj = encryptor.EncryptObjectAsync(pkcs12Data, keyProtector).GetAwaiter().GetResult(); if (string.IsNullOrEmpty(asymEncObj.KeyId) || asymEncObj.KeyId.Length != 40) { throw new InvalidOperationException("AsymmetricEncryptor.EncryptObject returned without KeyId populated."); } var protectedKey = new ProtectedX509Certificate2(x509Certificate2.Thumbprint.ToLower(), asymEncObj); return(await Task.FromResult(protectedKey)); }
public void TestAes5WithCertificate() { var cert2 = LoadCertificate(); var publicKey = new X509CertificatePublicKey(cert2); var privateKey = new X509Certificate2KeyEncryptionKey(cert2); int length = 100; var rand = new RandomGenerator(); for (int i = 0; i < length; i++) { var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_5); var asymObj = asymEnc.EncryptObjectAsync(stringToEncrypt, publicKey).GetAwaiter().GetResult(); var decrypted = asymEnc.DecryptObject(asymObj, privateKey); Assert.AreEqual(stringToEncrypt, decrypted); } }
//private X509Certificate2 _x5092; #region properties #endregion #region .ctors #endregion #region methods public async Task<ProtectedX509Certificate2> IssueNewCertificateAsync(IPublicKey keyProtector, ICertificatePolicy certificatePolicy) { if (keyProtector == null) { throw new ArgumentNullException("keyProtectorPublicKey"); } //if (keyProtector.PublicKey == null) //{ // throw new ArgumentNullException("keyProtectorPublicKey.PublicKey"); //} //var publicKeyProvider = keyProtector.PublicKey.Key as RSACryptoServiceProvider; //if (publicKeyProvider == null) //{ // throw new NotImplementedException("keyProtectorPublicKey.PublicKey.Key must be a valid RSACryptoServiceProvider"); //} string thumbprint; string pemPublicCert; byte[] pkcs12Data; System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2; GenerateSigningCertificate(certificatePolicy, out thumbprint, out pemPublicCert, out pkcs12Data, out x509Certificate2); // encrypt the password using our primary certificate var encryptor = new AsymmetricEncryptor() { AsymmetricStrategy = AsymmetricStrategyOption.Aes256_1000 }; var asymEncObj = encryptor.EncryptObjectAsync(pkcs12Data, keyProtector).GetAwaiter().GetResult(); if (string.IsNullOrEmpty(asymEncObj.KeyId) || asymEncObj.KeyId.Length != 40) { throw new InvalidOperationException("AsymmetricEncryptor.EncryptObject returned without KeyId populated."); } var protectedKey = new ProtectedX509Certificate2(x509Certificate2.Thumbprint.ToLower(), asymEncObj); return await Task.FromResult(protectedKey); }
public void Encrypt_And_Decrypt() { var hmacKey = KeyGenerator.GenerateHmacKey(); var keys = KeyGenerator.GenerateKeys(); var encryptor = new AsymmetricEncryptor(new AsymmetricOptions() { HmacKey = hmacKey, Key = keys.PublicKey }); const string expected = "Some test"; var encrypted = encryptor.Encrypt(expected); var decryptor = new AsymmetricEncryptor(new AsymmetricOptions() { HmacKey = hmacKey, Key = keys.PrivateKey }); var decrypted = decryptor.DecryptAsString(encrypted); Assert.Equal(expected, decrypted); }
public async Task<IPrivateKey> ToKeyEncyrptionKeyAsync(IPrivateKey keyProtector) { if (keyProtector == null) { throw new ArgumentNullException("keyProtector"); } if (keyProtector.KeyId != _encryptedKey.KeyId) { throw new ArgumentException(string.Format("keyProtector.KeyId '{0}' does not match encryptedKey.KeyId '{1}'.", keyProtector.KeyId, _encryptedKey.KeyId)); } // decrypt the key and populate to the x509 var asymEnc = new AsymmetricEncryptor(); var decrypted = await asymEnc.DecryptObjectAsync(_encryptedKey, keyProtector); var pfxBytes = (byte[])decrypted; if (decrypted == null || !pfxBytes.Any()) { throw new CryptographicException(string.Format("encryptedKey successfull decrypted but was not a valid PFX byte array. Type was '{0}'.", decrypted.GetType().FullName)); } IPrivateKey protectedKeyAsKeyEncryptionKey; try { var x509 = new X509Certificate2(pfxBytes); if (x509.Thumbprint.ToLower() != this.KeyId.ToLower()) { throw new System.Security.SecurityException(string.Format("The original KeyId '{0}' does not match the certificate thumbprint '{1}'.", this.KeyId, x509.Thumbprint)); } if (x509.HasPrivateKey && x509.PrivateKey == null) { var csp = x509.PrivateKey as RSACryptoServiceProvider; if (csp == null) { throw new NotImplementedException(string.Format("encryptedKey does not have a valid RSACryptoServiceProvider private key. Type was '{0}'.", x509.PrivateKey.GetType().FullName)); } if (csp.CspKeyContainerInfo.Exportable) { throw new System.Security.SecurityException("The decrypted X509Certificate2 was marked as exportable in the CspKeyContainerInfo. This is not permitted on a protected key."); } } protectedKeyAsKeyEncryptionKey = Utilities.X509CertificateHelper.GetKeyEncryptionKey(x509); } catch (Exception ex) { throw new InvalidOperationException(string.Format("X509Certificate2 could not be validated. Thumbprint '{0}'. See inner exception for details.", ex)); } return protectedKeyAsKeyEncryptionKey; }
public void TestAsymmetricallyEncryptedBackupObject() { var cert2 = LoadCertificate(); var publicKey = new X509CertificatePublicKey(cert2); var privateKey = new X509Certificate2KeyEncryptionKey(cert2); var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; var encryptor = new AsymmetricEncryptor() { AsymmetricStrategy = AsymmetricStrategyOption.Aes256_200000 }; var asymEncObj = encryptor.EncryptObjectAsync(stringToEncrypt, publicKey).GetAwaiter().GetResult(); asymEncObj.PublicMetadata = new Dictionary<string, string>(); asymEncObj.PublicMetadata["keyA"] = "valueA"; asymEncObj.PublicMetadata["keyB"] = "valueB"; var asymEncObj2 = encryptor.EncryptObjectAsync(stringToEncrypt, publicKey).GetAwaiter().GetResult(); asymEncObj.PublicMetadata = new Dictionary<string, string>(); asymEncObj.PublicMetadata["keyA-2"] = "valueA-2"; asymEncObj.PublicMetadata["keyB-2"] = "valueB-2"; var backup = new AsymmetricallyEncryptedBackupObject() { AssociationObjectIdentifier = Guid.NewGuid().ToString(), AssociationObjectType = "test", BackupObjects = new Dictionary<string, AsymmetricallyEncryptedObject>() }; backup.BackupObjects["objA"] = asymEncObj; backup.BackupObjects["objB"] = asymEncObj2; var asymBackup = encryptor.EncryptObjectAsync(backup, publicKey).GetAwaiter().GetResult(); var decrypted = encryptor.DecryptObject(asymBackup, privateKey); Assert.IsTrue(decrypted is AsymmetricallyEncryptedBackupObject); var asBytes = asymBackup.ToByteArray(); var newAsymmObj = new AsymmetricallyEncryptedObject(); newAsymmObj.LoadFromByteArray(asBytes); var decrypted2 = encryptor.DecryptObject(newAsymmObj, privateKey); Assert.IsTrue(decrypted2 is AsymmetricallyEncryptedBackupObject); // let's decrypt the embedded types var backupObjFromBytes = decrypted2 as AsymmetricallyEncryptedBackupObject; Assert.AreEqual(backupObjFromBytes.AssociationObjectIdentifier, backup.AssociationObjectIdentifier); Assert.AreEqual(backupObjFromBytes.AssociationObjectType, backup.AssociationObjectType); var objA = backupObjFromBytes.BackupObjects["objA"]; var decryptedObjA = encryptor.DecryptObject(objA, privateKey); Assert.AreEqual(stringToEncrypt, decryptedObjA); var objB = backupObjFromBytes.BackupObjects["objB"]; var decryptedObjB = encryptor.DecryptObject(objB, privateKey); Assert.AreEqual(stringToEncrypt, decryptedObjB); }
public void TestAes5WithDualCertificate() { var cert2 = LoadCertificate(); var publicKey = new X509CertificatePublicKey(cert2); var privateKey = new X509Certificate2KeyEncryptionKey(cert2); var cert2Dual = LoadCertificate2(); var publicKey2 = new X509CertificatePublicKey(cert2Dual); var privateKey2 = new X509Certificate2KeyEncryptionKey(cert2Dual); int length = 100; var rand = new RandomGenerator(); for (int i = 0; i < length; i++) { var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_5); var asymObj = asymEnc.EncryptObject(stringToEncrypt, publicKey, publicKey2); var decrypted = asymEnc.DecryptObject(asymObj, privateKey, privateKey2); Assert.AreEqual(stringToEncrypt, decrypted); } }
public EncryptedCredential(string userName, string password, RSAParameters parameters) { UserName = AsymmetricEncryptor.Encrypt(userName, parameters); Password = AsymmetricEncryptor.Encrypt(password, parameters); }
public void TestAes1000WithCertificate() { var cert2 = LoadCertificate(); //var publicKey = X509CertificateHelper.GetRSACryptoServiceProviderFromPublicKey(cert2); var keyProtector = X509CertificateHelper.GetKeyEncryptionKey(cert2); // generate a protected key var gen = new ProtectedX509Certificate2Generator(); var policy = new CertificatePolicy() { CommonName = "Testing protected certs", AllPurposes = true, ValidForDays = 2 }; var protectedKey = Task.Run(() => gen.IssueNewCertificateAsync(keyProtector, policy)).GetAwaiter().GetResult(); // save the key to test var keyOutputFilePath = (CERT_FOLDER + "temp\\pk-" + protectedKey.KeyId + ".kpk"); var fi = new FileInfo(keyOutputFilePath); if (!fi.Directory.Exists) { fi.Directory.Create(); } var bytes = Task.Run(() => protectedKey.ToByteArrayAsync()).GetAwaiter().GetResult(); File.WriteAllBytes(fi.FullName, bytes); Console.WriteLine(fi.FullName); var list = new List<string>(); var listEnc = new List<AsymmetricallyEncryptedObject>(); using (var privateKey = Task.Run(() => protectedKey.ToKeyEncyrptionKeyAsync(keyProtector)).GetAwaiter().GetResult()) { //var publicKey = privateKey.PublicKey.Key as RSACryptoServiceProvider; //File.WriteAllText(fi.FullName + "_A.cer", privateKey.PublicKeyToPEM()); int length = 100; var rand = new RandomGenerator(); for (int i = 0; i < length; i++) { var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; list.Add(stringToEncrypt); var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000); var asymObj = asymEnc.EncryptObjectAsync(stringToEncrypt, privateKey).GetAwaiter().GetResult(); listEnc.Add(asymObj); var decrypted = asymEnc.DecryptObjectAsync(asymObj, privateKey).GetAwaiter().GetResult(); Assert.AreEqual(stringToEncrypt, decrypted); } } // lets reload a new private key var fileBytes = File.ReadAllBytes(fi.FullName); var encKey = new AsymmetricallyEncryptedObject(); encKey.LoadFromByteArray(fileBytes); var protectedKey2 = new ProtectedX509Certificate2(protectedKey.KeyId, encKey); using (var privateKey = Task.Run(() => protectedKey2.ToKeyEncyrptionKeyAsync(keyProtector)).GetAwaiter().GetResult()) { var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000); int i = 0; foreach (var line in list) { var asymObj = listEnc[i]; var decrypted = asymEnc.DecryptObject(asymObj, privateKey); Assert.AreEqual(line, decrypted); i++; } } }
public void TestAes1000WithCertificate() { var cert2 = LoadCertificate(); //var publicKey = X509CertificateHelper.GetRSACryptoServiceProviderFromPublicKey(cert2); var keyProtector = X509CertificateHelper.GetKeyEncryptionKey(cert2); // generate a protected key var gen = new ProtectedX509Certificate2Generator(); var policy = new CertificatePolicy() { CommonName = "Testing protected certs", AllPurposes = true, ValidForDays = 2 }; var protectedKey = Task.Run(() => gen.IssueNewCertificateAsync(keyProtector, policy)).GetAwaiter().GetResult(); // save the key to test var keyOutputFilePath = (CERT_FOLDER + "temp\\pk-" + protectedKey.KeyId + ".kpk"); var fi = new FileInfo(keyOutputFilePath); if (!fi.Directory.Exists) { fi.Directory.Create(); } var bytes = Task.Run(() => protectedKey.ToByteArrayAsync()).GetAwaiter().GetResult(); File.WriteAllBytes(fi.FullName, bytes); Console.WriteLine(fi.FullName); var list = new List <string>(); var listEnc = new List <AsymmetricallyEncryptedObject>(); using (var privateKey = Task.Run(() => protectedKey.ToKeyEncyrptionKeyAsync(keyProtector)).GetAwaiter().GetResult()) { //var publicKey = privateKey.PublicKey.Key as RSACryptoServiceProvider; //File.WriteAllText(fi.FullName + "_A.cer", privateKey.PublicKeyToPEM()); int length = 100; var rand = new RandomGenerator(); for (int i = 0; i < length; i++) { var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; list.Add(stringToEncrypt); var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000); var asymObj = asymEnc.EncryptObjectAsync(stringToEncrypt, privateKey).GetAwaiter().GetResult(); listEnc.Add(asymObj); var decrypted = asymEnc.DecryptObjectAsync(asymObj, privateKey).GetAwaiter().GetResult(); Assert.AreEqual(stringToEncrypt, decrypted); } } // lets reload a new private key var fileBytes = File.ReadAllBytes(fi.FullName); var encKey = new AsymmetricallyEncryptedObject(); encKey.LoadFromByteArray(fileBytes); var protectedKey2 = new ProtectedX509Certificate2(protectedKey.KeyId, encKey); using (var privateKey = Task.Run(() => protectedKey2.ToKeyEncyrptionKeyAsync(keyProtector)).GetAwaiter().GetResult()) { var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000); int i = 0; foreach (var line in list) { var asymObj = listEnc[i]; var decrypted = asymEnc.DecryptObject(asymObj, privateKey); Assert.AreEqual(line, decrypted); i++; } } }
public InitializeSessionToken(string value, string nonce, string publicKey) : base(value) { _nonce = nonce; _encryptor = new AsymmetricEncryptor(publicKey); }
public void TestAes1000WithCertificateAndSerialization() { var cert2 = LoadCertificate(); var publicKey = new X509CertificatePublicKey(cert2); var privateKey = new X509Certificate2KeyEncryptionKey(cert2); int length = 100; var rand = new RandomGenerator(); //for (int i = 0; i < length; i++) //{ // var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; // var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000); // var asymObj = asymEnc.EncryptObject(stringToEncrypt, cert2.Thumbprint.ToString().ToLower(), publicKey); // var decrypted = asymEnc.DecryptObject(asymObj, privateKey); // Assert.AreEqual(stringToEncrypt, decrypted); //} var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; var encryptor = new AsymmetricEncryptor() { AsymmetricStrategy = AsymmetricStrategyOption.Aes256_1000 }; var asymEncObj = encryptor.EncryptObjectAsync(stringToEncrypt, publicKey).GetAwaiter().GetResult(); asymEncObj.PublicMetadata = new Dictionary<string, string>(); asymEncObj.PublicMetadata["keyA"] = "valueA"; asymEncObj.PublicMetadata["keyB"] = "valueB"; asymEncObj.KeyId = cert2.Thumbprint.ToLower(); var asymEncObjDirectSerializedBytes = Serializer.SerializeToByteArray(asymEncObj); // deserialize var asymEncObj2 = Serializer.DeserializeFromByteArray(asymEncObjDirectSerializedBytes) as AsymmetricallyEncryptedObject; Assert.IsNotNull(asymEncObj); Assert.IsTrue(!string.IsNullOrEmpty(asymEncObj.KeyId)); var asymEncObjBytes2 = asymEncObj.ToByteArray(); var asymEncObj3 = new AsymmetricallyEncryptedObject(); asymEncObj3.LoadFromByteArray(asymEncObjBytes2); var decrypted = encryptor.DecryptObject(asymEncObj3, privateKey) as string; Assert.AreEqual(decrypted, stringToEncrypt); // test deserializing with direct var asymEncObj4 = new AsymmetricallyEncryptedObject(); asymEncObj4.LoadFromByteArray(asymEncObjDirectSerializedBytes); var decrypted2 = encryptor.DecryptObject(asymEncObj4, privateKey) as string; Assert.AreEqual(decrypted2, stringToEncrypt); }
public void TestAsymmetricallyEncryptedBackupObject() { var cert2 = LoadCertificate(); var publicKey = new X509CertificatePublicKey(cert2); var privateKey = new X509Certificate2KeyEncryptionKey(cert2); var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; var encryptor = new AsymmetricEncryptor() { AsymmetricStrategy = AsymmetricStrategyOption.Aes256_20000 }; var asymEncObj = encryptor.EncryptObjectAsync(stringToEncrypt, publicKey).GetAwaiter().GetResult(); asymEncObj.PublicMetadata = new Dictionary <string, string>(); asymEncObj.PublicMetadata["keyA"] = "valueA"; asymEncObj.PublicMetadata["keyB"] = "valueB"; var asymEncObj2 = encryptor.EncryptObjectAsync(stringToEncrypt, publicKey).GetAwaiter().GetResult(); asymEncObj.PublicMetadata = new Dictionary <string, string>(); asymEncObj.PublicMetadata["keyA-2"] = "valueA-2"; asymEncObj.PublicMetadata["keyB-2"] = "valueB-2"; var backup = new AsymmetricallyEncryptedBackupObject() { AssociationObjectIdentifier = Guid.NewGuid().ToString(), AssociationObjectType = "test", BackupObjects = new Dictionary <string, AsymmetricallyEncryptedObject>() }; backup.BackupObjects["objA"] = asymEncObj; backup.BackupObjects["objB"] = asymEncObj2; var asymBackup = encryptor.EncryptObjectAsync(backup, publicKey).GetAwaiter().GetResult(); var decrypted = encryptor.DecryptObject(asymBackup, privateKey); Assert.IsTrue(decrypted is AsymmetricallyEncryptedBackupObject); var asBytes = asymBackup.ToByteArray(); var newAsymmObj = new AsymmetricallyEncryptedObject(); newAsymmObj.LoadFromByteArray(asBytes); var decrypted2 = encryptor.DecryptObject(newAsymmObj, privateKey); Assert.IsTrue(decrypted2 is AsymmetricallyEncryptedBackupObject); // let's decrypt the embedded types var backupObjFromBytes = decrypted2 as AsymmetricallyEncryptedBackupObject; Assert.AreEqual(backupObjFromBytes.AssociationObjectIdentifier, backup.AssociationObjectIdentifier); Assert.AreEqual(backupObjFromBytes.AssociationObjectType, backup.AssociationObjectType); var objA = backupObjFromBytes.BackupObjects["objA"]; var decryptedObjA = encryptor.DecryptObject(objA, privateKey); Assert.AreEqual(stringToEncrypt, decryptedObjA); var objB = backupObjFromBytes.BackupObjects["objB"]; var decryptedObjB = encryptor.DecryptObject(objB, privateKey); Assert.AreEqual(stringToEncrypt, decryptedObjB); }
public async Task UpdateKeyProtectorAsync(IPrivateKey currentKeyProtector, IPublicKey newKeyProtector) { if (currentKeyProtector == null) { throw new ArgumentNullException("currentKeyProtector"); } if (currentKeyProtector.KeyId != _encryptedKey.KeyId) { throw new ArgumentException(string.Format("currentKeyProtector.KeyId '{0}' does not match encryptedKey.KeyId '{1}'.", currentKeyProtector.KeyId, _encryptedKey.KeyId)); } if (newKeyProtector == null) { throw new ArgumentNullException("newKeyProtector"); } // decrypt the key and populate to the x509 var asymEnc = new AsymmetricEncryptor(); var decrypted = await asymEnc.DecryptObjectAsync(_encryptedKey, currentKeyProtector); var pfxBytes = decrypted as byte[]; if (pfxBytes == null || !pfxBytes.Any()) { throw new CryptographicException(string.Format("encryptedKey successfull decrypted but was not a valid PFX byte array. Type was '{0}'.", decrypted.GetType().FullName)); } // re-encrypt the key var newAsymEncObj = await asymEnc.EncryptObjectAsync(pfxBytes, newKeyProtector); _encryptedKey = newAsymEncObj; }