Example #1
0
        private KeyType PickKeyTypeOfficialKeyczar(KeyPurpose purpose)
        {
            KeyType type;

            if (_asymm)
            {
                if (purpose == KeyPurpose.DecryptAndEncrypt)
                {
                    type = KeyType.RsaPriv;
                }
                else
                {
                    if (_asymmAlg == "rsa")
                    {
                        type = KeyType.RsaPriv;
                    }
                    else
                    {
                        type = KeyType.DsaPriv;
                    }
                }
            }
            else if (purpose == KeyPurpose.DecryptAndEncrypt)
            {
                type = KeyType.Aes;
            }
            else
            {
                type = KeyType.HmacSha1;
            }
            return(type);
        }
Example #2
0
            /// <summary>
            /// Imports the X509 certificate.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <returns></returns>
            public virtual ImportedKeySet X509Certificate(KeyPurpose purpose, Stream input, bool official = false, KeyType hint = null)
            {
                var parser    = new X509CertificateParser();
                var cert      = parser.ReadCertificate(input);
                var bouncyKey = cert.GetPublicKey();
                Key key;

                switch (bouncyKey)
                {
                case RsaKeyParameters rsa:
                    key = KeyFromBouncyCastle(rsa, purpose, official, hint);
                    break;

                case DsaPublicKeyParameters dsa:
                    if (KeyPurpose.Encrypt == purpose)
                    {
                        throw new InvalidKeySetException("DSA key cannot be used for encryption!");
                    }
                    key = KeyFromBouncyCastle(dsa);
                    break;

                default:
                    throw new InvalidKeySetException("Unsupported key type!");
                }
                return(new ImportedKeySet(key, purpose, "imported from certificate"));
            }
Example #3
0
        public override int Run(string[] remainingArguments)
        {
            KeyPurpose purpose = _pupose == "sign" ? KeyPurpose.SignAndVerify : KeyPurpose.DecryptAndEncrypt;

            KeyType type = PickKeyType(purpose);


            var meta = new KeyMetadata()
            {
                Name    = _name,
                Purpose = purpose,
                KeyType = type,
            };

            using (var keySet = new MutableKeySet(meta))
            {
                if (keySet.Save(new KeySetWriter(_location)))
                {
                    Console.WriteLine(Localized.MsgCreatedKeySet);
                    return(0);
                }
            }
            Console.WriteLine("{0} {1}.", Localized.MsgExistingKeySet, _location);

            return(-1);
        }
Example #4
0
 private Key KeyFromBouncyCastle(RsaKeyParameters keyParam, KeyPurpose purpose, bool official = false, KeyType hint = null)
 {
     if (official || purpose == KeyPurpose.Encrypt)
     {
         return(new RsaPublicKey
         {
             Modulus = keyParam.Modulus.ToSystemBigInteger(),
             PublicExponent = keyParam.Exponent.ToSystemBigInteger(),
             Size = keyParam.Modulus.BitLength,
         });
     }
     else if (hint == UnofficialKeyType.RSAPubPkcs15Sign)
     {
         return(new Unofficial.RsaPublicSignPkcs15Key()
         {
             Modulus = keyParam.Modulus.ToSystemBigInteger(),
             PublicExponent = keyParam.Exponent.ToSystemBigInteger(),
             Size = keyParam.Modulus.BitLength,
             Digest = Unofficial.RsaPrivateSignPssKey.DigestForSize(keyParam.Modulus.BitLength)
         });
     }
     else
     {
         return(new Unofficial.RsaPublicSignPssKey
         {
             Modulus = keyParam.Modulus.ToSystemBigInteger(),
             PublicExponent = keyParam.Exponent.ToSystemBigInteger(),
             Size = keyParam.Modulus.BitLength,
             Digest = Unofficial.RsaPrivateSignPssKey.DigestForSize(keyParam.Modulus.BitLength)
         });
     }
 }
        public void TestExportPem(string keyType, string purpose, string topDir)
        {
            KeyPurpose p  = purpose;
            KeyType    kt = keyType;

            var path          = Util.TestDataPath(WRITE_DATA, topDir, "certificates");
            var pubPath       = path + ".public";
            var exportPath    = path + "-pkcs8.pem";
            var exportPubPath = path + "-public.pem";

            var writer    = new KeySetWriter(path, overwrite: true);
            var pubWriter = new KeySetWriter(pubPath, overwrite: true);

            using (var ks = CreateNewKeySet(kt, p))
            {
                var ver = ks.AddKey(KeyStatus.Primary);
                Expect(ver, Is.EqualTo(1));

                using (var pubks = ks.PublicKey())
                {
                    var pubsuccess = pubks.Save(pubWriter);
                    Expect(pubsuccess, Is.True);

                    pubsuccess = pubks.ExportPrimaryAsPkcs(exportPubPath, () => null);
                    Expect(pubsuccess, Is.True);
                }
                Func <string> password = () => "pass"; //Hardcoding because this is a test

                var success = ks.ExportPrimaryAsPkcs(exportPath, password);
                Expect(success, Is.True);

                success = ks.Save(writer);
                Expect(success, Is.True);
            }
        }
Example #6
0
        public override int Run(string[] remainingArguments)
        {
            KeyPurpose purpose = _pupose == "sign" ? KeyPurpose.SignAndVerify : KeyPurpose.DecryptAndEncrypt;

            KeyType officalKeyType = null;

            if (!_unofficial)
            {
                officalKeyType = PickKeyTypeOfficialKeyczar(purpose);
            }


            var meta = new KeyMetadata(officialMetaDataKeyType: officalKeyType)
            {
                Name    = _name,
                Purpose = purpose,
                Kind    = _asymm ? KeyKind.Private : KeyKind.Symmetric,
            };

            using (var keySet = new MutableKeySet(meta))
            {
                if (keySet.Save(new FileSystemKeySetWriter(_location)))
                {
                    Console.WriteLine(Localized.MsgCreatedKeySet);
                    return(0);
                }
            }
            Console.WriteLine("{0} {1}.", Localized.MsgExistingKeySet, _location);

            return(-1);
        }
Example #7
0
            /// <summary>
            /// Import the PKCS key.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <param name="passwordPrompt">The pass phrase prompt.</param>
            /// <param name="official"></param>
            /// <param name="hint"></param>
            /// <returns></returns>
            /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception>
            /// <exception cref="InvalidKeySetException">Unsupported key type!</exception>
            public virtual ImportedKeySet PkcsKey(KeyPurpose purpose, Stream input, Func <string> passwordPrompt = null, bool official = false, KeyType hint = null)
            {
                using (var password = CachedPrompt.Password(passwordPrompt))
                {
                    AsymmetricKeyParameter bouncyKey;
                    var resetStream = Utility.ResetStreamWhenFinished(input);
                    using (var streamReader = new NondestructiveStreamReader(input))
                    {
                        bouncyKey =
                            new PemReader(streamReader, new PasswordFinder(password.Prompt)).ReadObject() as
                            AsymmetricKeyParameter;
                    }

                    if (bouncyKey == null)
                    {
                        resetStream.Reset();
                        bouncyKey = passwordPrompt == null
                                        ? PrivateKeyFactory.CreateKey(input)
                                        : PrivateKeyFactory.DecryptKey(
                            (password.Prompt() ?? String.Empty).ToCharArray(), input);
                    }

                    Key key;

                    switch (bouncyKey)
                    {
                    case RsaPrivateCrtKeyParameters rsa:
                        key = KeyFromBouncyCastle(rsa, purpose, official, hint);
                        break;

                    case DsaPrivateKeyParameters dsa:

                        if (KeyPurpose.DecryptAndEncrypt == purpose)
                        {
                            throw new InvalidKeySetException("DSA key cannot be used for encryption and decryption!");
                        }

                        key = KeyFromBouncyCastle(dsa);
                        break;

                    case RsaKeyParameters rsa:
                        key = KeyFromBouncyCastle(rsa, purpose, official, hint);
                        break;

                    case DsaPublicKeyParameters dsa:
                        if (KeyPurpose.Encrypt == purpose)
                        {
                            throw new InvalidKeySetException("DSA key cannot be used for encryption!");
                        }
                        key = KeyFromBouncyCastle(dsa);
                        break;

                    default:
                        throw new InvalidKeySetException("Unsupported key type!");
                    }

                    return(new ImportedKeySet(key, purpose, "imported from pkcs file"));
                }
            }
Example #8
0
 private MutableKeySet CreateNewKeySetMeta(KeyKind type, KeyPurpose purpose, string name = null)
 {
     return(new MutableKeySet(new KeyMetadata
     {
         Name = name ?? "Test",
         Purpose = purpose,
         Kind = type
     }));
 }
 public T GetValidKey <T>(KeyPurpose purpose) where T : Content
 {
     foreach (var r in Book)
     {
         if (r.Purpose == purpose && r.PrivateKey is T)
         {
             return(r.PrivateKey as T);
         }
     }
     return(null);
 }
Example #10
0
        private ImportedKeySet HelperImportKeySet(String fileFormat, KeyPurpose keyPurpose, Stream keystream)
        {
            switch (fileFormat)
            {
            case "pfx":
                return(ImportedKeySet.Import.Pkcs12Keys(keyPurpose, keystream, () => "pass"
                                                        /* hard coding for test only!!!!*/, official: true));

            default:
                return(ImportedKeySet.Import.PkcsKey(keyPurpose, keystream, () => "pass"
                                                     /* hard coding for test only!!!!*/, official: true));
            }
        }
Example #11
0
 public ImportedKeySet(IEnumerable <Key> keys, KeyPurpose purpose, string description = null)
 {
     _key      = keys.ToList();
     _metadata = new KeyMetadata()
     {
         Name     = description,
         Purpose  = purpose,
         Kind     = keys.First().KeyType.Kind,
         Versions = keys.Select((it, i) =>
                                new KeyVersion(
                                    i == 0 ? KeyStatus.Primary : KeyStatus.Active,
                                    i + 1,
                                    it
                                    )).ToList()
     };
 }
Example #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImportedKeySet"/> class.
 /// </summary>
 /// <param name="key">The key.</param>
 /// <param name="purpose">The purpose.</param>
 /// <param name="description">The description.</param>
 public ImportedKeySet(Key key, KeyPurpose purpose, string description = null)
 {
     _key.Add(key);
     _metadata = new KeyMetadata()
     {
         Name     = description ?? "Imported " + key.KeyType.Identifier,
         Purpose  = purpose,
         Kind     = key.KeyType.Kind,
         Versions = new List <KeyVersion>
         {
             new KeyVersion(
                 KeyStatus.Primary,
                 1,
                 key
                 )
         }
     };
 }
Example #13
0
        private KeyType PickKeyType(KeyPurpose purpose)
        {
            KeyType type;

            if (_asymm)
            {
                if (purpose == KeyPurpose.DecryptAndEncrypt)
                {
                    type = KeyType.RsaPriv;
                }
                else
                {
                    if (_unofficial)
                    {
                        type = UnofficialKeyType.RSAPrivSign;
                    }
                    else if (_asymmAlg == "rsa")
                    {
                        type = KeyType.RsaPriv;
                    }
                    else
                    {
                        type = KeyType.DsaPriv;
                    }
                }
            }
            else if (purpose == KeyPurpose.DecryptAndEncrypt)
            {
                if (_unofficial)
                {
                    type = UnofficialKeyType.AesAead;
                }
                else
                {
                    type = KeyType.Aes;
                }
            }
            else
            {
                type = KeyType.HmacSha1;
            }
            return(type);
        }
Example #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImportedKeySet"/> class.
 /// </summary>
 /// <param name="key">The key.</param>
 /// <param name="purpose">The purpose.</param>
 /// <param name="description">The description.</param>
 public ImportedKeySet(Key key, KeyPurpose purpose, string description = null)
 {
     _key = key;
     var keyType = key.KeyType;
     _metadata = new KeyMetadata()
                     {
                         Name = description ?? "Imported" + key.KeyType.Identifier,
                         Purpose = purpose,
                         KeyType = keyType,
                         Versions = new List<KeyVersion>
                                        {
                                            new KeyVersion
                                                {
                                                    VersionNumber = 0,
                                                    Status = KeyStatus.Primary,
                                                    Exportable = false
                                                }
                                        }
                     };
 }
Example #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImportedKeySet"/> class.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="purpose">The purpose.</param>
        /// <param name="description">The description.</param>
        public ImportedKeySet(Key key, KeyPurpose purpose, string description = null)
        {
            _key = key;
            var keyType = key.KeyType;

            _metadata = new KeyMetadata()
            {
                Name     = description ?? "Imported" + key.KeyType.Identifier,
                Purpose  = purpose,
                KeyType  = keyType,
                Versions = new List <KeyVersion>
                {
                    new KeyVersion
                    {
                        VersionNumber = 0,
                        Status        = KeyStatus.Primary,
                        Exportable    = false
                    }
                }
            };
        }
Example #16
0
            /// <summary>
            /// Imports the X509 certificate.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <returns></returns>
            public virtual ImportedKeySet X509Certificate(KeyPurpose purpose, Stream input)
            {
                var parser    = new X509CertificateParser();
                var cert      = parser.ReadCertificate(input);
                var bouncyKey = cert.GetPublicKey();

                Key key;

                if (bouncyKey is RsaKeyParameters)
                {
                    var keyParam = bouncyKey as RsaKeyParameters;
                    key = new RsaPublicKey
                    {
                        Modulus        = keyParam.Modulus.ToSystemBigInteger(),
                        PublicExponent = keyParam.Exponent.ToSystemBigInteger(),
                        Size           = keyParam.Modulus.BitLength,
                    };
                }
                else if (bouncyKey is DsaPublicKeyParameters)
                {
                    var keyParam = bouncyKey as DsaPublicKeyParameters;
                    if (KeyPurpose.Encrypt == purpose)
                    {
                        throw new InvalidKeySetException("DSA key cannot be used for encryption!");
                    }
                    key = new DsaPublicKey
                    {
                        Y    = keyParam.Y.ToSystemBigInteger(),
                        G    = keyParam.Parameters.G.ToSystemBigInteger(),
                        P    = keyParam.Parameters.P.ToSystemBigInteger(),
                        Q    = keyParam.Parameters.Q.ToSystemBigInteger(),
                        Size = keyParam.Parameters.P.BitLength
                    };
                }
                else
                {
                    throw new InvalidKeySetException("Unsupported key type!");
                }
                return(new ImportedKeySet(key, purpose, "imported from certificate"));
            }
Example #17
0
 public ImportedKeySet Pkcs12Keys(KeyPurpose purpose, string path, Func <string> passwordPrompt = null, bool official = false, KeyType hint = null)
 {
     using (var stream = File.OpenRead(path))
         return(Pkcs12Keys(purpose, stream, passwordPrompt, official, hint));
 }
Example #18
0
 /// <summary>
 /// Imports the X509 the certificate.
 /// </summary>
 /// <param name="purpose">The purpose.</param>
 /// <param name="path">The path.</param>
 /// <returns></returns>
 /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception>
 /// <exception cref="InvalidKeySetException">Unsupported key type!</exception>
 public ImportedKeySet X509Certificate(KeyPurpose purpose, string path)
 {
     using (var stream = File.OpenRead(path))
         return(X509Certificate(purpose, stream));
 }
Example #19
0
            /// <summary>
            /// Import the PKCS key.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <param name="passwordPrompt">The pass phrase prompt.</param>
            /// <returns></returns>
            /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception>
            /// <exception cref="InvalidKeySetException">Unsupported key type!</exception>
            public virtual ImportedKeySet PkcsKey(KeyPurpose purpose, Stream input, Func <string> passwordPrompt = null)
            {
                using (var password = CachedPrompt.Password(passwordPrompt))
                {
                    AsymmetricKeyParameter bouncyKey;
                    var resetStream = Utility.ResetStreamWhenFinished(input);
                    using (var streamReader = new NondestructiveStreamReader(input))
                    {
                        bouncyKey =
                            new PemReader(streamReader, new PasswordFinder(password.Prompt)).ReadObject() as
                            AsymmetricKeyParameter;
                    }

                    if (bouncyKey == null)
                    {
                        resetStream.Reset();
                        bouncyKey = passwordPrompt == null
                                        ? PrivateKeyFactory.CreateKey(input)
                                        : PrivateKeyFactory.DecryptKey(
                            (password.Prompt() ?? String.Empty).ToCharArray(), input);
                    }

                    Key key;

                    if (bouncyKey is RsaPrivateCrtKeyParameters)
                    {
                        var keyParam = bouncyKey as RsaPrivateCrtKeyParameters;
                        key = new RsaPrivateKey()
                        {
                            PublicKey = new RsaPublicKey()
                            {
                                Modulus        = keyParam.Modulus.ToSystemBigInteger(),
                                PublicExponent = keyParam.PublicExponent.ToSystemBigInteger(),
                                Size           = keyParam.Modulus.BitLength,
                            },
                            PrimeP          = keyParam.P.ToSystemBigInteger(),
                            PrimeExponentP  = keyParam.DP.ToSystemBigInteger(),
                            PrimeExponentQ  = keyParam.DQ.ToSystemBigInteger(),
                            PrimeQ          = keyParam.Q.ToSystemBigInteger(),
                            CrtCoefficient  = keyParam.QInv.ToSystemBigInteger(),
                            PrivateExponent = keyParam.Exponent.ToSystemBigInteger(),
                            Size            = keyParam.Modulus.BitLength,
                        };
                    }
                    else if (bouncyKey is DsaPrivateKeyParameters)
                    {
                        var keyParam = bouncyKey as DsaPrivateKeyParameters;
                        if (KeyPurpose.DecryptAndEncrypt == purpose)
                        {
                            throw new InvalidKeySetException("DSA key cannot be used for encryption and decryption!");
                        }


                        key = new DsaPrivateKey()
                        {
                            X         = keyParam.X.ToSystemBigInteger(),
                            PublicKey = new DsaPublicKey
                            {
                                Y =
                                    keyParam.Parameters.G.ModPow(keyParam.X,
                                                                 keyParam.Parameters.P)
                                    .ToSystemBigInteger(),
                                G    = keyParam.Parameters.G.ToSystemBigInteger(),
                                P    = keyParam.Parameters.P.ToSystemBigInteger(),
                                Q    = keyParam.Parameters.Q.ToSystemBigInteger(),
                                Size = keyParam.Parameters.P.BitLength
                            },
                            Size = keyParam.Parameters.P.BitLength
                        };
                    }
                    else
                    {
                        throw new InvalidKeySetException("Unsupported key type!");
                    }


                    return(new ImportedKeySet(key, purpose, "imported from pkcs file"));
                }
            }
Example #20
0
 /// <summary>
 /// Import the PKCS key.
 /// </summary>
 /// <param name="purpose">The purpose.</param>
 /// <param name="path">The path.</param>
 /// <param name="passwordPrompt">The pass phrase prompt.</param>
 /// <returns></returns>
 public ImportedKeySet PkcsKey(KeyPurpose purpose, string path, Func <string> passwordPrompt = null)
 {
     using (var stream = File.OpenRead(path))
         return(PkcsKey(purpose, stream, passwordPrompt));
 }
Example #21
0
 /// <summary>
 /// Import the PKCS key.
 /// </summary>
 /// <param name="purpose">The purpose.</param>
 /// <param name="path">The path.</param>
 /// <param name="passwordPrompt">The pass phrase prompt.</param>
 /// <returns></returns>
 public ImportedKeySet PkcsKey(KeyPurpose purpose, string path, Func<string> passwordPrompt = null)
 {
     using (var stream = File.OpenRead(path))
         return PkcsKey(purpose, stream, passwordPrompt);
 }
Example #22
0
            /// <summary>
            /// Import the PKCS key.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <param name="passwordPrompt">The pass phrase prompt.</param>
            /// <returns></returns>
            /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception>
            /// <exception cref="InvalidKeySetException">Unsupported key type!</exception>
            public virtual ImportedKeySet PkcsKey(KeyPurpose purpose, Stream input, Func<string> passwordPrompt = null)
            {
                using (var password = CachedPrompt.Password(passwordPrompt))
                {
                    AsymmetricKeyParameter bouncyKey;
                    var resetStream = Utility.ResetStreamWhenFinished(input);
                    using (var streamReader = new NondestructiveStreamReader(input))
                    {
                        bouncyKey =
                            new PemReader(streamReader, new PasswordFinder(password.Prompt)).ReadObject() as
                            AsymmetricKeyParameter;
                    }

                    if (bouncyKey == null)
                    {
                        resetStream.Reset();
                        bouncyKey = passwordPrompt == null
                                        ? PrivateKeyFactory.CreateKey(input)
                                        : PrivateKeyFactory.DecryptKey(
                                            (password.Prompt() ?? String.Empty).ToCharArray(), input);
                    }

                    Key key;

                    if (bouncyKey is RsaPrivateCrtKeyParameters)
                    {
                        var keyParam = bouncyKey as RsaPrivateCrtKeyParameters;
                        key = new RsaPrivateKey()
                                  {
                                      PublicKey = new RsaPublicKey()
                                                      {
                                                          Modulus = keyParam.Modulus.ToSystemBigInteger(),
                                                          PublicExponent = keyParam.PublicExponent.ToSystemBigInteger(),
                                                          Size = keyParam.Modulus.BitLength,
                                                      },
                                      PrimeP = keyParam.P.ToSystemBigInteger(),
                                      PrimeExponentP = keyParam.DP.ToSystemBigInteger(),
                                      PrimeExponentQ = keyParam.DQ.ToSystemBigInteger(),
                                      PrimeQ = keyParam.Q.ToSystemBigInteger(),
                                      CrtCoefficient = keyParam.QInv.ToSystemBigInteger(),
                                      PrivateExponent = keyParam.Exponent.ToSystemBigInteger(),
                                      Size = keyParam.Modulus.BitLength,
                                  };
                    }
                    else if (bouncyKey is DsaPrivateKeyParameters)
                    {
                        var keyParam = bouncyKey as DsaPrivateKeyParameters;
                        if (KeyPurpose.DecryptAndEncrypt == purpose)
                        {
                            throw new InvalidKeySetException("DSA key cannot be used for encryption and decryption!");
                        }

                        key = new DsaPrivateKey()
                                  {
                                      X = keyParam.X.ToSystemBigInteger(),
                                      PublicKey = new DsaPublicKey
                                                      {
                                                          Y =
                                                              keyParam.Parameters.G.ModPow(keyParam.X,
                                                                                           keyParam.Parameters.P)
                                                                      .ToSystemBigInteger(),
                                                          G = keyParam.Parameters.G.ToSystemBigInteger(),
                                                          P = keyParam.Parameters.P.ToSystemBigInteger(),
                                                          Q = keyParam.Parameters.Q.ToSystemBigInteger(),
                                                          Size = keyParam.Parameters.P.BitLength
                                                      },
                                      Size = keyParam.Parameters.P.BitLength
                                  };
                    }
                    else
                    {
                        throw new InvalidKeySetException("Unsupported key type!");
                    }

                    return new ImportedKeySet(key, purpose, "imported from pkcs file");
                }
            }
Example #23
0
 private Key KeyFromBouncyCastle(RsaPrivateCrtKeyParameters keyParam, KeyPurpose purpose,
                                 bool official = false, KeyType hint = null)
 {
     if (official || purpose == KeyPurpose.DecryptAndEncrypt)
     {
         return(new RsaPrivateKey()
         {
             PublicKey = new RsaPublicKey()
             {
                 Modulus = keyParam.Modulus.ToSystemBigInteger(),
                 PublicExponent = keyParam.PublicExponent.ToSystemBigInteger(),
                 Size = keyParam.Modulus.BitLength,
             },
             PrimeP = keyParam.P.ToSystemBigInteger(),
             PrimeExponentP = keyParam.DP.ToSystemBigInteger(),
             PrimeExponentQ = keyParam.DQ.ToSystemBigInteger(),
             PrimeQ = keyParam.Q.ToSystemBigInteger(),
             CrtCoefficient = keyParam.QInv.ToSystemBigInteger(),
             PrivateExponent = keyParam.Exponent.ToSystemBigInteger(),
             Size = keyParam.Modulus.BitLength,
         });
     }
     else if (hint == UnofficialKeyType.RSAPrivPkcs15Sign)
     {
         return(new Unofficial.RsaPrivateSignPkcs15Key()
         {
             PublicKey = new Unofficial.RsaPublicSignPkcs15Key()
             {
                 Modulus = keyParam.Modulus.ToSystemBigInteger(),
                 PublicExponent = keyParam.PublicExponent.ToSystemBigInteger(),
                 Size = keyParam.Modulus.BitLength,
                 Digest = Unofficial.RsaPrivateSignPssKey.DigestForSize(keyParam.Modulus.BitLength)
             },
             PrimeP = keyParam.P.ToSystemBigInteger(),
             PrimeExponentP = keyParam.DP.ToSystemBigInteger(),
             PrimeExponentQ = keyParam.DQ.ToSystemBigInteger(),
             PrimeQ = keyParam.Q.ToSystemBigInteger(),
             CrtCoefficient = keyParam.QInv.ToSystemBigInteger(),
             PrivateExponent = keyParam.Exponent.ToSystemBigInteger(),
             Size = keyParam.Modulus.BitLength,
         });
     }
     else
     {
         return(new Unofficial.RsaPrivateSignPssKey()
         {
             PublicKey = new Unofficial.RsaPublicSignPssKey()
             {
                 Modulus = keyParam.Modulus.ToSystemBigInteger(),
                 PublicExponent = keyParam.PublicExponent.ToSystemBigInteger(),
                 Size = keyParam.Modulus.BitLength,
                 Digest = Unofficial.RsaPrivateSignPssKey.DigestForSize(keyParam.Modulus.BitLength)
             },
             PrimeP = keyParam.P.ToSystemBigInteger(),
             PrimeExponentP = keyParam.DP.ToSystemBigInteger(),
             PrimeExponentQ = keyParam.DQ.ToSystemBigInteger(),
             PrimeQ = keyParam.Q.ToSystemBigInteger(),
             CrtCoefficient = keyParam.QInv.ToSystemBigInteger(),
             PrivateExponent = keyParam.Exponent.ToSystemBigInteger(),
             Size = keyParam.Modulus.BitLength,
         });
     }
 }
Example #24
0
            /// <summary>
            /// Imports the X509 certificate.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <returns></returns>
            public virtual ImportedKeySet X509Certificate(KeyPurpose purpose, Stream input)
            {
                var parser = new X509CertificateParser();
                var cert = parser.ReadCertificate(input);
                var bouncyKey = cert.GetPublicKey();

                Key key;
                if (bouncyKey is RsaKeyParameters)
                {
                    var keyParam = bouncyKey as RsaKeyParameters;
                    key = new RsaPublicKey
                              {
                                  Modulus = keyParam.Modulus.ToSystemBigInteger(),
                                  PublicExponent = keyParam.Exponent.ToSystemBigInteger(),
                                  Size = keyParam.Modulus.BitLength,
                              };
                }
                else if (bouncyKey is DsaPublicKeyParameters)
                {
                    var keyParam = bouncyKey as DsaPublicKeyParameters;
                    if (KeyPurpose.Encrypt == purpose)
                    {
                        throw new InvalidKeySetException("DSA key cannot be used for encryption!");
                    }
                    key = new DsaPublicKey
                              {
                                  Y = keyParam.Y.ToSystemBigInteger(),
                                  G = keyParam.Parameters.G.ToSystemBigInteger(),
                                  P = keyParam.Parameters.P.ToSystemBigInteger(),
                                  Q = keyParam.Parameters.Q.ToSystemBigInteger(),
                                  Size = keyParam.Parameters.P.BitLength
                              };
                }
                else
                {
                    throw new InvalidKeySetException("Unsupported key type!");
                }
                return new ImportedKeySet(key, purpose, "imported from certificate");
            }
Example #25
0
 /// <summary>
 /// Imports the X509 the certificate.
 /// </summary>
 /// <param name="purpose">The purpose.</param>
 /// <param name="path">The path.</param>
 /// <param name="official"></param>
 /// <param name="hint"></param>
 /// <returns></returns>
 /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception>
 /// <exception cref="InvalidKeySetException">Unsupported key type!</exception>
 public ImportedKeySet X509Certificate(KeyPurpose purpose, string path, bool official = false, KeyType hint = null)
 {
     using (var stream = File.OpenRead(path))
         return(X509Certificate(purpose, stream, official, hint));
 }
Example #26
0
 /// <summary>
 /// Imports the X509 the certificate.
 /// </summary>
 /// <param name="purpose">The purpose.</param>
 /// <param name="path">The path.</param>
 /// <returns></returns>
 /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception>
 /// <exception cref="InvalidKeySetException">Unsupported key type!</exception>
 public ImportedKeySet X509Certificate(KeyPurpose purpose, string path)
 {
     using (var stream = File.OpenRead(path))
         return X509Certificate(purpose, stream);
 }
Example #27
0
            public virtual ImportedKeySet Pkcs12Keys(KeyPurpose purpose, Stream input, Func <string> passwordPrompt = null, bool official = false, KeyType hint = null)
            {
                using (var password = CachedPrompt.Password(passwordPrompt))
                {
                    var keyStore = new Pkcs12Store(input, password.Prompt().ToCharArray());
                    var keys     = new List <Key>();
                    foreach (string n in keyStore.Aliases)
                    {
                        if (keyStore.IsKeyEntry(n))
                        {
                            AsymmetricKeyEntry key = keyStore.GetKey(n);

                            if (key.Key.IsPrivate)
                            {
                                switch (key.Key)
                                {
                                case RsaPrivateCrtKeyParameters rsa:
                                    keys.Add(KeyFromBouncyCastle(rsa, purpose, official, hint));
                                    break;

                                case DsaPrivateKeyParameters dsa:
                                    if (purpose == KeyPurpose.SignAndVerify)
                                    {
                                        keys.Add(KeyFromBouncyCastle(dsa));
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    if (!keys.Any())
                    {
                        foreach (string n in keyStore.Aliases)
                        {
                            if (keyStore.IsCertificateEntry(n))
                            {
                                var entry  = keyStore.GetCertificate(n);
                                var pubKey = entry.Certificate.GetPublicKey();
                                switch (pubKey)
                                {
                                case RsaKeyParameters rsa:
                                    keys.Add(KeyFromBouncyCastle(rsa, purpose, official, hint));
                                    break;

                                case DsaPublicKeyParameters dsa:
                                    if (purpose == KeyPurpose.SignAndVerify)
                                    {
                                        keys.Add(KeyFromBouncyCastle(dsa));
                                    }
                                    break;
                                }
                            }
                        }
                    }

                    if (keys.Any())
                    {
                        return(new ImportedKeySet(keys, purpose, "imported keys"));
                    }
                    throw new InvalidKeySetException("couldn't find any keys in file");
                }
            }