コード例 #1
0
        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 ProtectedX509Certificate2(string keyId, byte[] keyAsBytes)
 {
     if (keyAsBytes == null)
     {
         throw new ArgumentNullException("keyAsBytes");
     }
     var encryptedKey = new AsymmetricallyEncryptedObject();
     encryptedKey.LoadFromByteArray(keyAsBytes);
     if (!string.IsNullOrEmpty(encryptedKey.Key2Id))
     {
         throw new NotImplementedException(string.Format("encryptedKey has a value of '{0}' on Key2Id. Dual key encryption is not supported on IProtectedKey implementations.", encryptedKey.Key2Id));
     }
     if (keyId == null)
     {
         throw new ArgumentNullException("keyId");
     }
     if (keyId.Length != 40)
     {
         throw new ArgumentNullException("keyId must be 40 characters");
     }
     this.KeyId = keyId;
     _encryptedKey = encryptedKey;
 }
        public ProtectedX509Certificate2(string keyId, byte[] keyAsBytes)
        {
            if (keyAsBytes == null)
            {
                throw new ArgumentNullException("keyAsBytes");
            }
            var encryptedKey = new AsymmetricallyEncryptedObject();

            encryptedKey.LoadFromByteArray(keyAsBytes);
            if (!string.IsNullOrEmpty(encryptedKey.Key2Id))
            {
                throw new NotImplementedException(string.Format("encryptedKey has a value of '{0}' on Key2Id. Dual key encryption is not supported on IProtectedKey implementations.", encryptedKey.Key2Id));
            }
            if (keyId == null)
            {
                throw new ArgumentNullException("keyId");
            }
            if (keyId.Length != 40)
            {
                throw new ArgumentNullException("keyId must be 40 characters");
            }
            this.KeyId    = keyId;
            _encryptedKey = encryptedKey;
        }
コード例 #4
0
        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 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++;
                }
            }



        }
コード例 #7
0
        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);

        }
コード例 #8
0
        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);


        }