/**
         * Return a RFC 3280 type 2 key identifier. As in:
         * <pre>
         * (2) The keyIdentifier is composed of a four bit type field with
         * the value 0100 followed by the least significant 60 bits of the
         * SHA-1 hash of the value of the BIT STRING subjectPublicKey.
         * </pre>
         * @param keyInfo the key info object containing the subjectPublicKey field.
         * @return the key identifier.
         */
        public static SubjectKeyIdentifier CreateTruncatedSha1KeyIdentifier(
            SubjectPublicKeyInfo keyInfo)
        {
            byte[] dig = GetDigest(keyInfo);
            byte[] id = new byte[8];

            Array.Copy(dig, dig.Length - 8, id, 0, id.Length);

            id[0] &= 0x0f;
            id[0] |= 0x40;

            return new SubjectKeyIdentifier(id);
        }
示例#2
0
		public void Test_SubjectPublicKeyInfo()
		{
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo();
			AlgorithmIdentifier ai = new AlgorithmIdentifier();
			ai.Assign(OID.RSA.sha1WithRSAEncryption);

			BERWriter.DumpHEX(ai);


			spki.Assign(ai, new ASN1BitString(new byte[]{0x1, 0x2}, 9));

			BERWriter.DumpHEX(spki);
			

		}
        public CertificationRequestInfo(
            X509Name				subject,
            SubjectPublicKeyInfo	pkInfo,
            Asn1Set					attributes)
        {
            this.subject = subject;
            this.subjectPKInfo = pkInfo;
            this.attributes = attributes;

            if (subject == null || version == null || subjectPKInfo == null)
            {
                throw new ArgumentException(
                    "Not all mandatory fields set in CertificationRequestInfo generator.");
            }
        }
        private CertTemplate(Asn1Sequence seq)
        {
            this.seq = seq;

            foreach (Asn1TaggedObject tObj in seq)
            {
                switch (tObj.TagNo)
                {
                case 0:
                    version = DerInteger.GetInstance(tObj, false);
                    break;
                case 1:
                    serialNumber = DerInteger.GetInstance(tObj, false);
                    break;
                case 2:
                    signingAlg = AlgorithmIdentifier.GetInstance(tObj, false);
                    break;
                case 3:
                    issuer = X509Name.GetInstance(tObj, true); // CHOICE
                    break;
                case 4:
                    validity = OptionalValidity.GetInstance(Asn1Sequence.GetInstance(tObj, false));
                    break;
                case 5:
                    subject = X509Name.GetInstance(tObj, true); // CHOICE
                    break;
                case 6:
                    publicKey = SubjectPublicKeyInfo.GetInstance(tObj, false);
                    break;
                case 7:
                    issuerUID = DerBitString.GetInstance(tObj, false);
                    break;
                case 8:
                    subjectUID = DerBitString.GetInstance(tObj, false);
                    break;
                case 9:
                    extensions = X509Extensions.GetInstance(tObj, false);
                    break;
                default:
                    throw new ArgumentException("unknown tag: " + tObj.TagNo, "seq");
                }
            }
        }
示例#5
0
		static Samples() 
		{
			/// utcTime
			utcTime = new ASN1UTCTime();
			utcTime.Assign("0401291907+0100"); /// 29/01/2004, 19:07, CET
			utcTime.DecodeString();

			
			
			/// Name (X.501)
			name = new Name();

			try 
			{
				using(FileStream fs = new FileStream(@"test.X501.Name.01.ber", FileMode.Open)) 
				{
					BinaryReader br = new BinaryReader(fs);
					byte[] ber_bytes = br.ReadBytes((int)fs.Length);

					BEREncoding ber = new BEREncoding(ber_bytes);
					name.fromBER(ber);

					fs.Close();
				}
			}
			catch (System.Exception e)
			{
				Console.WriteLine(e.ToString());
				throw new Exception("Samples pallette failed at initializing .name!");
			}


			/// SubjectPublicKeyInfo subjectPKInfo
			subjectPKInfo = new SubjectPublicKeyInfo();
			//			ContentEncryptionAlgorithmIdentifier alg = new ContentEncryptionAlgorithmIdentifier();
			//			alg.Assign(PKCS7.CMS_AlgorithmIdentifiers.rsaEncryption, null);
			//			subjectPKInfo.Assign(alg, new ASN1BitString(new byte[]{0x1, 0x1, 0x1}, 19));
			

		}
        private CertificationRequestInfo(
            Asn1Sequence seq)
        {
            version = (DerInteger) seq[0];

            subject = X509Name.GetInstance(seq[1]);
            subjectPKInfo = SubjectPublicKeyInfo.GetInstance(seq[2]);

            //
            // some CertificationRequestInfo objects seem to treat this field
            // as optional.
            //
            if (seq.Count > 3)
            {
                DerTaggedObject tagobj = (DerTaggedObject) seq[3];
                attributes = Asn1Set.GetInstance(tagobj, false);
            }

            if (subject == null || version == null || subjectPKInfo == null)
            {
                throw new ArgumentException(
                    "Not all mandatory fields set in CertificationRequestInfo generator.");
            }
        }
        /// <summary>
        /// Create a Subject Public Key Info object for a given public key.
        /// </summary>
        /// <param name="publicKey">One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters</param>
        /// <returns>A subject public key info object.</returns>
        /// <exception cref="Exception">Throw exception if object provided is not one of the above.</exception>
        public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo(
            AsymmetricKeyParameter publicKey)
        {
            if (publicKey == null)
                throw new ArgumentNullException("publicKey");
            if (publicKey.IsPrivate)
                throw new ArgumentException("Private key passed - public key expected.", "publicKey");

            if (publicKey is ElGamalPublicKeyParameters)
            {
                ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)publicKey;
                ElGamalParameters kp = _key.Parameters;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(
                        OiwObjectIdentifiers.ElGamalAlgorithm,
                        new ElGamalParameter(kp.P, kp.G).ToAsn1Object()),
                        new DerInteger(_key.Y));

                return info;
            }

            if (publicKey is DsaPublicKeyParameters)
            {
                DsaPublicKeyParameters _key = (DsaPublicKeyParameters) publicKey;
                DsaParameters kp = _key.Parameters;
                Asn1Encodable ae = kp == null
                    ?	null
                    :	new DsaParameter(kp.P, kp.Q, kp.G).ToAsn1Object();

                return new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, ae),
                    new DerInteger(_key.Y));
            }

            if (publicKey is DHPublicKeyParameters)
            {
                DHPublicKeyParameters _key = (DHPublicKeyParameters) publicKey;
                DHParameters kp = _key.Parameters;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(
                        _key.AlgorithmOid,
                        new DHParameter(kp.P, kp.G, kp.L).ToAsn1Object()),
                        new DerInteger(_key.Y));

                return info;
            } // End of DH

            if (publicKey is RsaKeyParameters)
            {
                RsaKeyParameters _key = (RsaKeyParameters) publicKey;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance),
                    new RsaPublicKeyStructure(_key.Modulus, _key.Exponent).ToAsn1Object());

                return info;
            } // End of RSA.

            if (publicKey is ECPublicKeyParameters)
            {            
               
                ECPublicKeyParameters _key = (ECPublicKeyParameters) publicKey;


                if (_key.Parameters is ECGost3410Parameters)
                {
                    ECGost3410Parameters gostParams = (ECGost3410Parameters)_key.Parameters;

                    BigInteger bX = _key.Q.AffineXCoord.ToBigInteger();
                    BigInteger bY = _key.Q.AffineYCoord.ToBigInteger();
                    bool is512 = (bX.BitLength > 256);

                    Gost3410PublicKeyAlgParameters parameters = new Gost3410PublicKeyAlgParameters(
                        gostParams.PublicKeyParamSet,
                        gostParams.DigestParamSet,
                        gostParams.EncryptionParamSet);

                    int encKeySize;
                    int offset;
                    DerObjectIdentifier algIdentifier;
                    if (is512)
                    {
                        encKeySize = 128;
                        offset = 64;
                        algIdentifier = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512;
                    }
                    else
                    {
                        encKeySize = 64;
                        offset = 32;
                        algIdentifier = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256;
                    }

                    byte[] encKey = new byte[encKeySize];
               
                    ExtractBytes(encKey, encKeySize / 2, 0, bX);
                    ExtractBytes(encKey, encKeySize / 2, offset, bY);
                  
                    return new SubjectPublicKeyInfo(new AlgorithmIdentifier(algIdentifier, parameters), new DerOctetString(encKey));
                   

                } // End of ECGOST3410_2012





                if (_key.AlgorithmName == "ECGOST3410")
                {
                    if (_key.PublicKeyParamSet == null)
                        throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");

                    ECPoint q = _key.Q.Normalize();
                    BigInteger bX = q.AffineXCoord.ToBigInteger();
                    BigInteger bY = q.AffineYCoord.ToBigInteger();

                    byte[] encKey = new byte[64];
                    ExtractBytes(encKey, 0, bX);
                    ExtractBytes(encKey, 32, bY);

                    Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                        _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);

                    AlgorithmIdentifier algID = new AlgorithmIdentifier(
                        CryptoProObjectIdentifiers.GostR3410x2001,
                        gostParams.ToAsn1Object());

                    return new SubjectPublicKeyInfo(algID, new DerOctetString(encKey));
                }
                else
                {
                    X962Parameters x962;
                    if (_key.PublicKeyParamSet == null)
                    {
                        ECDomainParameters kp = _key.Parameters;
                        X9ECParameters ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed());

                        x962 = new X962Parameters(ecP);
                    }
                    else
                    {
                        x962 = new X962Parameters(_key.PublicKeyParamSet);
                    }

                    byte[] pubKey = _key.Q.GetEncoded(false);

                    AlgorithmIdentifier algID = new AlgorithmIdentifier(
                        X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object());

                    return new SubjectPublicKeyInfo(algID, pubKey);
                }
            } // End of EC

            if (publicKey is Gost3410PublicKeyParameters)
            {
                Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters) publicKey;

                if (_key.PublicKeyParamSet == null)
                    throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");

                byte[] keyEnc = _key.Y.ToByteArrayUnsigned();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyBytes.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian
                }

                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);

                AlgorithmIdentifier algID = new AlgorithmIdentifier(
                    CryptoProObjectIdentifiers.GostR3410x94,
                    algParams.ToAsn1Object());

                return new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes));
            }

            if (publicKey is X448PublicKeyParameters)
            {
                X448PublicKeyParameters key = (X448PublicKeyParameters)publicKey;

                return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448), key.GetEncoded());
            }

            if (publicKey is X25519PublicKeyParameters)
            {
                X25519PublicKeyParameters key = (X25519PublicKeyParameters)publicKey;

                return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), key.GetEncoded());
            }

            if (publicKey is Ed448PublicKeyParameters)
            {
                Ed448PublicKeyParameters key = (Ed448PublicKeyParameters)publicKey;

                return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448), key.GetEncoded());
            }

            if (publicKey is Ed25519PublicKeyParameters)
            {
                Ed25519PublicKeyParameters key = (Ed25519PublicKeyParameters)publicKey;

                return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), key.GetEncoded());
            }

            throw new ArgumentException("Class provided no convertible: " + Platform.GetTypeName(publicKey));
        }
 public ProofOfPossessionSigningKeyBuilder(SubjectPublicKeyInfo pubKeyInfo)
 {
     this._pubKeyInfo = pubKeyInfo;
 }
        ///// <summary>
        ///// Create a new certificate
        ///// </summary>
        ///// <param name="issuer">Issuer certificate, if null then self-sign</param>
        ///// <param name="subjectName">Subject name</param>
        ///// <param name="serialNumber">Serial number of certificate, if null then will generate a new one</param>
        ///// <param name="keySize">Size of RSA key</param>
        ///// <param name="notBefore">Start date of certificate</param>
        ///// <param name="notAfter">End date of certificate</param>
        ///// <param name="extensions">Array of extensions, if null then no extensions</param>
        ///// <param name="hashAlgorithm">Specify the signature hash algorithm</param>
        ///// <returns>The created X509 certificate</returns>
        public static SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 issuer, SystemX509.X500DistinguishedName subjectName,
                                                             byte[] serialNumber, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore,
                                                             DateTime notAfter, SystemX509.X509ExtensionCollection extensions)
        {
            SecureRandom random = new SecureRandom();
            X509V3CertificateGenerator builder      = new X509V3CertificateGenerator();
            AsymmetricCipherKeyPair    bcSubjectKey = CreateRSAKey(keySize, random);
            AsymmetricCipherKeyPair    bcSignKey    = issuer == null ? bcSubjectKey : issuer.GetBCPrivateKey();

            if (bcSignKey == null)
            {
                throw new ArgumentException("issuer");
            }

            X509Name issuerNameObj = issuer == null?X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData))
                                         : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData));

            X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData));

            BigInteger subjectSerial = new BigInteger(1, serialNumber != null ? serialNumber : Guid.NewGuid().ToByteArray());
            BigInteger issuerSerial  = issuer == null ? subjectSerial : new BigInteger(1, issuer.GetSerialNumber());

            builder.SetIssuerDN(issuerNameObj);
            builder.SetSubjectDN(subjectNameObj);
            builder.SetSerialNumber(subjectSerial);
            builder.SetNotBefore(notBefore.ToUniversalTime());
            builder.SetNotAfter(notAfter.ToUniversalTime());
            builder.SetPublicKey(bcSubjectKey.Public);

            SubjectPublicKeyInfo   info         = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSignKey.Public);
            AuthorityKeyIdentifier authKeyId    = new AuthorityKeyIdentifier(info, new GeneralNames(new GeneralName(issuerNameObj)), issuerSerial);
            SubjectKeyIdentifier   subjectKeyid = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSubjectKey.Public));

            builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authKeyId);
            builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, true, subjectKeyid);

            if (extensions != null)
            {
                foreach (SystemX509.X509Extension ext in extensions)
                {
                    if (!ext.Oid.Value.Equals(X509Extensions.AuthorityKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(X509Extensions.SubjectKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(szOID_AUTHORITY_KEY_IDENTIFIER2))
                    {
                        Asn1InputStream istm = new Asn1InputStream(ext.RawData);
                        Asn1Object      obj  = istm.ReadObject();
                        builder.AddExtension(ext.Oid.Value, ext.Critical, obj);
                    }
                }
            }

            X509Certificate cert = builder.Generate(CreateSignatureFactory(hashAlgorithm, bcSignKey, random));

            Pkcs12StoreBuilder   pkcs  = new Pkcs12StoreBuilder();
            Pkcs12Store          store = pkcs.Build();
            X509CertificateEntry entry = new X509CertificateEntry(cert);

            store.SetCertificateEntry("main", entry);

            AsymmetricKeyEntry key_entry = new AsymmetricKeyEntry(bcSubjectKey.Private);

            store.SetKeyEntry("main", key_entry, new[] { entry });
            MemoryStream stm = new MemoryStream();

            store.Save(stm, new char[0], new SecureRandom());
            return(new SystemX509.X509Certificate2(stm.ToArray(), String.Empty, SystemX509.X509KeyStorageFlags.Exportable));
        }
 /// <summary>
 /// Constructor from an algorithm and a SubjectPublicKeyInfo object containing an RSA public key.
 /// </summary>
 /// <param name="algorithm">Algorithm marker to associate with the key.</param>
 /// <param name="publicKeyInfo">A SubjectPublicKeyInfo object.</param>
 public AsymmetricRsaPublicKey(Algorithm algorithm, SubjectPublicKeyInfo publicKeyInfo)
     : this(algorithm, publicKeyInfo.AlgorithmID, ParsePublicKey(publicKeyInfo))
 {
 }
示例#11
0
            public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest)
            {
                if (certificateRequest.CertificateTypes == null ||
                    !Arrays.Contains(certificateRequest.CertificateTypes, ClientCertificateType.ecdsa_sign))
                {
                    return(null);
                }

                if (TlsKey != null)
                {
                    if (TlsKey.CertType == CertificateType.X509)
                    {
                        return(new DefaultTlsSignerCredentials(_mContext, new Certificate(TlsKey.X509Certificate), TlsKey.PrivateKey.AsPrivateKey(),
                                                               new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                    }
#if SUPPORT_RPK
                    else if (TlsKey.CertType == CertificateType.RawPublicKey)
                    {
                        OneKey k = TlsKey.PrivateKey;
                        if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                            k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                        {
                            X9ECParameters         p          = k.GetCurve();
                            ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
                            ECPrivateKeyParameters privKey    = new ECPrivateKeyParameters("ECDSA", ConvertBigNum(k[CoseKeyParameterKeys.EC_D]), parameters);

                            ECPoint point = k.GetPoint();
                            ECPublicKeyParameters param = new ECPublicKeyParameters("ECDSA", point, /*parameters*/ SecObjectIdentifiers.SecP256r1);

                            SubjectPublicKeyInfo spi = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(param);

                            return(new DefaultTlsSignerCredentials(_mContext, new RawPublicKey(spi), privKey, new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                        }
                    }
#endif
#if SUPPORT_TLS_CWT
                    else if (TlsKey.CertType == CertificateType.CwtPublicKey)
                    {
                        OneKey k = TlsKey.PublicCwt.Cnf.Key;
                        if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                            k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                        {
                            AsymmetricKeyParameter privKey = TlsKey.PrivateKey.AsPrivateKey();

                            return(new DefaultTlsSignerCredentials(_mContext, new CwtPublicKey(TlsKey.PublicCwt.EncodeToBytes()), privKey,
                                                                   new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                        }
                    }
#endif
                }

                // If we did not fine appropriate signer credentials - ask for help

                TlsEvent e = new TlsEvent(TlsEvent.EventCode.SignCredentials)
                {
                    CipherSuite = KeyExchangeAlgorithm.ECDHE_ECDSA
                };

                EventHandler <TlsEvent> handler = TlsEventHandler;
                if (handler != null)
                {
                    handler(this, e);
                }

                if (e.SignerCredentials != null)
                {
                    return(e.SignerCredentials);
                }
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }
示例#12
0
        private object ReadPrivateKey(PemObject pemObject)
        {
            string text = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();

            byte[]      array      = pemObject.Content;
            IDictionary dictionary = Platform.CreateHashtable();

            foreach (PemHeader pemHeader in pemObject.Headers)
            {
                dictionary[pemHeader.Name] = pemHeader.Value;
            }
            string a = (string)dictionary["Proc-Type"];

            if (a == "4,ENCRYPTED")
            {
                if (this.pFinder == null)
                {
                    throw new PasswordException("No password finder specified, but a password is required");
                }
                char[] password = this.pFinder.GetPassword();
                if (password == null)
                {
                    throw new PasswordException("Password is null, but a password is required");
                }
                string   text2  = (string)dictionary["DEK-Info"];
                string[] array2 = text2.Split(new char[]
                {
                    ','
                });
                string dekAlgName = array2[0].Trim();
                byte[] iv         = Hex.Decode(array2[1].Trim());
                array = PemUtilities.Crypt(false, array, password, dekAlgName, iv);
            }
            object result;

            try
            {
                Asn1Sequence instance = Asn1Sequence.GetInstance(array);
                string       a2;
                if ((a2 = text) != null)
                {
                    AsymmetricKeyParameter asymmetricKeyParameter;
                    AsymmetricKeyParameter publicParameter;
                    if (!(a2 == "RSA"))
                    {
                        if (!(a2 == "DSA"))
                        {
                            if (!(a2 == "EC"))
                            {
                                if (!(a2 == "ENCRYPTED"))
                                {
                                    if (!(a2 == ""))
                                    {
                                        goto IL_356;
                                    }
                                    result = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(instance));
                                    return(result);
                                }
                                else
                                {
                                    char[] password2 = this.pFinder.GetPassword();
                                    if (password2 == null)
                                    {
                                        throw new PasswordException("Password is null, but a password is required");
                                    }
                                    result = PrivateKeyFactory.DecryptKey(password2, EncryptedPrivateKeyInfo.GetInstance(instance));
                                    return(result);
                                }
                            }
                            else
                            {
                                ECPrivateKeyStructure eCPrivateKeyStructure = new ECPrivateKeyStructure(instance);
                                AlgorithmIdentifier   algID   = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, eCPrivateKeyStructure.GetParameters());
                                PrivateKeyInfo        keyInfo = new PrivateKeyInfo(algID, eCPrivateKeyStructure.ToAsn1Object());
                                asymmetricKeyParameter = PrivateKeyFactory.CreateKey(keyInfo);
                                DerBitString publicKey = eCPrivateKeyStructure.GetPublicKey();
                                if (publicKey != null)
                                {
                                    SubjectPublicKeyInfo keyInfo2 = new SubjectPublicKeyInfo(algID, publicKey.GetBytes());
                                    publicParameter = PublicKeyFactory.CreateKey(keyInfo2);
                                }
                                else
                                {
                                    publicParameter = ECKeyPairGenerator.GetCorrespondingPublicKey((ECPrivateKeyParameters)asymmetricKeyParameter);
                                }
                            }
                        }
                        else
                        {
                            if (instance.Count != 6)
                            {
                                throw new PemException("malformed sequence in DSA private key");
                            }
                            DerInteger    derInteger  = (DerInteger)instance[1];
                            DerInteger    derInteger2 = (DerInteger)instance[2];
                            DerInteger    derInteger3 = (DerInteger)instance[3];
                            DerInteger    derInteger4 = (DerInteger)instance[4];
                            DerInteger    derInteger5 = (DerInteger)instance[5];
                            DsaParameters parameters  = new DsaParameters(derInteger.Value, derInteger2.Value, derInteger3.Value);
                            asymmetricKeyParameter = new DsaPrivateKeyParameters(derInteger5.Value, parameters);
                            publicParameter        = new DsaPublicKeyParameters(derInteger4.Value, parameters);
                        }
                    }
                    else
                    {
                        if (instance.Count != 9)
                        {
                            throw new PemException("malformed sequence in RSA private key");
                        }
                        RsaPrivateKeyStructure instance2 = RsaPrivateKeyStructure.GetInstance(instance);
                        publicParameter        = new RsaKeyParameters(false, instance2.Modulus, instance2.PublicExponent);
                        asymmetricKeyParameter = new RsaPrivateCrtKeyParameters(instance2.Modulus, instance2.PublicExponent, instance2.PrivateExponent, instance2.Prime1, instance2.Prime2, instance2.Exponent1, instance2.Exponent2, instance2.Coefficient);
                    }
                    result = new AsymmetricCipherKeyPair(publicParameter, asymmetricKeyParameter);
                    return(result);
                }
IL_356:
                throw new ArgumentException("Unknown key type: " + text, "type");
            }
            catch (IOException ex)
            {
                throw ex;
            }
            catch (Exception ex2)
            {
                throw new PemException("problem creating " + text + " private key: " + ex2.ToString());
            }
            return(result);
        }
示例#13
0
        /// <summary>
        /// Create a Subject Public Key Info object for a given public key.
        /// </summary>
        /// <param name="key">One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters</param>
        /// <returns>A subject public key info object.</returns>
        /// <exception cref="Exception">Throw exception if object provided is not one of the above.</exception>
        public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo(
            AsymmetricKeyParameter key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (key.IsPrivate)
            {
                throw new ArgumentException("Private key passed - public key expected.", "key");
            }

            if (key is ElGamalPublicKeyParameters)
            {
                ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)key;
                ElGamalParameters          kp   = _key.Parameters;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(
                        OiwObjectIdentifiers.ElGamalAlgorithm,
                        new ElGamalParameter(kp.P, kp.G).ToAsn1Object()),
                    new DerInteger(_key.Y));

                return(info);
            }

            if (key is DsaPublicKeyParameters)
            {
                DsaPublicKeyParameters _key = (DsaPublicKeyParameters)key;
                DsaParameters          kp   = _key.Parameters;
                Asn1Encodable          ae   = kp == null
                                        ?       null
                                        :       new DsaParameter(kp.P, kp.Q, kp.G).ToAsn1Object();

                return(new SubjectPublicKeyInfo(
                           new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, ae),
                           new DerInteger(_key.Y)));
            }

            if (key is DHPublicKeyParameters)
            {
                DHPublicKeyParameters _key = (DHPublicKeyParameters)key;
                DHParameters          kp   = _key.Parameters;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(
                        _key.AlgorithmOid,
                        new DHParameter(kp.P, kp.G, kp.L).ToAsn1Object()),
                    new DerInteger(_key.Y));

                return(info);
            } // End of DH

            if (key is RsaKeyParameters)
            {
                RsaKeyParameters _key = (RsaKeyParameters)key;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance),
                    new RsaPublicKeyStructure(_key.Modulus, _key.Exponent).ToAsn1Object());

                return(info);
            } // End of RSA.

            if (key is ECPublicKeyParameters)
            {
                ECPublicKeyParameters _key = (ECPublicKeyParameters)key;

                if (_key.AlgorithmName == "ECGOST3410")
                {
                    if (_key.PublicKeyParamSet == null)
                    {
                        throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
                    }

                    ECPoint    q  = _key.Q;
                    BigInteger bX = q.X.ToBigInteger();
                    BigInteger bY = q.Y.ToBigInteger();

                    byte[] encKey = new byte[64];
                    ExtractBytes(encKey, 0, bX);
                    ExtractBytes(encKey, 32, bY);

                    Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                        _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);

                    AlgorithmIdentifier algID = new AlgorithmIdentifier(
                        CryptoProObjectIdentifiers.GostR3410x2001,
                        gostParams.ToAsn1Object());

                    return(new SubjectPublicKeyInfo(algID, new DerOctetString(encKey)));
                }
                else
                {
                    X962Parameters x962;
                    if (_key.PublicKeyParamSet == null)
                    {
                        ECDomainParameters kp  = _key.Parameters;
                        X9ECParameters     ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed());

                        x962 = new X962Parameters(ecP);
                    }
                    else
                    {
                        x962 = new X962Parameters(_key.PublicKeyParamSet);
                    }

                    Asn1OctetString p = (Asn1OctetString)(new X9ECPoint(_key.Q).ToAsn1Object());

                    AlgorithmIdentifier algID = new AlgorithmIdentifier(
                        X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object());

                    return(new SubjectPublicKeyInfo(algID, p.GetOctets()));
                }
            }             // End of EC

            if (key is Gost3410PublicKeyParameters)
            {
                Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters)key;

                if (_key.PublicKeyParamSet == null)
                {
                    throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
                }

                byte[] keyEnc   = _key.Y.ToByteArrayUnsigned();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyBytes.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i];                     // must be little endian
                }

                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);

                AlgorithmIdentifier algID = new AlgorithmIdentifier(
                    CryptoProObjectIdentifiers.GostR3410x94,
                    algParams.ToAsn1Object());

                return(new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes)));
            }

            throw new ArgumentException("Class provided no convertible: " + key.GetType().FullName);
        }
示例#14
0
 public PopoSigningKeyInput(PKMacValue pkmac, SubjectPublicKeyInfo spki)
 {
     this.publicKeyMac = pkmac;
     this.publicKey    = spki;
 }
示例#15
0
        private static OriginatorPublicKey CreateOriginatorPublicKey(AsymmetricKeyParameter publicKey)
        {
            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            return(new OriginatorPublicKey(new AlgorithmIdentifier(subjectPublicKeyInfo.AlgorithmID.Algorithm, DerNull.Instance), subjectPublicKeyInfo.PublicKeyData.GetBytes()));
        }
 /// <summary>
 /// Return a RFC 5280 type 1 key identifier. As in: "(1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
 /// value of the BIT STRING subjectPublicKey(excluding the tag, length, and number of unused bits)."
 /// </summary>
 /// <param name="publicKeyInfo">the key info object containing the subjectPublicKey field.</param>
 /// <returns>the key identifier.</returns>
 public SubjectKeyIdentifier CreateSubjectKeyIdentifier(
     SubjectPublicKeyInfo publicKeyInfo)
 {
     return(new SubjectKeyIdentifier(calculateIdentifier(publicKeyInfo)));
 }
示例#17
0
文件: X9Test.cs 项目: 894880010/MP
        private void EncodePublicKey()
        {
            X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3);

            if (X9IntegerConverter.GetByteLength(ecP.Curve) != 30)
            {
                Fail("wrong byte length reported for curve");
            }

            if (ecP.Curve.FieldSize != 239)
            {
                Fail("wrong field size reported for curve");
            }

            //
            // named curve
            //
            X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1);
            ECPoint        point   = ecP.G.Multiply(BigInteger.ValueOf(100));

            DerOctetString p = new DerOctetString(point.GetEncoded(true));

            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets());

            if (!Arrays.AreEqual(info.GetEncoded(), namedPub))
            {
                Fail("failed public named generation");
            }

            X9ECPoint x9P = new X9ECPoint(ecP.Curve, p);

            if (!Arrays.AreEqual(p.GetOctets(), x9P.Point.GetEncoded()))
            {
                Fail("point encoding not preserved");
            }

            Asn1Object o = Asn1Object.FromByteArray(namedPub);

            if (!info.Equals(o))
            {
                Fail("failed public named equality");
            }

            //
            // explicit curve parameters
            //
            _params = new X962Parameters(ecP);

            info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets());

            if (!Arrays.AreEqual(info.GetEncoded(), expPub))
            {
                Fail("failed public explicit generation");
            }

            o = Asn1Object.FromByteArray(expPub);

            if (!info.Equals(o))
            {
                Fail("failed public explicit equality");
            }
        }
示例#18
0
 public static OneAsymmetricKeyInfo CreateOneAsymmetricKeyInfo(RSAKeyPair keyPair)
 {
     return(CreateOneAsymmetricKeyInfo(PrivateKeyInfo.GetInstance(keyPair.PrivateKey), SubjectPublicKeyInfo.GetInstance(keyPair.PublicKey)));
 }
 public virtual CertTemplateBuilder SetPublicKey(SubjectPublicKeyInfo spki)
 {
     publicKey = spki;
     return this;
 }
        private static byte[] GetDigest(
            SubjectPublicKeyInfo spki)
        {
            IDigest digest = new Sha1Digest();
            byte[] resBuf = new byte[digest.GetDigestSize()];

            byte[] bytes = spki.PublicKeyData.GetBytes();
            digest.BlockUpdate(bytes, 0, bytes.Length);
            digest.DoFinal(resBuf, 0);
            return resBuf;
        }
 /**
  * Calculates the keyIdentifier using a SHA1 hash over the BIT STRING
  * from SubjectPublicKeyInfo as defined in RFC3280.
  *
  * @param spki the subject public key info.
  */
 public SubjectKeyIdentifier(
     SubjectPublicKeyInfo spki)
 {
     this.keyIdentifier = GetDigest(spki);
 }
 /**
  * Return a RFC 3280 type 1 key identifier. As in:
  * <pre>
  * (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
  * value of the BIT STRING subjectPublicKey (excluding the tag,
  * length, and number of unused bits).
  * </pre>
  * @param keyInfo the key info object containing the subjectPublicKey field.
  * @return the key identifier.
  */
 public static SubjectKeyIdentifier CreateSha1KeyIdentifier(
     SubjectPublicKeyInfo keyInfo)
 {
     return new SubjectKeyIdentifier(keyInfo);
 }
        public Pkcs10CertificationRequest(string signatureAlgorithm, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter signingKey)
        {
            if (signatureAlgorithm == null)
            {
                throw new ArgumentNullException("signatureAlgorithm");
            }
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }
            if (publicKey.IsPrivate)
            {
                throw new ArgumentException("expected public key", "publicKey");
            }
            if (!signingKey.IsPrivate)
            {
                throw new ArgumentException("key for signing must be private", "signingKey");
            }
            string text = Platform.ToUpperInvariant(signatureAlgorithm);
            DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)Pkcs10CertificationRequest.algorithms[text];

            if (derObjectIdentifier == null)
            {
                try
                {
                    derObjectIdentifier = new DerObjectIdentifier(text);
                }
                catch (Exception innerException)
                {
                    throw new ArgumentException("Unknown signature type requested", innerException);
                }
            }
            if (Pkcs10CertificationRequest.noParams.Contains(derObjectIdentifier))
            {
                this.sigAlgId = new AlgorithmIdentifier(derObjectIdentifier);
            }
            else if (Pkcs10CertificationRequest.exParams.Contains(text))
            {
                this.sigAlgId = new AlgorithmIdentifier(derObjectIdentifier, (Asn1Encodable)Pkcs10CertificationRequest.exParams[text]);
            }
            else
            {
                this.sigAlgId = new AlgorithmIdentifier(derObjectIdentifier, DerNull.Instance);
            }
            SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pkInfo, attributes);
            ISigner signer = SignerUtilities.GetSigner(signatureAlgorithm);

            signer.Init(true, signingKey);
            try
            {
                byte[] derEncoded = this.reqInfo.GetDerEncoded();
                signer.BlockUpdate(derEncoded, 0, derEncoded.Length);
            }
            catch (Exception innerException2)
            {
                throw new ArgumentException("exception encoding TBS cert request", innerException2);
            }
            this.sigBits = new DerBitString(signer.GenerateSignature());
        }
        public static AsymmetricKeyParameter CreateKey(
            SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.ObjectID;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption)
                || algOid.Equals(X509ObjectIdentifiers.IdEARsa)
                || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss)
                || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
                    keyInfo.GetPublicKey());

                return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent);
            }
            else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey());

                BigInteger y = dhPublicKey.Y.Value;

                if (IsPkcsDHParam(seq))
                    return ReadPkcsDHParam(algOid, y, seq);

                DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);

                BigInteger p = dhParams.P.Value;
                BigInteger g = dhParams.G.Value;
                BigInteger q = dhParams.Q.Value;

                BigInteger j = null;
                if (dhParams.J != null)
                {
                    j = dhParams.J.Value;
                }

                DHValidationParameters validation = null;
                DHValidationParms dhValidationParms = dhParams.ValidationParms;
                if (dhValidationParms != null)
                {
                    byte[] seed = dhValidationParms.Seed.GetBytes();
                    BigInteger pgenCounter = dhValidationParms.PgenCounter.Value;

                    // TODO Check pgenCounter size?

                    validation = new DHValidationParameters(seed, pgenCounter.IntValue);
                }

                return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
            }
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DerInteger derY = (DerInteger) keyInfo.GetPublicKey();

                return ReadPkcsDHParam(algOid, derY.Value, seq);
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger) keyInfo.GetPublicKey();

                return new ElGamalPublicKeyParameters(
                    derY.Value,
                    new ElGamalParameters(para.P, para.G));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)
                || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger derY = (DerInteger) keyInfo.GetPublicKey();
                Asn1Encodable ae = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return new DsaPublicKeyParameters(derY.Value, parameters);
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
                X9ECPoint derQ = new X9ECPoint(x9.Curve, key);
                ECPoint q = derQ.Point;

                if (para.IsNamedCurve)
                {
                    return new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters);
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return new ECPublicKeyParameters(q, dParams);
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence) algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString) keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = key.GetOctets();
                byte[] x = new byte[32];
                byte[] y = new byte[32];

                for (int i = 0; i != y.Length; i++)
                {
                    x[i] = keyEnc[32 - 1 - i];
                }

                for (int i = 0; i != x.Length; i++)
                {
                    y[i] = keyEnc[64 - 1 - i];
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                    return null;

                ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y));

                return new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet);
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence) algID.Parameters);

                DerOctetString derY;
                try
                {
                    derY = (DerOctetString) keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = derY.GetOctets();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian
                }

                BigInteger y = new BigInteger(1, keyBytes);

                return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet);
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid);
            }
        }
示例#25
0
 public PopoSigningKeyInput(GeneralName sender, SubjectPublicKeyInfo spki)
 {
     this.sender    = sender;
     this.publicKey = spki;
 }
 /// <summary>
 /// Constructor using an encoded subject public key info.
 /// </summary>
 /// <param name="subject">The subject for the certification request.</param>
 /// <param name="encodedPublicKeyInfo">An encoding of the public key to go in the final certificate.</param>
 public Pkcs10CertificationRequestBuilder(X500Name subject, byte[] encodedPublicKeyInfo) : this(subject, SubjectPublicKeyInfo.GetInstance(encodedPublicKeyInfo))
 {
 }
示例#27
0
        /**
         * Read a Key Pair
         */
        private object ReadPrivateKey(PemObject pemObject)
        {
            //
            // extract the key
            //
            Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY"));

            string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();

            byte[] keyBytes = pemObject.Content;

            IDictionary fields = Platform.CreateHashtable();

            foreach (PemHeader header in pemObject.Headers)
            {
                fields[header.Name] = header.Value;
            }

            string procType = (string)fields["Proc-Type"];

            if (procType == "4,ENCRYPTED")
            {
                if (pFinder == null)
                {
                    throw new PasswordException("No password finder specified, but a password is required");
                }

                char[] password = pFinder.GetPassword();

                if (password == null)
                {
                    throw new PasswordException("Password is null, but a password is required");
                }

                string   dekInfo = (string)fields["DEK-Info"];
                string[] tknz    = dekInfo.Split(',');

                string dekAlgName = tknz[0].Trim();
                byte[] iv         = Hex.Decode(tknz[1].Trim());

                keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv);
            }

            try
            {
                AsymmetricKeyParameter pubSpec, privSpec;
                Asn1Sequence           seq = (Asn1Sequence)Asn1Object.FromByteArray(keyBytes);

                switch (type)
                {
                case "RSA":
                {
                    if (seq.Count != 9)
                    {
                        throw new PemException("malformed sequence in RSA private key");
                    }

                    RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);

                    pubSpec  = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
                    privSpec = new RsaPrivateCrtKeyParameters(
                        rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                        rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                        rsa.Coefficient);

                    break;
                }

                case "DSA":
                {
                    if (seq.Count != 6)
                    {
                        throw new PemException("malformed sequence in DSA private key");
                    }

                    // TODO Create an ASN1 object somewhere for this?
                    //DerInteger v = (DerInteger)seq[0];
                    DerInteger p = (DerInteger)seq[1];
                    DerInteger q = (DerInteger)seq[2];
                    DerInteger g = (DerInteger)seq[3];
                    DerInteger y = (DerInteger)seq[4];
                    DerInteger x = (DerInteger)seq[5];

                    DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value);

                    privSpec = new DsaPrivateKeyParameters(x.Value, parameters);
                    pubSpec  = new DsaPublicKeyParameters(y.Value, parameters);

                    break;
                }

                case "EC":
                {
                    ECPrivateKeyStructure pKey  = new ECPrivateKeyStructure(seq);
                    AlgorithmIdentifier   algId = new AlgorithmIdentifier(
                        X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());

                    PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());

                    // TODO Are the keys returned here ECDSA, as Java version forces?
                    privSpec = PrivateKeyFactory.CreateKey(privInfo);

                    DerBitString pubKey = pKey.GetPublicKey();
                    if (pubKey != null)
                    {
                        SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes());

                        // TODO Are the keys returned here ECDSA, as Java version forces?
                        pubSpec = PublicKeyFactory.CreateKey(pubInfo);
                    }
                    else
                    {
                        pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey(
                            (ECPrivateKeyParameters)privSpec);
                    }

                    break;
                }

                case "ENCRYPTED":
                {
                    char[] password = pFinder.GetPassword();

                    if (password == null)
                    {
                        throw new PasswordException("Password is null, but a password is required");
                    }

                    return(PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq)));
                }

                case "":
                {
                    return(PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq)));
                }

                default:
                    throw new ArgumentException("Unknown key type: " + type, "type");
                }

                return(new AsymmetricCipherKeyPair(pubSpec, privSpec));
            }
            catch (IOException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new PemException(
                          "problem creating " + type + " private key: " + e.ToString());
            }
        }
 /// <summary>
 /// Constructor using a subject public key info.
 /// </summary>
 /// <param name="subject">The subject for the certification request.</param>
 /// <param name="publicKeyInfo">The public key to go in the final certificate and be associated with the subject.</param>
 public Pkcs10CertificationRequestBuilder(X500Name subject, SubjectPublicKeyInfo publicKeyInfo)
 {
     this.subject       = subject;
     this.publicKeyInfo = publicKeyInfo;
 }
示例#29
0
        public static AsymmetricKeyParameter CreateKey(SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algId = keyInfo.getAlgorithmId();

            if (algId.getObjectId().Equals(PKCSObjectIdentifiers.rsaEncryption) ||
                algId.getObjectId().Equals(X509ObjectIdentifiers.id_ea_rsa))
            {
                RSAPublicKeyStructure pubKey = new RSAPublicKeyStructure((ASN1Sequence)keyInfo.getPublicKey());

                return(new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent()));
            }
            else if (algId.getObjectId().Equals(PKCSObjectIdentifiers.dhKeyAgreement) ||
                     algId.getObjectId().Equals(X9ObjectIdentifiers.dhpublicnumber))
            {
                DHParameter para = new DHParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger  derY = (DERInteger)keyInfo.getPublicKey();

                return(new DHPublicKeyParameters(derY.getValue(), new DHParameters(para.getP(), para.getG())));
            }
            else if (algId.getObjectId().Equals(OIWObjectIdentifiers.elGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger       derY = (DERInteger)keyInfo.getPublicKey();

                return(new ElGamalPublicKeyParameters(derY.getValue(), new ElGamalParameters(para.getP(), para.getG())));
            }
            else if (algId.getObjectId().Equals(X9ObjectIdentifiers.id_dsa) ||
                     algId.getObjectId().Equals(OIWObjectIdentifiers.dsaWithSHA1))
            {
                DSAParameter para = new DSAParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger   derY = (DERInteger)keyInfo.getPublicKey();

                return(new DSAPublicKeyParameters(derY.getValue(), new DSAParameters(para.getP(), para.getQ(), para.getG())));
            }
            else if (algId.getObjectId().Equals(X9ObjectIdentifiers.id_ecPublicKey))
            {
                X962Parameters     para    = new X962Parameters((ASN1Object)keyInfo.getAlgorithmId().getParameters());
                ECDomainParameters dParams = null;

                if (para.isNamedCurve())
                {
                    DERObjectIdentifier oid = (DERObjectIdentifier)para.getParameters();
                    X9ECParameters      ecP = X962NamedCurves.getByOID(oid);

                    dParams = new ECDomainParameters(
                        ecP.getCurve(),
                        ecP.getG(),
                        ecP.getN(),
                        ecP.getH(),
                        ecP.getSeed());
                }
                else
                {
                    X9ECParameters ecP = new X9ECParameters((ASN1Sequence)para.getParameters().toASN1Object());


                    dParams = new ECDomainParameters(
                        ecP.getCurve(),
                        ecP.getG(),
                        ecP.getN(),
                        ecP.getH(),
                        ecP.getSeed());
                }

                DERBitString    bits = keyInfo.getPublicKeyData();
                byte[]          data = bits.getBytes();
                ASN1OctetString key  = new DEROctetString(data);

                X9ECPoint derQ = new X9ECPoint(dParams.getCurve(), key);

                return(new ECPublicKeyParameters(derQ.getPoint(), dParams));
            }
            else
            {
                throw new Exception("algorithm identifier in key not recognised");
            }
        }
示例#30
0
 public static AsymmetricKeyParameter CreateKey(byte[] keyInfoData)
 {
     return(CreateKey(SubjectPublicKeyInfo.GetInstance(Asn1Object.FromByteArray(keyInfoData))));
 }
示例#31
0
        /// <summary>
        /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
        /// </summary>
        ///<param name="signatureAlgorithm">Name of Sig Alg.</param>
        /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param>
        /// <param name="publicKey">Public Key to be included in cert reqest.</param>
        /// <param name="attributes">ASN1Set of Attributes.</param>
        /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param>
        public Pkcs10CertificationRequest(
            string signatureAlgorithm,
            X509Name subject,
            AsymmetricKeyParameter publicKey,
            Asn1Set attributes,
            AsymmetricKeyParameter signingKey)
        {
            if (signatureAlgorithm == null)
            {
                throw new ArgumentNullException("signatureAlgorithm");
            }
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }
            if (publicKey.IsPrivate)
            {
                throw new ArgumentException("expected public key", "publicKey");
            }
            if (!signingKey.IsPrivate)
            {
                throw new ArgumentException("key for signing must be private", "signingKey");
            }

//			DerObjectIdentifier sigOid = SignerUtilities.GetObjectIdentifier(signatureAlgorithm);
            string algorithmName       = signatureAlgorithm.ToUpperInvariant();
            DerObjectIdentifier sigOid = (DerObjectIdentifier)algorithms[algorithmName];

            if (sigOid == null)
            {
                try
                {
                    sigOid = new DerObjectIdentifier(algorithmName);
                }
                catch (Exception e)
                {
                    throw new ArgumentException("Unknown signature type requested", e);
                }
            }

            if (noParams.Contains(sigOid))
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid);
            }
            else if (exParams.Contains(algorithmName))
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid, (Asn1Encodable)exParams[algorithmName]);
            }
            else
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid, DerNull.Instance);
            }

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);

            ISigner sig = SignerUtilities.GetSigner(signatureAlgorithm);

            sig.Init(true, signingKey);

            try
            {
                // Encode.
                byte[] b = reqInfo.GetDerEncoded();
                sig.BlockUpdate(b, 0, b.Length);
            }
            catch (Exception e)
            {
                throw new ArgumentException("exception encoding TBS cert request", e);
            }

            // Generate Signature.
            sigBits = new DerBitString(sig.GenerateSignature());
        }
示例#32
0
    public static AsymmetricKeyParameter CreateKey(SubjectPublicKeyInfo keyInfo)
    {
        AlgorithmIdentifier algorithmID = keyInfo.AlgorithmID;
        DerObjectIdentifier algorithm   = algorithmID.Algorithm;

        if (algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption) || algorithm.Equals(X509ObjectIdentifiers.IdEARsa) || algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algorithm.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
        {
            RsaPublicKeyStructure instance = RsaPublicKeyStructure.GetInstance(keyInfo.GetPublicKey());
            return(new RsaKeyParameters(isPrivate: false, instance.Modulus, instance.PublicExponent));
        }
        if (algorithm.Equals(X9ObjectIdentifiers.DHPublicNumber))
        {
            Asn1Sequence instance2 = Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object());
            DHPublicKey  instance3 = DHPublicKey.GetInstance(keyInfo.GetPublicKey());
            BigInteger   value     = instance3.Y.Value;
            if (IsPkcsDHParam(instance2))
            {
                return(ReadPkcsDHParam(algorithm, value, instance2));
            }
            DHDomainParameters instance4 = DHDomainParameters.GetInstance(instance2);
            BigInteger         value2    = instance4.P.Value;
            BigInteger         value3    = instance4.G.Value;
            BigInteger         value4    = instance4.Q.Value;
            BigInteger         j         = null;
            if (instance4.J != null)
            {
                j = instance4.J.Value;
            }
            DHValidationParameters validation      = null;
            DHValidationParms      validationParms = instance4.ValidationParms;
            if (validationParms != null)
            {
                byte[]     bytes  = validationParms.Seed.GetBytes();
                BigInteger value5 = validationParms.PgenCounter.Value;
                validation = new DHValidationParameters(bytes, value5.IntValue);
            }
            return(new DHPublicKeyParameters(value, new DHParameters(value2, value3, value4, j, validation)));
        }
        if (algorithm.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
        {
            Asn1Sequence instance5  = Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object());
            DerInteger   derInteger = (DerInteger)keyInfo.GetPublicKey();
            return(ReadPkcsDHParam(algorithm, derInteger.Value, instance5));
        }
        if (algorithm.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
        {
            ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object()));
            DerInteger       derInteger2      = (DerInteger)keyInfo.GetPublicKey();
            return(new ElGamalPublicKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G)));
        }
        if (algorithm.Equals(X9ObjectIdentifiers.IdDsa) || algorithm.Equals(OiwObjectIdentifiers.DsaWithSha1))
        {
            DerInteger    derInteger3 = (DerInteger)keyInfo.GetPublicKey();
            Asn1Encodable parameters  = algorithmID.Parameters;
            DsaParameters parameters2 = null;
            if (parameters != null)
            {
                DsaParameter instance6 = DsaParameter.GetInstance(parameters.ToAsn1Object());
                parameters2 = new DsaParameters(instance6.P, instance6.Q, instance6.G);
            }
            return(new DsaPublicKeyParameters(derInteger3.Value, parameters2));
        }
        if (algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey))
        {
            X962Parameters  x962Parameters = new X962Parameters(algorithmID.Parameters.ToAsn1Object());
            X9ECParameters  x9ECParameters = (!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters);
            Asn1OctetString s         = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
            X9ECPoint       x9ECPoint = new X9ECPoint(x9ECParameters.Curve, s);
            ECPoint         point     = x9ECPoint.Point;
            if (x962Parameters.IsNamedCurve)
            {
                return(new ECPublicKeyParameters("EC", point, (DerObjectIdentifier)x962Parameters.Parameters));
            }
            ECDomainParameters parameters3 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed());
            return(new ECPublicKeyParameters(point, parameters3));
        }
        if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
        {
            Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters((Asn1Sequence)algorithmID.Parameters);
            Asn1OctetString asn1OctetString;
            try
            {
                asn1OctetString = (Asn1OctetString)keyInfo.GetPublicKey();
            }
            catch (IOException)
            {
                throw new ArgumentException("invalid info structure in GOST3410 public key");
            }
            byte[] octets = asn1OctetString.GetOctets();
            byte[] array  = new byte[32];
            byte[] array2 = new byte[32];
            for (int i = 0; i != array2.Length; i++)
            {
                array[i] = octets[31 - i];
            }
            for (int k = 0; k != array.Length; k++)
            {
                array2[k] = octets[63 - k];
            }
            ECDomainParameters byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet);
            if (byOid == null)
            {
                return(null);
            }
            ECPoint q = byOid.Curve.CreatePoint(new BigInteger(1, array), new BigInteger(1, array2));
            return(new ECPublicKeyParameters("ECGOST3410", q, gost3410PublicKeyAlgParameters.PublicKeyParamSet));
        }
        if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x94))
        {
            Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters((Asn1Sequence)algorithmID.Parameters);
            DerOctetString derOctetString;
            try
            {
                derOctetString = (DerOctetString)keyInfo.GetPublicKey();
            }
            catch (IOException)
            {
                throw new ArgumentException("invalid info structure in GOST3410 public key");
            }
            byte[] octets2 = derOctetString.GetOctets();
            byte[] array3  = new byte[octets2.Length];
            for (int l = 0; l != octets2.Length; l++)
            {
                array3[l] = octets2[octets2.Length - 1 - l];
            }
            BigInteger y = new BigInteger(1, array3);
            return(new Gost3410PublicKeyParameters(y, gost3410PublicKeyAlgParameters2.PublicKeyParamSet));
        }
        throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algorithm);
    }
 /// <summary>
 /// Constructor from an algorithm and an encoding of a SubjectPublicKeyInfo object containing an RSA public key.
 /// </summary>
 /// <param name="algorithm">Algorithm marker to associate with the key.</param>
 /// <param name="publicKeyInfoEncoding">An encoding of a SubjectPublicKeyInfo object.</param>
 public AsymmetricRsaPublicKey(Algorithm algorithm, byte[] publicKeyInfoEncoding)
     : this(algorithm, SubjectPublicKeyInfo.GetInstance(publicKeyInfoEncoding))
 {
 }
 public void SetSubjectPublicKeyInfo(
     SubjectPublicKeyInfo pubKeyInfo)
 {
     this.subjectPublicKeyInfo = pubKeyInfo;
 }
        /// <summary>
        /// 从证书中提取公钥并转换为PEM编码
        /// </summary>
        /// <param name="input">证书</param>
        /// <returns>PEM编码公钥</returns>
        public static string ExtractPemPublicKeyFromCert(X509Certificate input)
        {
            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(input.GetPublicKey());

            return(Convert.ToBase64String(subjectPublicKeyInfo.GetDerEncoded()));
        }
 /// <summary>
 /// Create an AuthorityKeyIdentifier from the passed in public key.
 /// </summary>
 /// <param name="publicKey">the public key to base the key identifier on.</param>
 /// <returns>an AuthorityKeyIdentifier.</returns>
 public AuthorityKeyIdentifier CreateAuthorityKeyIdentifier(IAsymmetricPublicKey publicKey)
 {
     return(new AuthorityKeyIdentifier(calculateIdentifier(SubjectPublicKeyInfo.GetInstance(publicKey.GetEncoded()))));
 }
示例#37
0
 public virtual CertTemplateBuilder SetPublicKey(SubjectPublicKeyInfo spki)
 {
     publicKey = spki;
     return(this);
 }
 /// <summary>
 /// Create an AuthorityKeyIdentifier from the passed in SubjectPublicKeyInfo.
 /// </summary>
 /// <param name="publicKeyInfo">the SubjectPublicKeyInfo to base the key identifier on.</param>
 /// <returns>an AuthorityKeyIdentifier.</returns>
 public AuthorityKeyIdentifier CreateAuthorityKeyIdentifier(SubjectPublicKeyInfo publicKeyInfo)
 {
     return(new AuthorityKeyIdentifier(calculateIdentifier(publicKeyInfo)));
 }
示例#39
0
        public static AsymmetricKeyParameter CreateKey(
            SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.Algorithm;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
                    keyInfo.GetPublicKey());

                return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey());

                BigInteger y = dhPublicKey.Y.Value;

                if (IsPkcsDHParam(seq))
                {
                    return(ReadPkcsDHParam(algOid, y, seq));
                }

                DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);

                BigInteger p = dhParams.P.Value;
                BigInteger g = dhParams.G.Value;
                BigInteger q = dhParams.Q.Value;

                BigInteger j = null;
                if (dhParams.J != null)
                {
                    j = dhParams.J.Value;
                }

                DHValidationParameters validation        = null;
                DHValidationParms      dhValidationParms = dhParams.ValidationParms;
                if (dhValidationParms != null)
                {
                    byte[]     seed        = dhValidationParms.Seed.GetBytes();
                    BigInteger pgenCounter = dhValidationParms.PgenCounter.Value;

                    // TODO Check pgenCounter size?

                    validation = new DHValidationParameters(seed, pgenCounter.IntValue);
                }

                return(new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation)));
            }
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(ReadPkcsDHParam(algOid, derY.Value, seq));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(new ElGamalPublicKeyParameters(
                           derY.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) ||
                     algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger    derY = (DerInteger)keyInfo.GetPublicKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPublicKeyParameters(derY.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                Asn1OctetString key  = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
                X9ECPoint       derQ = new X9ECPoint(x9.Curve, key);
                ECPoint         q    = derQ.Point;

                if (para.IsNamedCurve)
                {
                    return(new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPublicKeyParameters(q, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001) || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256) || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = key.GetOctets();
                int    keyLen = keyEnc.Length;
                byte[] x      = new byte[keyLen / 2];
                byte[] y      = new byte[keyLen / 2];

                for (int i = 0; i != y.Length; i++)
                {
                    x[i] = keyEnc[keyLen / 2 - 1 - i];
                }

                for (int i = 0; i != x.Length; i++)
                {
                    y[i] = keyEnc[keyLen - 1 - i];
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    return(null);
                }

                ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y));

                return(new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                DerOctetString derY;
                try
                {
                    derY = (DerOctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc   = derY.GetOctets();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian
                }

                BigInteger y = new BigInteger(1, keyBytes);

                return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X25519))
            {
                return(new X25519PublicKeyParameters(GetRawKey(keyInfo, X25519PublicKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X448))
            {
                return(new X448PublicKeyParameters(GetRawKey(keyInfo, X448PublicKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519))
            {
                return(new Ed25519PublicKeyParameters(GetRawKey(keyInfo, Ed25519PublicKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448))
            {
                return(new Ed448PublicKeyParameters(GetRawKey(keyInfo, Ed448PublicKeyParameters.KeySize), 0));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in public key not recognised: " + algOid);
            }
        }
 /// <summary>
 /// Create an AuthorityKeyIdentifier from the passed in arguments.
 /// </summary>
 /// <param name="publicKeyInfo">the SubjectPublicKeyInfo to base the key identifier on.</param>
 /// <param name="generalNames">the general names to associate with the issuer cert's issuer.</param>
 /// <param name="serial">the serial number of the issuer cert.</param>
 /// <returns>an AuthorityKeyIdentifier.</returns>
 public AuthorityKeyIdentifier CreateAuthorityKeyIdentifier(SubjectPublicKeyInfo publicKeyInfo, GeneralNames generalNames, BigInteger serial)
 {
     return(new AuthorityKeyIdentifier(calculateIdentifier(publicKeyInfo), generalNames, serial));
 }
示例#41
0
 public static AsymmetricKeyParameter CreateKey(Stream inStr) =>
 CreateKey(SubjectPublicKeyInfo.GetInstance(Asn1Object.FromStream(inStr)));
 /// <summary>
 /// Return a RFC 5280 type 1 key identifier. As in: "(1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
 /// value of the BIT STRING subjectPublicKey(excluding the tag, length, and number of unused bits)."
 /// </summary>
 /// <param name="publicKey">the public key to base the identifier on.</param>
 /// <returns>the key identifier.</returns>
 public SubjectKeyIdentifier CreateSubjectKeyIdentifier(IAsymmetricPublicKey publicKey)
 {
     return(CreateSubjectKeyIdentifier(SubjectPublicKeyInfo.GetInstance(publicKey.GetEncoded())));
 }