Example #1
0
        public void RSALocalKeyDecryptionPaddingHashInvalidThrows()
        {
            byte[] toEncrypt          = new byte[] { 1, 2, 3, 4 };
            ManagedRSAEncryption util = new ManagedRSAEncryption();

            byte[] encrypted = util.EncryptWithLocalKey(TestProvider, TestKeyName, toEncrypt, "Not a real padding hash function", PaddingFlags.OAEPPadding);
        }
Example #2
0
        public void ProviderKeyCleanup(string providerName, string keyName)
        {
            //Clear out the test key
            ManagedRSAEncryption managedRSA = new ManagedRSAEncryption();

            managedRSA.DestroyLocalRSAKey(providerName, keyName);
        }
Example #3
0
        public void RSALocalKeyDecryptionPaddingInvalidThrows()
        {
            byte[] toEncrypt          = new byte[] { 1, 2, 3, 4 };
            ManagedRSAEncryption util = new ManagedRSAEncryption();

            byte[] encrypted = util.EncryptWithLocalKey(TestProvider, TestKeyName, toEncrypt, null, PaddingFlags.PSSPadding + 10000);
        }
        public void TestCleanup()
        {
            //Clear out the test key
            ManagedRSAEncryption managedRSA = new ManagedRSAEncryption();

            managedRSA.DestroyLocalRSAKey(TestProvider, TestKeyName);
        }
Example #5
0
        public void TestInitialize()
        {
            ManagedRSAEncryption utility = new ManagedRSAEncryption();

            //Create the test key

            utility.TryGenerateLocalRSAKey(TestProvider, TestKeyName);
        }
Example #6
0
        public void RSALocalKeyDecryptionProviderMissingThrows()
        {
            byte[] toEncrypt          = new byte[] { 1, 2, 3, 4 };
            ManagedRSAEncryption util = new ManagedRSAEncryption();

            byte[] encrypted = util.EncryptWithLocalKey(TestProvider, TestKeyName, toEncrypt);
            byte[] decrypted = util.DecryptWithLocalKey("FakeProviderName", TestKeyName, encrypted);
        }
Example #7
0
        public void TestCleanup()
        {
            ManagedRSAEncryption utility = new ManagedRSAEncryption();

            //Destroy the test key


            utility.DestroyLocalRSAKey(TestProvider, TestKeyName);
        }
Example #8
0
        public void TestLine(string line)
        {
            eventLog1.WriteEntry(string.Format("Testing Line:{0}", line));
            string[] split = line.Split(TestFileSeparator);
            if (split.Length != 6)
            {
                StringBuilder testFormatBuilder = new StringBuilder();
                testFormatBuilder.AppendLine(string.Format("Test line is of incorrect format, should be of format unencrypted{0}encrypted{0}providername{0}keyname{0}hashalgorithm{0}paddingflags for line {1}", TestFileSeparator, line));
                testFormatBuilder.AppendLine(string.Format("Encrypted value should be Base64 encoded"));
                testFormatBuilder.AppendLine(string.Format("HashAlgorithm can be SHA1, SHA256, SHA384, SHA512"));
                testFormatBuilder.AppendLine(string.Format("PaddingFlags can be 1, 2, 4, 8"));
                eventLog1.WriteEntry(testFormatBuilder.ToString(), EventLogEntryType.Error);
                return;
            }

            string unencrypted   = split[0];
            string encrypted     = split[1];
            string provider      = split[2];
            string keyname       = split[3];
            string hashAlgorithm = split[4];
            int    paddingFlags  = int.Parse(split[5]);


            byte[] encryptedAsBytes = Convert.FromBase64String(encrypted);

            string               resultString = "";
            EventLogEntryType    entryType    = EventLogEntryType.Information;
            ManagedRSAEncryption crypto       = new ManagedRSAEncryption();

            try
            {
                byte[] decrypted       = crypto.DecryptWithLocalKey(provider, keyname, encryptedAsBytes, hashAlgorithm, paddingFlags);
                string decryptedString = Encoding.ASCII.GetString(decrypted);

                if (String.Equals(unencrypted, decryptedString))
                {
                    resultString = string.Format("Successfully decrypted to value {0} for line {1}", unencrypted, line);
                }
                else
                {
                    resultString = string.Format("Failed to decrypt to value {0}, decrypted value was {1} for line {2}", unencrypted, decryptedString, line);
                    entryType    = EventLogEntryType.Error;
                }
            }
            catch (Exception e)
            {
                resultString = string.Format("Failed to decrypt line with exception {0} the line was: {1}", e, line);
                entryType    = EventLogEntryType.Error;
            }

            eventLog1.WriteEntry(resultString, entryType);
            string assemblyPath = Path.GetDirectoryName(typeof(IntunePFXCertConnectorValidationService).Assembly.Location);

            eventLog1.WriteEntry(string.Format("Wrinting results to {0}", Path.Combine(assemblyPath, ResultFile)));
            File.WriteAllText(Path.Combine(assemblyPath, ResultFile), contents: resultString);
        }
Example #9
0
        private void ValidatePasswordDecryptable(UserPFXCertificate userPFXResult, string expectedPassword, string hashAlgorithm, int paddingFlags)
        {
            ManagedRSAEncryption encryptionUtility = new ManagedRSAEncryption();

            byte[] passwordBytes       = Convert.FromBase64String(userPFXResult.EncryptedPfxPassword);
            byte[] unencryptedPassword = encryptionUtility.DecryptWithLocalKey(userPFXResult.ProviderName, userPFXResult.KeyName, passwordBytes, hashAlgorithm, paddingFlags);
            string clearTextPassword   = Encoding.ASCII.GetString(unencryptedPassword);

            Assert.AreEqual(clearTextPassword, expectedPassword);
        }
Example #10
0
        private void ProviderKeyInitialize(string providerName, string keyName, string algorithmName)
        {
            ManagedRSAEncryption managedRSA = new ManagedRSAEncryption();

            if (!managedRSA.TryGenerateLocalRSAKey(providerName, keyName))
            {
                //Delete and try again
                managedRSA.DestroyLocalRSAKey(providerName, keyName);
                managedRSA.TryGenerateLocalRSAKey(providerName, keyName);
            }
        }
        public void TestInitialize()
        {
            ManagedRSAEncryption managedRSA = new ManagedRSAEncryption();

            if (!managedRSA.TryGenerateLocalRSAKey(TestProvider, TestKeyName))
            {
                //Delete and try again
                managedRSA.DestroyLocalRSAKey(TestProvider, TestKeyName);
                managedRSA.TryGenerateLocalRSAKey(TestProvider, TestKeyName);
            }
        }
        public void CertKeyEncryptionE2E()
        {
            byte[] toEncrypt              = new byte[] { 1, 2, 3, 4 };
            ManagedRSAEncryption managed  = new ManagedRSAEncryption();
            X509Certificate2     testCert = new X509Certificate2(Convert.FromBase64String(TestCertBase64Encoded), TestCertPassword);

            byte[] encrypted = managed.EncryptWithCertificate(toEncrypt, testCert);
            byte[] decrypted = managed.DecryptWithCertificate(encrypted, testCert);

            CollectionAssert.AreNotEqual(toEncrypt, encrypted);
            CollectionAssert.AreNotEqual(encrypted, decrypted);
            CollectionAssert.AreEqual(toEncrypt, decrypted);
        }
Example #13
0
        protected override void ProcessRecord()
        {
            ManagedRSAEncryption managedRSA = new ManagedRSAEncryption();

            if (!managedRSA.ImportKeyToKSP(ProviderName, KeyName, FilePath, MakeExportable.IsPresent))
            {
                //Creation failed, likely already exists
                this.WriteError(
                    new ErrorRecord(
                        new InvalidOperationException("Key Import failed"),
                        "KeyImportFailure",
                        ErrorCategory.InvalidOperation,
                        null));
            }
        }
        public void EncryptionUtilitiesFullE2E()
        {
            byte[] originalData           = new byte[] { 1, 2, 3, 4 };
            ManagedRSAEncryption managed  = new ManagedRSAEncryption();
            X509Certificate2     testCert = new X509Certificate2(Convert.FromBase64String(TestCertBase64Encoded), TestCertPassword);

            byte[] encryptedWithLocal      = managed.EncryptWithLocalKey(TestProvider, TestKeyName, originalData);
            byte[] recryptedWithDeviceCert = managed.RecryptPfxImportMessage(encryptedWithLocal, testCert, TestProvider, TestKeyName);
            byte[] decryptedWithDeviceCert = managed.DecryptWithCertificate(recryptedWithDeviceCert, testCert);

            CollectionAssert.AreEqual(originalData, decryptedWithDeviceCert);
            CollectionAssert.AreNotEqual(originalData, encryptedWithLocal);
            CollectionAssert.AreNotEqual(originalData, recryptedWithDeviceCert);
            CollectionAssert.AreNotEqual(encryptedWithLocal, recryptedWithDeviceCert);
            CollectionAssert.AreNotEqual(encryptedWithLocal, decryptedWithDeviceCert);
            CollectionAssert.AreNotEqual(recryptedWithDeviceCert, decryptedWithDeviceCert);
        }
Example #15
0
        public void RSALocalKeyEncryptionDecryptionE2E()
        {
            byte[] toEncrypt          = new byte[] { 1, 2, 3, 4 };
            ManagedRSAEncryption util = new ManagedRSAEncryption();

            byte[] encrypted = util.EncryptWithLocalKey(TestProvider, TestKeyName, toEncrypt);
            byte[] decrypted = util.DecryptWithLocalKey(TestProvider, TestKeyName, encrypted);

            CollectionAssert.AreNotEqual(encrypted, toEncrypt);
            CollectionAssert.AreNotEqual(encrypted, decrypted);
            CollectionAssert.AreEqual(toEncrypt, decrypted);

            Assert.AreNotEqual(0, encrypted.Length);
            Assert.AreNotEqual(0, decrypted.Length);
            Assert.IsNotNull(encrypted);
            Assert.IsNotNull(decrypted);
        }
Example #16
0
        public void RSALocalKeyEncryptionDecryptionOAEPE2E()
        {
            byte[] toEncrypt          = new byte[] { 1, 2, 3, 4 };
            ManagedRSAEncryption util = new ManagedRSAEncryption();

            byte[] encrypted = util.EncryptWithLocalKey(TestProvider, TestKeyName, toEncrypt, PaddingHashAlgorithmNames.SHA256, PaddingFlags.OAEPPadding);
            byte[] decrypted = util.DecryptWithLocalKey(TestProvider, TestKeyName, encrypted, PaddingHashAlgorithmNames.SHA256, PaddingFlags.OAEPPadding);

            CollectionAssert.AreNotEqual(encrypted, toEncrypt);
            CollectionAssert.AreNotEqual(encrypted, decrypted);
            CollectionAssert.AreEqual(toEncrypt, decrypted);

            Assert.AreNotEqual(0, encrypted.Length);
            Assert.AreNotEqual(0, decrypted.Length);
            Assert.IsNotNull(encrypted);
            Assert.IsNotNull(decrypted);
        }
        protected override void ProcessRecord()
        {
            ManagedRSAEncryption managedRSA = new ManagedRSAEncryption();

            if (managedRSA.TryGenerateLocalRSAKey(ProviderName, KeyName, KeyLength))
            {
                //Creation succeeded
            }
            else
            {
                //Creation failed, likely already exists
                this.WriteError(
                    new ErrorRecord(
                        new InvalidOperationException("Key Creation failed, it likely already exists"),
                        "KeyAlreadyExists",
                        ErrorCategory.InvalidOperation,
                        null));
            }
        }
Example #18
0
        public void ExportImportEncryptTest()
        {
            byte[] toEncrypt = new byte[] { 1, 2, 3, 4 };
            string filePath  = @".\TestPublic.Key";

            try
            {
                File.Delete(filePath);
            }
            catch (Exception) { }
            ManagedRSAEncryption util = new ManagedRSAEncryption();

            util.ExportPublicKeytoFile(TestProvider, TestKeyName, filePath);
            Assert.IsTrue(File.Exists(filePath));
            byte[] encryptedBytes = util.EncryptWithFileKey(filePath, toEncrypt);
            Assert.IsNotNull(encryptedBytes);
            byte[] decryptedBytes = util.DecryptWithLocalKey(TestProvider, TestKeyName, encryptedBytes);
            Assert.AreEqual(System.Convert.ToBase64String(toEncrypt), System.Convert.ToBase64String(decryptedBytes));
            try
            {
                File.Delete(filePath);
            }
            catch (Exception) { }
        }
        protected override void ProcessRecord()
        {
            ManagedRSAEncryption managedRSA = new ManagedRSAEncryption();

            managedRSA.ExportPublicKeytoFile(ProviderName, KeyName, FilePath, FileFormat);
        }
        protected override void ProcessRecord()
        {
            byte[] pfxData;
            if (this.ParameterSetName == PFXBase64String)
            {
                pfxData = Convert.FromBase64String(Base64EncodedPfx);
            }
            else
            {
                pfxData = File.ReadAllBytes(PathToPfxFile);
            }

            X509Certificate2 pfxCert = new X509Certificate2();

            try
            {
                pfxCert.Import(pfxData, PfxPassword, X509KeyStorageFlags.DefaultKeySet);
            }
            catch (CryptographicException ex)
            {
                if (ex.HResult == ErrorCodeCantOpenFile)
                {
                    ThrowTerminatingError(
                        new ErrorRecord(
                            new ArgumentException(
                                string.Format("Could not Read Thumbprint on file at path: '{0}'. File must be a certificate.", PathToPfxFile), ex),
                            Guid.NewGuid().ToString(),
                            ErrorCategory.InvalidArgument,
                            null));
                }
                else if (ex.HResult == ErrorCodeNetworkPasswordIncorrect)
                {
                    ThrowTerminatingError(
                        new ErrorRecord(
                            new ArgumentException("Could not Read Thumbprint. Verify Password is Correct.", ex),
                            Guid.NewGuid().ToString(),
                            ErrorCategory.InvalidArgument,
                            null));
                }
                else
                {
                    ThrowTerminatingError(
                        new ErrorRecord(
                            new ArgumentException("Could not Read Thumbprint. Unknown Cause", ex),
                            Guid.NewGuid().ToString(),
                            ErrorCategory.InvalidArgument,
                            null));
                }
            }

            ManagedRSAEncryption encryptUtility = new ManagedRSAEncryption();

            byte[]   password             = new byte[PfxPassword.Length];
            GCHandle pinnedPasswordHandle = GCHandle.Alloc(password, GCHandleType.Pinned);

            byte[] encryptedPassword = null;
            try
            {
                ConvertSecureStringToByteArray(PfxPassword, ref password);

                string hashAlgorithm;
                int    paddingFlags;

                switch (PaddingScheme)
                {
                case UserPfxPaddingScheme.Pkcs1:
                case UserPfxPaddingScheme.OaepSha1:
                    ThrowTerminatingError(
                        new ErrorRecord(
                            new ArgumentException("Pkcs1 and OaepSha1 are no longer supported."),
                            Guid.NewGuid().ToString(),
                            ErrorCategory.InvalidArgument,
                            null));
                    return;

                case UserPfxPaddingScheme.OaepSha256:
                    hashAlgorithm = PaddingHashAlgorithmNames.SHA256;
                    paddingFlags  = PaddingFlags.OAEPPadding;
                    break;

                case UserPfxPaddingScheme.OaepSha384:
                    hashAlgorithm = PaddingHashAlgorithmNames.SHA384;
                    paddingFlags  = PaddingFlags.OAEPPadding;
                    break;

                case UserPfxPaddingScheme.None:
                    PaddingScheme = UserPfxPaddingScheme.OaepSha512;
                    goto default;       // Since C# doesn't allow switch-case fall-through!

                case UserPfxPaddingScheme.OaepSha512:
                default:
                    hashAlgorithm = PaddingHashAlgorithmNames.SHA512;
                    paddingFlags  = PaddingFlags.OAEPPadding;
                    break;
                }

                if (KeyFilePath != null)
                {
                    encryptedPassword = encryptUtility.EncryptWithFileKey(KeyFilePath, password, hashAlgorithm, paddingFlags);
                }
                else
                {
                    encryptedPassword = encryptUtility.EncryptWithLocalKey(ProviderName, KeyName, password, hashAlgorithm, paddingFlags);
                }
            }
            finally
            {
                if (password != null)
                {
                    password.ZeroFill();
                }

                if (pinnedPasswordHandle.IsAllocated)
                {
                    pinnedPasswordHandle.Free();
                }
            }

            string encryptedPasswordString = Convert.ToBase64String(encryptedPassword);

            UserPFXCertificate userPfxCertifiate = new UserPFXCertificate();

            userPfxCertifiate.Thumbprint           = pfxCert.Thumbprint.ToLowerInvariant();
            userPfxCertifiate.IntendedPurpose      = (UserPfxIntendedPurpose)IntendedPurpose;
            userPfxCertifiate.PaddingScheme        = (UserPfxPaddingScheme)PaddingScheme;
            userPfxCertifiate.KeyName              = KeyName;
            userPfxCertifiate.UserPrincipalName    = UPN;
            userPfxCertifiate.ProviderName         = ProviderName;
            userPfxCertifiate.StartDateTime        = Convert.ToDateTime(pfxCert.GetEffectiveDateString(), CultureInfo.CurrentCulture);
            userPfxCertifiate.ExpirationDateTime   = Convert.ToDateTime(pfxCert.GetExpirationDateString(), CultureInfo.CurrentCulture);
            userPfxCertifiate.CreatedDateTime      = DateTime.Now;
            userPfxCertifiate.LastModifiedDateTime = DateTime.Now;
            userPfxCertifiate.EncryptedPfxPassword = encryptedPasswordString;
            userPfxCertifiate.EncryptedPfxBlob     = pfxData;

            WriteObject(userPfxCertifiate);
        }
Example #21
0
        protected override void ProcessRecord()
        {
            ManagedRSAEncryption managedRSA = new ManagedRSAEncryption();

            managedRSA.ExportPrivateKeytoFile(ProviderName, KeyName, FilePath);
        }