Example #1
0
        /// <summary>
        /// Gets a textual representation of the certificate template cryptography settings.
        /// </summary>
        /// <returns>A textual representation of the certificate template cryptography settings</returns>
        public override String ToString()
        {
            String        nl = Environment.NewLine;
            StringBuilder SB = new StringBuilder();

            SB.Append($"[Cryptography Settings]{nl}");
            SB.Append("  CSP list: ");
            if (CSPList == null)
            {
                SB.Append($"Any installed CSP{nl}");
            }
            else
            {
                SB.Append(nl);
                foreach (String csp in CSPList)
                {
                    SB.Append($"     {csp}{nl}");
                }
                SB.Append(nl);
            }
            SB.Append($"  Key Algorithm: {KeyAlgorithm.Format(true)}{nl}");
            SB.Append($"  Hash Algorithm: {HashAlgorithm.Format(true)}{nl}");
            SB.Append($"  Key Length: {MinimalKeyLength}{nl}");
            SB.Append($"  Private key options: {PrivateKeyOptions}{nl}");
            SB.Append($"  KeySpec: {KeySpec}{nl}");
            SB.Append($"  CNG key usage: {CNGKeyUsage}");
            if (!String.IsNullOrEmpty(PrivateKeySecuritySDDL))
            {
                SB.Append($"{nl}  Private key security descriptor: {PrivateKeySecuritySDDL}");
            }
            return(SB.ToString());
        }
        private void UpdateFromMem(IntPtr subkeyPtr)
        {
            _gpgme_subkey subkey = (_gpgme_subkey)
                                   Marshal.PtrToStructure(subkeyPtr,
                                                          typeof(_gpgme_subkey));

            revoked          = subkey.revoked;
            expired          = subkey.expired;
            disabled         = subkey.disabled;
            invalid          = subkey.invalid;
            can_encrypt      = subkey.can_encrypt;
            can_sign         = subkey.can_sign;
            can_certify      = subkey.can_certify;
            can_authenticate = subkey.can_authenticate;
            is_qualified     = subkey.is_qualified;
            secret           = subkey.secret;

            pubkey_algo = (KeyAlgorithm)subkey.pubkey_algo;
            length      = (long)subkey.length;

            keyid     = Gpgme.PtrToStringAnsi(subkey.keyid);
            fpr       = Gpgme.PtrToStringAnsi(subkey.fpr);
            timestamp = (long)subkey.timestamp;
            expires   = (long)subkey.expires;

            if (subkey.next != (IntPtr)0)
            {
                next = new Subkey(subkey.next);
            }
        }
Example #3
0
        /// <summary>
        /// Creates a new instance of a specified algorithm-class.
        /// </summary>
        /// <param name="algorithm">The algorithm to use.</param>
        /// <param name="operation">The operations required to be supported.</param>
        /// <returns>Instance of the right algorithm class guaranted to support the given operations (i.e. implementing the correct interfaces).</returns>
        public static AlgorithmBase Create(KeyAlgorithm algorithm, KeyOperation operation)
        {
            Type          type     = Type.GetType("OpenPGP." + algorithm.ToString() + "Algorithm");
            AlgorithmBase instance = (AlgorithmBase)Activator.CreateInstance(type);

            return(instance);
        }
Example #4
0
        protected async Task CanGenerateCertificateWithEC(KeyAlgorithm algo)
        {
            var dirUri = await GetAcmeUriV2();

            var hosts    = new[] { $"www-ec-{DomainSuffix}.{algo}.certes-ci.dymetis.com".ToLower() };
            var ctx      = new AcmeContext(dirUri, GetKeyV2(algo), http: GetAcmeHttpClient(dirUri));
            var orderCtx = await AuthorizeHttp(ctx, hosts);

            var certKey        = KeyFactory.NewKey(algo);
            var finalizedOrder = await orderCtx.Finalize(new CsrInfo
            {
                CountryName      = "CA",
                State            = "Ontario",
                Locality         = "Toronto",
                Organization     = "Certes",
                OrganizationUnit = "Dev",
                CommonName       = hosts[0],
            }, certKey);

            var cert = await orderCtx.Download(null);

            var x509 = new X509Certificate2(cert.Certificate.ToDer());

            Assert.Contains(hosts[0], x509.Subject);

            // deactivate authz so the subsequence can trigger challenge validation
            await ClearAuthorizations(orderCtx);
        }
Example #5
0
        private void parseinfo()
        {
            if (info != null)
            {
                string[] token = info.Split(' ');
                int      len   = token.Length;

                if (len > 0)
                {
                    request_keyid = token[0];
                }
                if (len > 1)
                {
                    main_keyid = token[1];
                }
                if (len > 2)
                {
                    try
                    {
                        int ktype = int.Parse(token[2]);
                        keytype = (KeyAlgorithm)ktype;
                    }
                    catch {}
                }
                if (len > 3)
                {
                    try
                    {
                        int ksize = int.Parse(token[3]);
                        keylength = ksize;
                    }
                    catch { }
                }
            }
        }
Example #6
0
        private void UpdateFromMem(IntPtr keysigPtr)
        {
            _gpgme_key_sig keysig = (_gpgme_key_sig)Marshal.PtrToStructure(keysigPtr,
                                                                           typeof(_gpgme_key_sig));

            revoked    = keysig.revoked;
            expired    = keysig.expired;
            invalid    = keysig.invalid;
            exportable = keysig.exportable;

            pubkey_algo = (KeyAlgorithm)keysig.pubkey_algo;

            keyid   = Gpgme.PtrToStringAnsi(keysig.keyid);
            uid     = Gpgme.PtrToStringAnsi(keysig.uid);
            name    = Gpgme.PtrToStringAnsi(keysig.name);
            comment = Gpgme.PtrToStringAnsi(keysig.comment);
            email   = Gpgme.PtrToStringAnsi(keysig.email);

            timestamp = (long)keysig.timestamp;
            expires   = (long)keysig.expires;

            status    = keysig.status;
            sig_class = (long)keysig.sig_class;

            if (keysig.notations != (IntPtr)0)
            {
                notations = new SignatureNotation(keysig.notations);
            }

            if (keysig.next != (IntPtr)0)
            {
                next = new KeySignature(keysig.next);
            }
        }
Example #7
0
        public Key Generate(string name, KeyAlgorithm keyAlgorithm = KeyAlgorithm.RS256,
                            string description = null, string keyContents = null)
        {
            if (_dataContext.Keys.Any(x => x.Name == name))
            {
                name = $"{name}-{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            }

            if (keyContents == null)
            {
                keyContents = _certesAcmeProvider.NewKey(keyAlgorithm);
            }

            var key = new Key
            {
                DateCreated = DateTime.UtcNow,
                Name        = name,
                Description = description,
                RawData     = keyContents
            };

            _dataContext.Keys.Add(key);
            _dataContext.SaveChanges();

            return(key);
        }
Example #8
0
        /// <summary>
        /// Get the JWS name of the <paramref name="algorithm"/>.
        /// </summary>
        /// <param name="algorithm">The algorithm.</param>
        /// <returns></returns>
        public static string ToJwsAlgorithm(this KeyAlgorithm algorithm)
        {
            if (!Enum.IsDefined(typeof(KeyAlgorithm), algorithm))
            {
                throw new ArgumentException(nameof(algorithm));
            }

            return(algorithm.ToString());
        }
Example #9
0
        public async Task CanCreatePfxChain(KeyAlgorithm alog)
        {
            var(cert, key) = await Helper.GetValidCert();

            var pfxBuilder = new PfxBuilder(
                Encoding.UTF8.GetBytes(cert), KeyFactory.NewKey(alog));

            pfxBuilder.AddIssuers(Encoding.UTF8.GetBytes(cert));
            var pfx = pfxBuilder.Build("my-cert", "abcd1234");
        }
Example #10
0
        public void FailChainForExpiredCert(KeyAlgorithm alog)
        {
            var leafCert = File.ReadAllBytes("./Data/leaf-cert-expire.cer");

            var pfxBuilder = new PfxBuilder(leafCert, KeyFactory.NewKey(alog));

            pfxBuilder.AddIssuer(File.ReadAllBytes("./Data/test-ca2.pem"));
            pfxBuilder.AddIssuer(File.ReadAllBytes("./Data/test-root.pem"));
            Assert.Throws <PkixCertPathBuilderException>(() => pfxBuilder.Build("my-cert", "abcd1234"));
        }
Example #11
0
        public void CanCreatePfxWithoutChain(KeyAlgorithm alog)
        {
            var leafCert = File.ReadAllText("./Data/leaf-cert.pem");

            var pfxBuilder = new PfxBuilder(
                Encoding.UTF8.GetBytes(leafCert), KeyFactory.NewKey(alog));

            pfxBuilder.FullChain = false;
            var pfx = pfxBuilder.Build("my-cert", "abcd1234");
        }
Example #12
0
        public static string GetPubkeyAlgoName(KeyAlgorithm algo)
        {
            IntPtr ret = libgpgme.gpgme_pubkey_algo_name((gpgme_pubkey_algo_t)algo);

            if (ret == IntPtr.Zero)
            {
                throw new InvalidPubkeyAlgoException("The public key algorithm is unknown.");
            }

            return(PtrToStringAnsi(ret));
        }
Example #13
0
        public void CanCreatePfxChain(KeyAlgorithm alog)
        {
            var leafCert = File.ReadAllText("./Data/leaf-cert.pem");

            var pfxBuilder = new PfxBuilder(
                Encoding.UTF8.GetBytes(leafCert), KeyFactory.NewKey(alog));

            pfxBuilder.AddIssuer(File.ReadAllBytes("./Data/test-ca2.pem"));
            pfxBuilder.AddIssuer(File.ReadAllBytes("./Data/test-root.pem"));
            var pfx = pfxBuilder.Build("my-cert", "abcd1234");
        }
Example #14
0
        // internal AND protected
        internal override GpgInterfaceResult ProcessLine(String line)
        {
            if (!GNUCheck(ref line))
            {
                return(GpgInterfaceResult.Success);
            }

            switch (GetKeyword(ref line))
            {
            case GpgKeyword.BAD_PASSPHRASE:
            {
                if (IsMaxTries())
                {
                    return(GpgInterfaceResult.BadPassphrase);
                }
                break;
            }

            case GpgKeyword.GET_HIDDEN:
            {
                if (String.Equals(line, "passphrase.enter", StringComparison.Ordinal))
                {
                    SecureString password = InternalAskPassphrase(SignatureKeyId);
                    if (IsNullOrEmpty(password))
                    {
                        return(GpgInterfaceResult.UserAbort);
                    }
                    WritePassword(password);
                }
                break;
            }

            case GpgKeyword.SIG_CREATED:
            {
                String[] parts = line.Split(' ');
                Signed          = true;
                KeyAlgorithm    = GpgConvert.ToKeyAlgorithm(Int32.Parse(parts[1], CultureInfo.InvariantCulture));
                DigestAlgorithm = GpgConvert.ToDigestAlgorithm(Int32.Parse(parts[2], CultureInfo.InvariantCulture));
                break;
            }

            case GpgKeyword.GET_BOOL:
            {
                if (String.Equals(line, "openfile.overwrite.okay", StringComparison.Ordinal))
                {
                    WriteLine("YES");
                }
                break;
            }
            }

            return(GpgInterfaceResult.Success);
        }
Example #15
0
        private AccountKey GetTestKey(KeyAlgorithm algo)
        {
            var key =
                algo == KeyAlgorithm.ES256 ? Keys.ES256Key :
                algo == KeyAlgorithm.ES384 ? Keys.ES384Key :
                algo == KeyAlgorithm.ES512 ? Keys.ES512Key :
                Keys.RS256Key;

            using (var buffer = new MemoryStream(Encoding.UTF8.GetBytes(key)))
            {
                return(new AccountKey(KeyInfo.From(buffer)));
            }
        }
Example #16
0
        private void CanCreateEllipticCurveAlgo(KeyAlgorithm algorithm)
        {
            var provider = new KeyAlgorithmProvider();
            var algo     = provider.Get(algorithm) as EllipticCurveAlgorithm;

            Assert.NotNull(algo);

            var key = algo.GenerateKey();

            Assert.NotNull(key);

            Assert.NotNull(key.JsonWebKey);
        }
Example #17
0
        public void CanGetKey(KeyAlgorithm algorithm)
        {
            var provider = new KeyAlgorithmProvider();
            var algo     = provider.Get(algorithm);
            var key      = (AsymmetricCipherKey)algo.GenerateKey();

            var keyData = key.ToDer();

            var restored = provider.GetKey(keyData);

            var restoredData = restored.ToDer();

            Assert.Equal(keyData, restoredData);
        }
Example #18
0
        public void CanComputeHash(KeyAlgorithm algoType)
        {
            var provider = new KeyAlgorithmProvider();
            var algo     = provider.Get(algoType);
            var signer   = algo.CreateSigner(algo.GenerateKey());

            var data = Encoding.UTF8.GetBytes("secret message");
            var hash = signer.ComputeHash(data);

            using (var sha = SHA256.Create())
            {
                Assert.Equal(sha.ComputeHash(data), hash);
            }
        }
Example #19
0
File: Key.cs Project: Ifry/win-app
 private Key(byte[] bytes, string base64, KeyAlgorithm algorithm)
 {
     if (bytes == null || bytes.Length <= 0)
     {
         throw new ArgumentException($"The '{nameof(bytes)}' argument is empty.");
     }
     if (string.IsNullOrEmpty(base64))
     {
         throw new ArgumentException($"The '{nameof(base64)}' argument is empty.");
     }
     Bytes     = bytes;
     Base64    = base64;
     Algorithm = algorithm;
     Pem       = CreatePem();
 }
Example #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="signatureKeyId"></param>
        /// <param name="fileName"></param>
        /// <param name="signedFileName"></param>
        /// <param name="armored"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgSign(KeyId signatureKeyId, String fileName, String signedFileName, Boolean armored)
        {
            if (signatureKeyId == null)
            {
                throw new ArgumentNullException("signatureKeyId");
            }

            SignatureKeyId  = signatureKeyId;
            FileName        = fileName;
            SignedFileName  = signedFileName;
            Armored         = armored;
            Signed          = false;
            KeyAlgorithm    = KeyAlgorithm.None;
            DigestAlgorithm = DigestAlgorithm.None;
        }
Example #21
0
        private void UpdateFromMem(IntPtr recpPtr)
        {
            var recp = new _gpgme_recipient();

            Marshal.PtrToStructure(recpPtr, recp);

            _keyid       = Gpgme.PtrToStringUTF8(recp.keyid);
            _pubkey_algo = (KeyAlgorithm)recp.pubkey_algo;
            _status      = recp.status;

            if (recp.next != IntPtr.Zero)
            {
                _next = new Recipient(recp.next);
            }
        }
Example #22
0
        public static string GetTestKey(this KeyAlgorithm algo)
        {
            switch (algo)
            {
            case KeyAlgorithm.ES256:
                return(Keys.ES256Key);

            case KeyAlgorithm.ES384:
                return(Keys.ES384Key);

            case KeyAlgorithm.ES512:
                return(Keys.ES512Key);

            default:
                return(Keys.RS256Key);
            }
        }
        private void UpdateFromMem(IntPtr sigPtr)
        {
            _gpgme_new_signature newsig = new _gpgme_new_signature();

            Marshal.PtrToStructure(sigPtr, newsig);

            type        = (SignatureMode)newsig.type;
            pubkey_algo = (KeyAlgorithm)newsig.pubkey_algo;
            hash_algo   = (HashAlgorithm)newsig.hash_algo;
            fpr         = Gpgme.PtrToStringUTF8(newsig.fpr);
            sig_class   = (long)newsig.sig_class;
            timestamp   = (long)newsig.timestamp;

            if (!newsig.next.Equals(IntPtr.Zero))
            {
                next = new NewSignature(newsig.next);
            }
        }
 public void SetAlgorithm(KeyAlgorithm algo)
 {
     switch (algo)
     {
         case KeyAlgorithm.DSA:
             Algorithm = PgpSubkeyAlgorithm.DSASignOnly;
             break;
         case KeyAlgorithm.ELG:
             Algorithm = PgpSubkeyAlgorithm.ELGEncryptOnly;
             break;
         case KeyAlgorithm.RSA:
             Algorithm = PgpSubkeyAlgorithm.RSAUseCapabilities;
             break;
         default:
             throw new System.NotSupportedException("Algorithm is not supported as sub key.",
                 new NotSupportedException("Algorithm is not supported as sub key."));
     }
 }
Example #25
0
        internal static string ToPkcsObjectId(this KeyAlgorithm algo)
        {
            switch (algo)
            {
            case KeyAlgorithm.RS256:
                return(PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id);

            case KeyAlgorithm.ES256:
                return(X9ObjectIdentifiers.ECDsaWithSha256.Id);

            case KeyAlgorithm.ES384:
                return(X9ObjectIdentifiers.ECDsaWithSha384.Id);

            case KeyAlgorithm.ES512:
                return(X9ObjectIdentifiers.ECDsaWithSha512.Id);
            }

            return(null);
        }
Example #26
0
 public bool Contains(string value)
 {
     return
         (
         FriendlyName.Contains(value) ||
         Subject.Contains(value) ||
         Issuer.Contains(value) ||
         SerialNumber.Contains(value) ||
         Thumbprint.Contains(value) ||
         KeyAlgorithm.Contains(value) ||
         SignatureAlgorithm.Contains(value) ||
         Version.Contains(value) ||
         Format.Contains(value) ||
         Extentions.Contains(value) ||
         StoreLocation.Contains(value) ||
         StoreName.Contains(value) ||
         EffectiveDate.ToString().Contains(value) ||
         ExpirationDate.ToString().Contains(value)
         );
 }
Example #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgGenerateKey"/> class.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <param name="comment"></param>
        /// <param name="algorithm"></param>
        /// <param name="size"></param>
        /// <param name="expirationDate"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgGenerateKey(Name name, Email email, String comment, KeyAlgorithm algorithm, UInt32 size, DateTime expirationDate)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (email == null)
            {
                throw new ArgumentNullException("email");
            }

            Name           = name;
            Email          = email;
            Comment        = comment;
            Algorithm      = algorithm;
            Size           = size;
            ExpirationDate = expirationDate;
            FingerPrint    = null;
        }
Example #28
0
        /// <summary>
        /// For more information, see gpg source code, file keygen.c line 1518.
        /// </summary>
        /// <remarks>
        /// GPG does not accept a "None" algorithm, so RSA is used by default.
        /// But you should not call this function with the "None" algorithm.
        /// </remarks>
        public static Int32 ToId(KeyAlgorithm algorithm)
        {
            switch (algorithm)
            {
            case KeyAlgorithm.None: return(1);

            case KeyAlgorithm.RsaRsa: return(1);

            case KeyAlgorithm.DsaELGamal: return(2);

            case KeyAlgorithm.Dsa: return(3);

            case KeyAlgorithm.RsaSign: return(4);

            case KeyAlgorithm.ELGamal: return(5);

            case KeyAlgorithm.RsaEncrypt: return(6);

            default: return(1);
            }
        }
        public async Task RunAccountFlow(KeyAlgorithm algorithm)
        {
            var dirUri = await IntegrationHelper.GetAcmeUriV1();

            var key = new AccountKey(algorithm);

            using (var client = new AcmeClient(IntegrationHelper.GetAcmeHttpHandler(dirUri)))
            {
                client.Use(key.Export());
                var reg = await client.NewRegistraton();

                reg.Data.Agreement = reg.GetTermsOfServiceUri();

                await client.UpdateRegistration(reg);

                var newKey = new AccountKey().Export();
                await client.ChangeKey(reg, newKey);

                await client.DeleteRegistration(reg);
            }
        }
Example #30
0
        public void SetAlgorithm(KeyAlgorithm algo)
        {
            switch (algo)
            {
            case KeyAlgorithm.DSA:
                Algorithm = PgpSubkeyAlgorithm.DSASignOnly;
                break;

            case KeyAlgorithm.ELG:
                Algorithm = PgpSubkeyAlgorithm.ELGEncryptOnly;
                break;

            case KeyAlgorithm.RSA:
                Algorithm = PgpSubkeyAlgorithm.RSAUseCapabilities;
                break;

            default:
                throw new NotSupportedException("Algorithm is not supported as sub key.",
                                                new NotSupportedException("Algorithm is not supported as sub key."));
            }
        }
Example #31
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Id.Length != 0)
            {
                hash ^= Id.GetHashCode();
            }
            if (subjectCase_ == SubjectOneofCase.UserAccountId)
            {
                hash ^= UserAccountId.GetHashCode();
            }
            if (subjectCase_ == SubjectOneofCase.ServiceAccountId)
            {
                hash ^= ServiceAccountId.GetHashCode();
            }
            if (createdAt_ != null)
            {
                hash ^= CreatedAt.GetHashCode();
            }
            if (Description.Length != 0)
            {
                hash ^= Description.GetHashCode();
            }
            if (KeyAlgorithm != global::Yandex.Cloud.Iam.V1.Key.Types.Algorithm.Unspecified)
            {
                hash ^= KeyAlgorithm.GetHashCode();
            }
            if (PublicKey.Length != 0)
            {
                hash ^= PublicKey.GetHashCode();
            }
            hash ^= (int)subjectCase_;
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Example #32
0
 /// <summary>
 /// For more information, see gpg source code, file keygen.c line 1518.
 /// </summary>
 /// <remarks>
 /// GPG does not accept a "None" algorithm, so RSA is used by default.
 /// But you should not call this function with the "None" algorithm.
 /// </remarks>
 public static Int32 ToId(KeyAlgorithm algorithm)
 {
     switch (algorithm)
     {
         case KeyAlgorithm.None: return 1;
         case KeyAlgorithm.RsaRsa: return 1;
         case KeyAlgorithm.DsaELGamal: return 2;
         case KeyAlgorithm.Dsa: return 3;
         case KeyAlgorithm.RsaSign: return 4;
         case KeyAlgorithm.ELGamal: return 5;
         case KeyAlgorithm.RsaEncrypt: return 6;
         default: return 1;
     }
 }
        private void parseinfo()
        {
            if (info != null)
            {
                string[] token = info.Split(' ');
                int len = token.Length;

                if (len > 0)
                    request_keyid = token[0];
                if (len > 1)
                    main_keyid = token[1];
                if (len > 2)
                    try
                    {
                        int ktype = int.Parse(token[2]);
                        keytype = (KeyAlgorithm)ktype;
                    }
                    catch {}
                if (len > 3)
                    try
                    {
                        int ksize = int.Parse(token[3]);
                        keylength = ksize;
                    }
                    catch { }
            }
        }