Esempio n. 1
0
        public static X509Certificate GenerateSelfSignedCertificate(out AsymmetricKeyParameter privateKey)
        {
            var keypair = GenerateGostKeyPair(
                RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetA,
                RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512);

            var generator = new X509V3CertificateGenerator();

            generator.SetSerialNumber(new BigInteger(16 * 8, _random));
            generator.SetIssuerDN(new X509Name("CN=Fake CA"));
            generator.SetSubjectDN(new X509Name("CN=Fake Subject"));
            generator.SetNotBefore(DateTime.Today.AddDays(-1));
            generator.SetNotAfter(DateTime.Today.AddYears(1));
            generator.SetPublicKey(keypair.Public);

            var keyUsage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.NonRepudiation);

            generator.AddExtension(X509Extensions.KeyUsage, true, keyUsage);

            var signFactory = new GostSignatureFactory(
                RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512.ToString(),
                keypair.Private);

            privateKey = keypair.Private;

            return(generator.Generate(signFactory));
        }
 private byte[] DeriveTempKey(KerberosAuthenticationKey key, KeyUsage key_usage, byte key_type)
 {
     byte[] r = BitConverter.GetBytes((int)key_usage).Reverse().ToArray();
     Array.Resize(ref r, 5);
     r[4] = key_type;
     return(NFold.Compute(r, 16));
 }
        public void MicrosoftCertificateAuthority_Sign_CngEcdh256_CertificateAuthorityRequestResponse_Issued()
        {
            string templateName = "ServerAuthentication-CngEcdh";

            int                keysize    = 256;
            string             commonName = "domain.com";
            WindowsApi         api        = WindowsApi.Cng;
            CipherAlgorithm    cipher     = CipherAlgorithm.ECDH;
            KeyUsage           keyUsage   = KeyUsage.ServerAuthentication;
            CertificateSubject subject    = new CertificateSubject(commonName);

            Win32CertificateProvider provider = new Win32CertificateProvider();

            CertificateRequest csr = provider.CreateCsrKeyPair(subject, cipher, keysize, api, SigningRequestProtocol.Pkcs10);

            MicrosoftCertificateAuthority ca = new MicrosoftCertificateAuthority(new MicrosoftCertificateAuthorityOptions()
            {
                AuthenticationRealm = domain,
                AuthenticationType  = MicrosoftCertificateAuthorityAuthenticationType.UsernamePassword,
                HashAlgorithm       = HashAlgorithm.SHA256,
                ServerName          = caServerName,
                CommonName          = caCommonName,
                Username            = username,
                Password            = password
            });

            CertificateAuthorityRequestResponse response = ca.Sign(csr, templateName, keyUsage);

            Assert.AreEqual(CertificateRequestStatus.Issued, response.CertificateRequestStatus);
        }
        private static KeyUsage CertificateTypeToKeyUsage(CertificateType type)
        {
            KeyUsage k = KeyUsage.None;

            switch (type)
            {
            case CertificateType.DigitalSignature:
                k = KeyUsage.DigitalSignature;
                break;

            case CertificateType.KeyAgreement:
                k = KeyUsage.KeyAgreement;
                break;

            case CertificateType.TLS:
                k = KeyUsage.KeyCertSign;
                break;

            case CertificateType.Other:
                k = KeyUsage.CrlSign;
                break;

            default:
                // At least one bit must be used.
                k = KeyUsage.None;
                break;
            }
            return(k);
        }
Esempio n. 5
0
        public T Decrypt <T>(KerberosKey key, KeyUsage usage, Func <ReadOnlyMemory <byte>, T> func)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (func == null)
            {
                throw new ArgumentNullException(nameof(func));
            }

            if (!key.RequiresDerivation && key.EncryptionType != this.EType)
            {
                throw new InvalidOperationException($"Key EType {key.EncryptionType} must match the encrypted data EType {this.EType}");
            }

            var crypto = CryptoService.CreateTransform(this.EType);

            if (crypto == null)
            {
                throw new InvalidOperationException($"CryptoService couldn't create a transform for type {key.EncryptionType}");
            }

            var decrypted = crypto.Decrypt(this.Cipher, key, usage);

            return(func(decrypted));
        }
Esempio n. 6
0
        private static byte[] Decrypt(byte[] k1, byte[] ciphertext, KeyUsage keyType)
        {
            var salt = GetSalt((int)keyType);

            var k2 = KerberosHash.HMACMD5(k1, salt);

            var checksum = new byte[HashSize];

            Buffer.BlockCopy(ciphertext, 0, checksum, 0, HashSize);

            var k3 = KerberosHash.HMACMD5(k2, checksum);

            var ciphertextOffset = new byte[ciphertext.Length - HashSize];

            Buffer.BlockCopy(ciphertext, HashSize, ciphertextOffset, 0, ciphertextOffset.Length);

            var plaintext = RC4.Decrypt(k3, ciphertextOffset);

            var calculatedHmac = KerberosHash.HMACMD5(k2, plaintext);

            if (!KerberosHash.AreEqualSlow(calculatedHmac, ciphertext, calculatedHmac.Length))
            {
                throw new SecurityException("Invalid Checksum");
            }

            var output = new byte[plaintext.Length - ConfounderSize];

            Buffer.BlockCopy(plaintext, ConfounderSize, output, 0, output.Length);

            return(output);
        }
Esempio n. 7
0
 /// <summary>
 /// Creates a new private key.
 /// </summary>
 /// <param name="keyProvider">The provider for the key. <see cref="KeyProviders"/> contains different types of providers.</param>
 /// <param name="keyName">The name of the key to persist. Use <c>null</c> to create an ephemeral key.</param>
 /// <param name="algorithm">The algorithm of the key. Not all providers support all algorithms.</param>
 /// <param name="keyUsage">Specifies the purpose of the key. This is not appicable to CNG algorithms.</param>
 /// <param name="keySize">The size of the key. Only valid for RSA keys.</param>
 /// <param name="overwrite">True to overwrite the provider's exisint private key, otherwise false.</param>
 /// <returns>A new private key.</returns>
 public static PrivateKey CreateNew(KeyProviderBase keyProvider, string keyName, Algorithm algorithm, KeyUsage keyUsage, int? keySize = null, bool overwrite = false)
 {
     var keySizeValue = keySize ?? 2048;
     KeySpec keySpec;
     var handle = keyProvider.CreateKey(keyName, keySizeValue, algorithm, overwrite, keyUsage, out keySpec);
     return new PrivateKey(handle, keyProvider, keySpec);
 }
        /// <summary>
        /// Creates a Symmetric key credential.
        /// </summary>
        /// <param name="startTime">Start time.</param>
        /// <param name="endTime">End time of the credential.</param>
        /// <param name="keyUsage">Key usage of the symmetric key.</param>
        /// <param name="base64EncodedKeyValue">Credential value</param>
        /// <returns>Key credential.</returns>
        /// <exception cref="ArgumentException">Key is not a valid base64 encoded string.</exception>
        public static KeyCredential CreateSymmetricKeyCredential(
            DateTime startTime,
            DateTime endTime,
            KeyUsage keyUsage,
            string base64EncodedKeyValue)
        {
            Utils.ThrowIfNullOrEmpty(base64EncodedKeyValue, "base64EncodedKeyValue");

            byte[] keyBytes = null;

            try
            {
                keyBytes = Convert.FromBase64String(base64EncodedKeyValue);
            }
            catch (FormatException)
            {
                throw new ArgumentException("Input was not a valid base64 encoded value.", "base64EncodedKeyValue");
            }

            return(KeyCredentialsHelper.CreateSymmetricKeyCredential(
                       startTime,
                       endTime,
                       keyUsage,
                       keyBytes));
        }
Esempio n. 9
0
        /// <summary>
        /// Add key usages to the certificate
        /// </summary>
        /// <param name="keyUsages"> Integer of chained flags. EXAMPLE: X509KeyUsageFlags.One | X509KeyUsageFlags.Two</param>
        /// <returns></returns>
        public CertificateBuilder AddKeyUsages(int keyUsages)
        {
            var keyUsageCertSign = new KeyUsage(keyUsages);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage.Id, false, keyUsageCertSign);
            return(this);
        }
Esempio n. 10
0
    public static KeyCode GetKeyForUsage(KeyUsage usage)
    {
        if (_keyCodeChanges == null)
            LoadKeyBindings(0);

        return _keyCodeChanges[usage];
    }
Esempio n. 11
0
 public static bool GetKeyUp(KeyUsage use)
 {
     KeyCode code;
     if (_keyCodeChanges.TryGetValue(use, out code))
         return Input.GetKeyUp(code);
     return false;
 }
Esempio n. 12
0
        public CertificateResult Create(
            string algorithm,
            int keyLength,
            string subjectName,
            DateTime notBefore,
            DateTime notAfter,
            KeyUsage keyUsage,
            KeyPurposeID[] extendedUsages,
            X509Certificate caCertificate,
            AsymmetricCipherKeyPair caKeyPair,
            CertificateEndPoints certificateEndPoints
            )
        {
            SecureRandom            random         = GenerateSecureRandom();
            AsymmetricCipherKeyPair subjectKeyPair = GenerateKeyPair(random, keyLength);
            BigInteger serialNumber = GenerateSerialNumber(random);
            string     caName       = caCertificate.SubjectDN.ToString();

            X509Certificate certificate = GenerateCertificate(
                random,
                algorithm,
                subjectName,
                subjectKeyPair,
                serialNumber,
                null,
                notBefore,
                notAfter,
                caName,
                caKeyPair,
                keyUsage,
                extendedUsages,
                certificateEndPoints);

            return(new CertificateResult(certificate, subjectKeyPair));
        }
        public void PrivateCertificateProcessing_CreateCertificate_CngRsa2048_ClientServerAuth_ReturnedX509Certificate2HasClientServerAuthKeyUsage()
        {
            KeyUsage expected = KeyUsage.ServerAuthentication | KeyUsage.ClientAuthentication;

            CreatePrivateCertificateModel model = new CreatePrivateCertificateModel()
            {
                CipherAlgorithm            = CipherAlgorithm.RSA,
                KeyUsage                   = expected.ToString(),
                HashAlgorithm              = HashAlgorithm.SHA256,
                KeySize                    = 2048,
                Provider                   = WindowsApi.Cng,
                SubjectAlternativeNamesRaw = "integrationtestdomain.com,integrationtestdomain",
                SubjectCity                = "Seattle",
                SubjectCommonName          = "integrationtestdomain",
                SubjectCountry             = "US",
                SubjectDepartment          = "Engineering",
                SubjectState               = "WA",
                SubjectOrganization        = "IntegrationTestingCorp"
            };


            PrivateCertificateProcessing   processor = new PrivateCertificateProcessing(certDb, configDb, certProvider, GetAuthorizationLogic_Allow(), templateLogic, GetAuditLogic());
            CreatePrivateCertificateResult result    = processor.CreateCertificateWithPrivateKey(model, user.Object);

            X509Certificate2 cert = new X509Certificate2(result.PfxByte, result.Password);

            KeyUsage actualKeyUsage = x509Normalization.GetKeyUsage(cert);

            Assert.AreEqual(expected, actualKeyUsage);
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(string.Empty, Properties.Resources.CreateCertificatePolicy))
            {
                var policy = new PSKeyVaultCertificatePolicy(
                    DnsName,
                    (KeyUsage == null || !KeyUsage.Any()) ? null : KeyUsage.Select(keyUsage => keyUsage.ToString()).ToList <string>(),
                    Ekus,
                    !Disabled.IsPresent,
                    IssuerName,
                    CertificateType,
                    RenewAtNumberOfDaysBeforeExpiry,
                    RenewAtPercentageLifetime,
                    EmailAtNumberOfDaysBeforeExpiry,
                    EmailAtPercentageLifetime,
                    ReuseKeyOnRenewal.IsPresent,
                    SecretContentType,
                    SubjectName,
                    ValidityInMonths,
                    KeyType,
                    KeySize,
                    Curve,
                    KeyNotExportable.IsPresent ? !KeyNotExportable.IsPresent : (bool?)null,
                    CertificateTransparency ?? (bool?)null);

                this.WriteObject(policy);
            }
        }
        public void PrivateCertificateProcessing_CreateCertificate_CngRsa2048_ClientServerAuth_Success()
        {
            KeyUsage keyUsage = KeyUsage.ServerAuthentication | KeyUsage.ClientAuthentication;
            CreatePrivateCertificateModel model = new CreatePrivateCertificateModel()
            {
                CipherAlgorithm            = CipherAlgorithm.RSA,
                KeyUsage                   = keyUsage.ToString(),
                HashAlgorithm              = HashAlgorithm.SHA256,
                KeySize                    = 2048,
                Provider                   = WindowsApi.Cng,
                SubjectAlternativeNamesRaw = "integrationtestdomain.com,integrationtestdomain",
                SubjectCity                = "Seattle",
                SubjectCommonName          = "integrationtestdomain",
                SubjectCountry             = "US",
                SubjectDepartment          = "Engineering",
                SubjectState               = "WA",
                SubjectOrganization        = "IntegrationTestingCorp"
            };


            PrivateCertificateProcessing   processor = new PrivateCertificateProcessing(certDb, configDb, certProvider, GetAuthorizationLogic_Allow(), templateLogic, GetAuditLogic());
            CreatePrivateCertificateResult result    = processor.CreateCertificateWithPrivateKey(model, user.Object);

            Assert.AreEqual(PrivateCertificateRequestStatus.Success, result.Status);
        }
Esempio n. 16
0
        /// <summary>
        /// Generate a self-signed certificate and add it to the Windows certificate store.
        /// </summary>
        /// <param name="subjectName">The subject name of the certificate.</param>
        /// <param name="friendlyName">The friendly name of the certificate.</param>
        /// <param name="location">Location of the certificate; either the Current User or Local Machine.</param>
        /// <param name="addAsTrustedRoot">Whether to add the generated certificate as a trusted root.</param>
        /// <param name="keyLength">Size of the key in bits.</param>
        /// <param name="durationYears">Duration of the certificate, specified in years.</param>
        /// <param name="oids">Collection of OIDs identifying certificate usage.</param>
        /// <returns>Self-signed certificate.</returns>
        public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, string friendlyName, StoreLocation location, bool addAsTrustedRoot, int keyLength, int durationYears, List <DerObjectIdentifier> oids)
        {
            // Prepare random number generation.
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            // Create asymmetric key.
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyLength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Generate a serial number.
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Assign the subject name.
            X509Name subjectDN = new X509Name("CN=" + subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Set valid dates.
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(durationYears);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Set key usage for digital signatures and key encipherment.
            KeyUsage usage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, usage);

            // Load the OIDs passed in and specify enhanced key usages.
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(oids));

            // Assign the public key.
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Self-sign the certificate using SHA-512.
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", subjectKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate bouncyCastleCertificate = certificateGenerator.Generate(signatureFactory);

            // Convert from BouncyCastle private key format to System.Security.Cryptography format.
            AsymmetricAlgorithm privateKey      = ToDotNetKey((RsaPrivateCrtKeyParameters)subjectKeyPair.Private);
            X509Certificate2    x509certificate = new X509Certificate2(DotNetUtilities.ToX509Certificate(bouncyCastleCertificate));

            x509certificate.PrivateKey   = privateKey;
            x509certificate.FriendlyName = subjectName;

            return(x509certificate);
        }
Esempio n. 17
0
        public override byte[] MakeChecksum(byte[] key, byte[] data, KeyUsage keyUsage)
        {
            var ksign = HMACMD5(key, Encoding.ASCII.GetBytes("signaturekey\0"));

            var tmp = MD5(ConvertToLittleEndian((int)keyUsage).Concat(data).ToArray());

            return(HMACMD5(ksign, tmp));
        }
Esempio n. 18
0
 private ReadOnlyMemory <byte> GetOrDeriveKey(KerberosKey kerberosKey, KeyUsage usage)
 {
     return(kerberosKey.GetOrDeriveKey(
                this,
                $"{usage}|Ke|{KeySize}|{BlockSize}",
                key => DK(key, usage, KeyDerivationMode.Ke, KeySize, BlockSize)
                ));
 }
        public void DataTransformation_ParseKeyUsage_InvalidKeyUsage_6point5_ThrowArgumentException()
        {
            DataTransformation dataTransformation = new DataTransformation();

            string keyUsageString = "6.5";

            KeyUsage actualKeyUsage = dataTransformation.ParseKeyUsage(keyUsageString);
        }
        public void DataTransformation_ParseKeyUsage_InvalidKeyUsage_SpecialCharacterDollar_ThrowArgumentException()
        {
            DataTransformation dataTransformation = new DataTransformation();

            string keyUsageString = "$";

            KeyUsage actualKeyUsage = dataTransformation.ParseKeyUsage(keyUsageString);
        }
Esempio n. 21
0
 public virtual T DecryptKdcRep <T>(KrbKdcRep kdcRep, KeyUsage keyUsage, Func <ReadOnlyMemory <byte>, T> func)
 {
     return(kdcRep.EncPart.Decrypt(
                CreateKey(),
                keyUsage,
                func
                ));
 }
Esempio n. 22
0
        public T Decrypt <T>(KerberosKey key, KeyUsage usage, Func <ReadOnlyMemory <byte>, T> func)
        {
            var crypto = CryptoService.CreateTransform(this.EType);

            var decrypted = crypto.Decrypt(this.Cipher, key, usage);

            return(func(decrypted));
        }
        public void DataTransformation_ParseKeyUsage_InvalidKeyUsage_Empty_ThrowArgumentNullException()
        {
            DataTransformation dataTransformation = new DataTransformation();

            string keyUsageString = string.Empty;

            KeyUsage actualKeyUsage = dataTransformation.ParseKeyUsage(keyUsageString);
        }
        public static X509Certificate2 CreateSigned(string subjectDN, DateTime effectiveDate, DateTime expirationDate, List <Uri> crlUrls, X509Certificate2 certificateAuthority, List <X509KeyUsageFlags> keyUsages = null)
        {
            Org.BouncyCastle.X509.X509Certificate caCert = DotNetUtilities.FromX509Certificate(certificateAuthority);
            AsymmetricCipherKeyPair keyPair = CreateRSAKeyPair();
            X509Name x509SubjectDN          = new X509Name(subjectDN);

            X509Certificate2 rtnCert = CreateCertificate(x509SubjectDN, effectiveDate, expirationDate, keyPair, caCert.SubjectDN,
                                                         TransformRSAPrivateKey((RSACryptoServiceProvider)certificateAuthority.PrivateKey), (certGen, serialNumber) =>
            {
                IList cn = x509SubjectDN.GetValueList(X509Name.CN);

                if (cn.Count > 0)
                {
                    if (Uri.CheckHostName(cn[0].ToString()) == UriHostNameType.Dns)
                    {
                        certGen.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.DnsName, cn[0].ToString())));
                    }
                    else
                    {
                        try
                        {
                            MailAddress ma = new MailAddress(cn[0].ToString());
                            certGen.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.Rfc822Name, cn[0].ToString())));
                        }
                        catch { }
                    }
                }

                KeyUsage ku = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment);
                if (keyUsages != null && keyUsages.Count > 0)
                {
                    if (!(keyUsages.Contains(X509KeyUsageFlags.DigitalSignature) &&
                          keyUsages.Contains(X509KeyUsageFlags.KeyEncipherment)))
                    {
                        if (keyUsages.Contains(X509KeyUsageFlags.DigitalSignature))
                        {
                            ku = new KeyUsage(KeyUsage.DigitalSignature);
                        }
                        else
                        {
                            ku = new KeyUsage(KeyUsage.KeyEncipherment);
                        }
                    }
                }

                certGen.AddExtension(X509Extensions.KeyUsage, true, ku);
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection));
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                certGen.AddCrlDistributionPoints(crlUrls);
            });

            rtnCert.PrivateKey = TransformRSAPrivateKey((RsaPrivateCrtKeyParameters)keyPair.Private);

            return(rtnCert);
        }
        public static KeyUsage convertKeyUsage(NativeKeyUsage nativeKeyUsage)
        {
            KeyUsage keyUsage = new KeyUsage();

            keyUsage.HasKeyUsageExtension = nativeKeyUsage.HasKeyUsageExtension;
            keyUsage.IsCritical           = nativeKeyUsage.IsCritical;
            keyUsage.KeyUsageFlags        = convertIntToKeyUsageFlag(nativeKeyUsage.Value);
            return(keyUsage);
        }
 public virtual ReadOnlyMemory <byte> MakeChecksum(
     ReadOnlyMemory <byte> data,
     KerberosKey key,
     KeyUsage usage,
     KeyDerivationMode kdf,
     int hashSize)
 {
     throw new NotImplementedException();
 }
Esempio n. 27
0
 public DaplugKeySet(byte version, KeyUsage usage, ushort access, byte[] encKey, byte[] macKey, byte[] dekKey)
 {
     this.Version = version;
     this.Usage   = usage;
     this.Access  = access;
     this.EncKey  = encKey;
     this.MacKey  = macKey;
     this.DeKey   = dekKey;
 }
Esempio n. 28
0
        private KeyUsage SetFlag(KeyUsage current, KeyUsage additional)
        {
            if (current.HasFlag(KeyUsage.None))
            {
                current = current & ~KeyUsage.None;
            }

            return(current | additional);
        }
Esempio n. 29
0
 public DaplugKeySet(byte version, KeyUsage usage, ushort access, string key)
 {
     this.Version = version;
     this.Usage   = usage;
     this.Access  = access;
     this.EncKey  = Helpers.StringToByteArray(key);
     this.MacKey  = Helpers.StringToByteArray(key);
     this.DeKey   = Helpers.StringToByteArray(key);
 }
Esempio n. 30
0
        internal bool Decrypt(KerberosKeySet keyset, KeyUsage key_usage, out KerberosTicket ticket)
        {
            if (this is KerberosTicketDecrypted)
            {
                ticket = this;
                return(true);
            }

            ticket = null;
            if (!EncryptedData.Decrypt(keyset, Realm, ServerName, key_usage, out byte[] decrypted))
Esempio n. 31
0
        private byte[] DK(byte[] key, KeyUsage usage, KeyDerivationMode kdf)
        {
            var constant = new byte[5];

            Endian.ConvertToBigEndian((int)usage, constant);

            constant[4] = (byte)kdf;

            return(DK(key, constant));
        }
Esempio n. 32
0
        private static ReadOnlySpan <byte> DK(ReadOnlySpan <byte> key, KeyUsage usage, KeyDerivationMode kdf, int keySize, int blockSize)
        {
            var constant = new Span <byte>(new byte[5]);

            Endian.ConvertToBigEndian((int)usage, constant);

            constant[4] = (byte)kdf;

            return(DK(key, constant, keySize, blockSize));
        }
Esempio n. 33
0
 public static bool IsSatisfied(this KeyUsage requirement, KeyUsage enforcement)
 {
     return(((requirement.AccessData & enforcement.AccessData) == requirement.AccessData) &&
            ((requirement.BatchRead & enforcement.BatchRead) == requirement.BatchRead) &&
            ((requirement.BatchWrite & enforcement.BatchWrite) == requirement.BatchWrite) &&
            ((requirement.ChangePassword & enforcement.ChangePassword) == requirement.ChangePassword) &&
            ((requirement.CreateSession & enforcement.CreateSession) == requirement.CreateSession) &&
            ((requirement.GetChangeToken & enforcement.GetChangeToken) == requirement.GetChangeToken) &&
            ((requirement.ProveIdentity & enforcement.ProveIdentity) == requirement.ProveIdentity) &&
            ((requirement.RenewSession & enforcement.RenewSession) == requirement.RenewSession));
 }
Esempio n. 34
0
 internal override NCryptKeyOrCryptProviderSafeHandle CreateKey(string keyName, int keySize, Algorithm algorithm, bool overwrite, KeyUsage keyUsage, out KeySpec keySpec)
 {
     const int ALREADY_EXISTS = unchecked((int)0x8009000f);
     if (algorithm != Algorithm.RSA)
     {
         throw new ArgumentException("CAPI does not support algorithms other than RSA.", nameof(algorithm));
     }
     NCryptKeyOrCryptProviderSafeHandle provider;
     if (!AdvApi32.CryptAcquireContext(out provider, keyName, _providerName, ProviderType.PROV_RSA_AES, CryptAcquireContextFlags.CRYPT_NEWKEYSET))
     {
         var lastError = Marshal.GetLastWin32Error();
         if (lastError == ALREADY_EXISTS && overwrite)
         {
             if (!AdvApi32.CryptAcquireContext(out provider, keyName, _providerName, ProviderType.PROV_RSA_AES, CryptAcquireContextFlags.CRYPT_DELETEKEYSET))
             {
                 throw new Win32Exception(Marshal.GetLastWin32Error());
             }
             if (!AdvApi32.CryptAcquireContext(out provider, keyName, _providerName, ProviderType.PROV_RSA_AES, CryptAcquireContextFlags.CRYPT_NEWKEYSET))
             {
                 throw new Win32Exception(Marshal.GetLastWin32Error());
             }
         }
         else
         {
             throw new Win32Exception(Marshal.GetLastWin32Error());
         }
     }
     var flags = CryptGenKeyFlags.CRYPT_EXPORTABLE;
     var keySizeFlags = ((uint)keySize & 0xFFFFU) << 16;
     var genKeyFlags = ((ushort)flags) | keySizeFlags;
     CryptKeySafeHandle key;
     KeySpec algorithmKeySpec;
     switch (keyUsage)
     {
         case KeyUsage.KeyExchange:
             algorithmKeySpec = KeySpec.AT_KEYEXCHANGE;
             break;
         case KeyUsage.Signature:
             algorithmKeySpec = KeySpec.AT_SIGNATURE;
             break;
         default:
             throw new ArgumentException(nameof(keyUsage));
     }
     if (!AdvApi32.CryptGenKey(provider, algorithmKeySpec, genKeyFlags, out key))
     {
         throw new Win32Exception(Marshal.GetLastWin32Error());
     }
     key.Close();
     keySpec = algorithmKeySpec;
     return provider;
 }
        /// <summary>
        /// Creates a Symmetric key credential.
        /// </summary>
        /// <param name="startTime">Start time of the credential.</param>
        /// <param name="endTime">End time of the credential.</param>
        /// <param name="keyUsage">Key usage for the symmetric key.</param>
        /// <param name="credentialBlob">Credential value</param>
        /// <returns>Key credential object.</returns>
        public static KeyCredential CreateSymmetricKeyCredential(
            DateTime startTime,
            DateTime endTime,
            KeyUsage keyUsage,
            byte[] credentialBlob)
        {
            Utils.ThrowIfNullOrEmpty(credentialBlob, "credentialBlob");
            ValidateStartAndEndTime(startTime, endTime);

            KeyCredential keyCredential = new KeyCredential();

            keyCredential.StartDate = startTime;
            keyCredential.EndDate = endTime;
            keyCredential.Type = KeyType.Symmetric.ToString();
            keyCredential.Usage = keyUsage.ToString();
            keyCredential.Value = credentialBlob;

            return keyCredential;
        }
Esempio n. 36
0
 internal override NCryptKeyOrCryptProviderSafeHandle CreateKey(string keyName, int keySize, Algorithm algorithm, bool overwrite, KeyUsage keyUsage, out KeySpec keySpec)
 {
     NCryptKeyOrCryptProviderSafeHandle keyHandle;
     var flags = overwrite ? NCryptCreatePersistedKeyFlags.NCRYPT_OVERWRITE_KEY_FLAG : NCryptCreatePersistedKeyFlags.NONE;
     var result = NCrypt.NCryptCreatePersistedKey(_storageProvider.Handle, out keyHandle, algorithm.Name, keyName, KeySpec.NONE, flags);
     if (result != SECURITY_STATUS.ERROR_SUCCESS)
     {
         throw new InvalidOperationException("Failed to generate a key.");
     }
     if (algorithm == Algorithm.RSA)
     {
         NCryptPropertyWriter.WriteUInt32(keyHandle, CngProperties.NCRYPT_LENGTH_PROPERTY, (uint) keySize);
     }
     NCryptPropertyWriter.WriteEnum(keyHandle, CngProperties.NCRYPT_EXPORT_POLICY_PROPERTY, CngExportPolicy.NCRYPT_ALLOW_EXPORT_FLAG);
     var finalizeResult = NCrypt.NCryptFinalizeKey(keyHandle, 0u);
     if (finalizeResult != SECURITY_STATUS.ERROR_SUCCESS)
     {
         throw new InvalidOperationException("Failed to finalize key.");
     }
     keySpec = KeySpec.NONE;
     return keyHandle;
 }
Esempio n. 37
0
    public static void ChangeKeyBinding(KeyUsage use, KeyCode newKey)
    {
        //  If the chosen key is already a keybinding, switch them
        if (_keyCodeChanges.ContainsValue(newKey))
        {
            var e = _keyCodeChanges.Keys.GetEnumerator();

            while(e.MoveNext())
            {
                if (_keyCodeChanges[e.Current] == newKey)
                {
                    _keyCodeChanges[e.Current] = _keyCodeChanges[use];
                    break;
                }
            }
        }

        _keyCodeChanges[use] = newKey;

        if (OnKeyBindChange != null)
            OnKeyBindChange.Invoke();
    }
        /// <summary>
        /// Creates a Symmetric key credential.
        /// </summary>
        /// <param name="startTime">Start time.</param>
        /// <param name="endTime">End time of the credential.</param>
        /// <param name="keyUsage">Key usage of the symmetric key.</param>
        /// <param name="base64EncodedKeyValue">Credential value</param>
        /// <returns>Key credential.</returns>
        /// <exception cref="ArgumentException">Key is not a valid base64 encoded string.</exception>
        public static KeyCredential CreateSymmetricKeyCredential(
            DateTime startTime,
            DateTime endTime,
            KeyUsage keyUsage,
            string base64EncodedKeyValue)
        {
            Utils.ThrowIfNullOrEmpty(base64EncodedKeyValue, "base64EncodedKeyValue");

            byte[] keyBytes = null;

            try
            {
                keyBytes = Convert.FromBase64String(base64EncodedKeyValue);
            }
            catch (FormatException)
            {
                throw new ArgumentException("Input was not a valid base64 encoded value.", "base64EncodedKeyValue");
            }
            
            return KeyCredentialsHelper.CreateSymmetricKeyCredential(
                startTime,
                endTime,
                keyUsage,
                keyBytes);
        }
        public void AddServiceKey(string displayName, byte[] keyValue, string protectionPassword, KeyType keyType, KeyUsage keyUsage)
        {
            try
            {
                var client = this.CreateManagementServiceClient();
                var defaultStartDate = DateTime.UtcNow;
                var defaultEndDate = defaultStartDate.AddYears(1);

                var serviceKey = new ServiceKey
                                     {
                                         DisplayName = displayName,
                                         Type = keyType.ToString(),
                                         Usage = keyUsage.ToString(),
                                         Value = keyValue,
                                         Password = string.IsNullOrEmpty(protectionPassword) ? null : new UTF8Encoding().GetBytes(protectionPassword),
                                         StartDate = defaultStartDate,
                                         EndDate = defaultEndDate,
                                         IsPrimary = true
                                     };

                client.AddToServiceKeys(serviceKey);
                client.SaveChanges();
            }
            catch (Exception ex)
            {
                throw TryGetExceptionDetails(ex);
            }
        }
Esempio n. 40
0
 internal abstract NCryptKeyOrCryptProviderSafeHandle CreateKey(string keyName, int keySize, Algorithm algorithm, bool overwrite, KeyUsage keyUsage, out KeySpec keySpec);