Beispiel #1
0
        public void Export(Container container, Stream output)
        {
            byte[]     rawCert    = container.GetRawCertificate();
            BigInteger privateKey = container.GetPrivateKey();

            X509Certificate      cert      = new X509CertificateParser().ReadCertificate(rawCert);
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);

            string      friendlyName = "alias";
            Pkcs12Store store        = new Pkcs12Store();

            store.SetCertificateEntry(friendlyName, certEntry);
            //store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { certEntry });

            char[] password = _password.ToCharArray();
            using (MemoryStream ms = new MemoryStream())
            {
                store.Save(ms, password, new SecureRandom());

                // Save дописывает в конец какой-то мусор
                ms.Position = 0;
                Asn1InputStream asn1   = new Asn1InputStream(ms);
                Asn1Object      result = asn1.ReadObject();
                byte[]          buf    = Pkcs12Utilities.ConvertToDefiniteLength(result.GetEncoded(), password);

                output.Write(buf, 0, buf.Length);
            }
        }
        public static void GenKey(out string publicKey, out string privateKey, out string privateKeyPk8)
        {
            publicKey     = string.Empty;
            privateKey    = string.Empty;
            privateKeyPk8 = string.Empty;
            try
            {
                //RSA密钥对的构造器
                RsaKeyPairGenerator r = new RsaKeyPairGenerator();
                //RSA密钥构造器的参数
                RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                    Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                    new SecureRandom(),
                    1024,   //密钥长度
                    25);
                r.Init(param);
                AsymmetricCipherKeyPair keyPair = r.GenerateKeyPair();
                //获取公钥和密钥
                AsymmetricKeyParameter private_key = keyPair.Private;
                AsymmetricKeyParameter public_key  = keyPair.Public;
                if (((RsaKeyParameters)public_key).Modulus.BitLength < 1024)
                {
                    Console.WriteLine("failed key generation (1024) length test");
                }
                using (TextWriter textWriter = new StringWriter())
                {
                    PemWriter pemWriter = new PemWriter(textWriter);
                    pemWriter.WriteObject(keyPair.Private);
                    pemWriter.Writer.Flush();
                    privateKey = textWriter.ToString();
                }
                using (TextWriter textpubWriter = new StringWriter())
                {
                    PemWriter pempubWriter = new PemWriter(textpubWriter);
                    pempubWriter.WriteObject(keyPair.Public);
                    pempubWriter.Writer.Flush();
                    publicKey = textpubWriter.ToString();
                }
                //keyPair = ReadPem(privateKey); // 直接读取字符串生成密码钥
                //public_key = keyPair.Public;//公钥
                //private_key = keyPair.Private;//私钥
                // 前面私钥为pkcs1格式,经过下面处理后,变成pkcs8格式
                SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(public_key);
                PrivateKeyInfo       privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key);
                Asn1Object           asn1ObjectPublic     = subjectPublicKeyInfo.ToAsn1Object();
                byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded();
                Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
                byte[]     privateInfoByte   = asn1ObjectPrivate.GetEncoded();

                var pubkeyb64 = Convert.ToBase64String(publicInfoByte);
                // 这里生成的是Pkcs8的密钥
                privateKeyPk8 = PrivateKeyPk8Format(Convert.ToBase64String(privateInfoByte));

                privateKey = PrivateKeyFormat(privateKey);
                publicKey  = PublicKeyFormat(publicKey);
            }
            catch (Exception ex) {
                throw ex;
            }
        }
Beispiel #3
0
 protected X509Name(Asn1Sequence seq)
 {
     this.seq = seq;
     foreach (Asn1Encodable item in seq)
     {
         Asn1Set instance = Asn1Set.GetInstance(item.ToAsn1Object());
         for (int i = 0; i < instance.Count; i++)
         {
             Asn1Sequence instance2 = Asn1Sequence.GetInstance(instance[i].ToAsn1Object());
             if (instance2.Count != 2)
             {
                 throw new ArgumentException("badly sized pair");
             }
             ordering.Add(DerObjectIdentifier.GetInstance(instance2[0].ToAsn1Object()));
             Asn1Object asn1Object = instance2[1].ToAsn1Object();
             if (asn1Object is IAsn1String && !(asn1Object is DerUniversalString))
             {
                 string text = ((IAsn1String)asn1Object).GetString();
                 if (Platform.StartsWith(text, "#"))
                 {
                     text = "\\" + text;
                 }
                 values.Add(text);
             }
             else
             {
                 values.Add("#" + Hex.ToHexString(asn1Object.GetEncoded()));
             }
             added.Add(i != 0);
         }
     }
 }
        public static byte[] ConvertToDefiniteLength(byte[] berPkcs12File, char[] passwd)
        {
            //IL_00e8: Unknown result type (might be due to invalid IL or missing references)
            Pfx             pfx        = new Pfx(Asn1Sequence.GetInstance(Asn1Object.FromByteArray(berPkcs12File)));
            ContentInfo     authSafe   = pfx.AuthSafe;
            Asn1OctetString instance   = Asn1OctetString.GetInstance(authSafe.Content);
            Asn1Object      asn1Object = Asn1Object.FromByteArray(instance.GetOctets());

            authSafe = new ContentInfo(authSafe.ContentType, new DerOctetString(asn1Object.GetEncoded("DER")));
            MacData macData = pfx.MacData;

            try
            {
                int    intValue             = macData.IterationCount.IntValue;
                byte[] octets               = Asn1OctetString.GetInstance(authSafe.Content).GetOctets();
                byte[] digest               = Pkcs12Store.CalculatePbeMac(macData.Mac.AlgorithmID.Algorithm, macData.GetSalt(), intValue, passwd, wrongPkcs12Zero: false, octets);
                AlgorithmIdentifier algID   = new AlgorithmIdentifier(macData.Mac.AlgorithmID.Algorithm, DerNull.Instance);
                DigestInfo          digInfo = new DigestInfo(algID, digest);
                macData = new MacData(digInfo, macData.GetSalt(), intValue);
            }
            catch (global::System.Exception ex)
            {
                throw new IOException("error constructing MAC: " + ex.ToString());
            }
            pfx = new Pfx(authSafe, macData);
            return(pfx.GetEncoded("DER"));
        }
Beispiel #5
0
        public key GetKey()
        {
            RsaKeyPairGenerator        keyPairGenerator = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters param            = new RsaKeyGenerationParameters(BigInteger.ValueOf(3), new SecureRandom(), 1024, 25);

            keyPairGenerator.Init(param);
            AsymmetricCipherKeyPair keyPair              = keyPairGenerator.GenerateKeyPair();
            AsymmetricKeyParameter  publicKey            = keyPair.Public;
            AsymmetricKeyParameter  privateKey           = keyPair.Private;
            SubjectPublicKeyInfo    subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo          privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded("UTF-8");
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();

            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");

            return(new key()
            {
                publicKey = Convert.ToBase64String(publicInfoByte),
                privateKey = Convert.ToBase64String(privateInfoByte)
            });
        }
Beispiel #6
0
        private void AddCertsFromSet(global::System.Collections.IList certs, Asn1Set certSet)
        {
            X509CertificateParser x509CertificateParser = new X509CertificateParser();

            global::System.Collections.IEnumerator enumerator = certSet.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                    try
                    {
                        Asn1Object asn1Object = asn1Encodable.ToAsn1Object();
                        if (asn1Object is Asn1Sequence)
                        {
                            certs.Add((object)x509CertificateParser.ReadCertificate(asn1Object.GetEncoded()));
                        }
                    }
                    catch (global::System.Exception e)
                    {
                        throw new CmsException("can't re-encode certificate!", e);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Beispiel #7
0
        public RSAKEY GetKey(string s1, string s2)
        {
            //获取公钥和密钥
            AsymmetricKeyParameter publicKey  = GetPublicKeyParameter(s1);
            AsymmetricKeyParameter privateKey = GetPrivateKeyParameter(s2);

            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo       privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);


            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded("UTF-8");
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();

            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");

            RSAKEY item = new RSAKEY()
            {
                PublicKey  = Convert.ToBase64String(publicInfoByte),
                PrivateKey = Convert.ToBase64String(privateInfoByte)
            };

            return(item);
        }
Beispiel #8
0
        public static string RsaSign(string content)
        {
            content = HMACSHA1Encode(content);
            var signer       = SignerUtilities.GetSigner("SHA1withRSA");
            var stringReader = new StringReader(_privateKeyString);
            var pemReader    = new PemReader(stringReader, new PasswordFinder("trdfdsfsd@12311".ToCharArray()));
            var keyPair      = (AsymmetricCipherKeyPair)pemReader.ReadObject();

            AsymmetricKeyParameter publicKey  = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo       privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded();
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();

            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded();

            var privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privateInfoByte);

            signer.Init(true, privateKeyParam);
            var plainBytes = Encoding.UTF8.GetBytes(content);

            signer.BlockUpdate(plainBytes, 0, plainBytes.Length);
            var signBytes = signer.GenerateSignature();

            return(ByteToHexStr(signBytes));
        }
        /// <summary>
        /// 将Pkcs1格式的私转成Pkcs8格式
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string ConvertPriPk1ToPk8(string privateKey)
        {
            AsymmetricCipherKeyPair keyPair = null;

            try
            {
                keyPair = ReadPem(privateKey); // 直接读取字符串生成密码钥
            }
            catch (Exception)
            {
                throw new Exception("密钥格式不正确");
            }
            try
            {
                AsymmetricKeyParameter private_key = keyPair.Private;
                AsymmetricKeyParameter public_key  = keyPair.Public;
                // 前面私钥为pkcs1格式,经过下面处理后,变成pkcs8格式
                SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(public_key);
                PrivateKeyInfo       privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key);
                Asn1Object           asn1ObjectPublic     = subjectPublicKeyInfo.ToAsn1Object();
                byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded();
                Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
                byte[]     privateInfoByte   = asn1ObjectPrivate.GetEncoded();
                var        pubkeyb64         = Convert.ToBase64String(publicInfoByte);
                // 这里生成的是Pkcs8的密钥
                return(PrivateKeyFormat(Convert.ToBase64String(privateInfoByte)));
            }
            catch (Exception)
            {
                throw new Exception("转换失败");
            }
        }
Beispiel #10
0
        public static RSAKEY GenerateRSAKey()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(0x3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,  //密钥长度
                25);

            //用参数初始化密钥构造器
            keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和密钥
            AsymmetricKeyParameter publicKey            = keyPair.Public;
            AsymmetricKeyParameter privateKey           = keyPair.Private;
            SubjectPublicKeyInfo   subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo         privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded("UTF-8");
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();

            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");
            RSAKEY item            = new RSAKEY()
            {
                PublicKey  = Convert.ToBase64String(publicInfoByte),
                PrivateKey = Convert.ToBase64String(privateInfoByte)
            };

            return(item);
        }
Beispiel #11
0
        private void TbsV3CertGenerate()
        {
            V3TbsCertificateGenerator gen = new V3TbsCertificateGenerator();
            DateTime startDate            = MakeUtcDateTime(1970, 1, 1, 0, 0, 1);
            DateTime endDate = MakeUtcDateTime(1970, 1, 1, 0, 0, 2);

            gen.SetSerialNumber(new DerInteger(2));

            gen.SetStartDate(new Time(startDate));
            gen.SetEndDate(new Time(endDate));

            gen.SetIssuer(new X509Name("CN=AU,O=Bouncy Castle"));
            gen.SetSubject(new X509Name("CN=AU,O=Bouncy Castle,OU=Test 2"));

            gen.SetSignature(new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5WithRsaEncryption, DerNull.Instance));

            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                new AlgorithmIdentifier(
                    OiwObjectIdentifiers.ElGamalAlgorithm,
                    new ElGamalParameter(BigInteger.One, BigInteger.Two)),
                new DerInteger(3));

            gen.SetSubjectPublicKeyInfo(info);

            //
            // add extensions
            //
            IList       order      = new ArrayList();
            IDictionary extensions = new Hashtable();

            order.Add(X509Extensions.AuthorityKeyIdentifier);
            order.Add(X509Extensions.SubjectKeyIdentifier);
            order.Add(X509Extensions.KeyUsage);

            extensions.Add(X509Extensions.AuthorityKeyIdentifier, new X509Extension(true, new DerOctetString(CreateAuthorityKeyId(info, new X509Name("CN=AU,O=Bouncy Castle,OU=Test 2"), 2))));
            extensions.Add(X509Extensions.SubjectKeyIdentifier, new X509Extension(true, new DerOctetString(new SubjectKeyIdentifier(info))));
            extensions.Add(X509Extensions.KeyUsage, new X509Extension(false, new DerOctetString(new KeyUsage(KeyUsage.DataEncipherment))));

            X509Extensions ex = new X509Extensions(order, extensions);

            gen.SetExtensions(ex);

            TbsCertificateStructure tbs = gen.GenerateTbsCertificate();

            if (!Arrays.AreEqual(tbs.GetEncoded(), v3Cert))
            {
                Fail("failed v3 cert generation");
            }

            //
            // read back test
            //
            Asn1Object o = Asn1Object.FromByteArray(v3Cert);

            if (!Arrays.AreEqual(o.GetEncoded(), v3Cert))
            {
                Fail("failed v3 cert read back test");
            }
        }
Beispiel #12
0
        /// <summary>
        /// 获取一个密钥对,其中私钥是DES加密后的
        /// </summary>
        /// <param name="userPassword"></param>
        /// <returns></returns>
        public static bool CreateRSAKeypair(string pwd, ref KeyPair resultKeypair)
        {
            _error = "";
            try
            {
                resultKeypair = new KeyPair {
                    publicKey = "", privateKey = ""
                };
                //RSA密钥对的构造器
                RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();

                //RSA密钥构造器的参数
                RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                    Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                    new Org.BouncyCastle.Security.SecureRandom(),
                    1024,   //密钥长度
                    25);

                //用参数初始化密钥构造器
                keyGenerator.Init(param);

                //产生密钥对
                AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
                if (((RsaKeyParameters)keyPair.Public).Modulus.BitLength < 1024)
                {
                    _error = "密钥生成失败,长度不足1024字节。";
                    return(false);
                }

                //获取公钥和密钥
                SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
                Asn1Object           asn1ObjectPublic     = subjectPublicKeyInfo.ToAsn1Object();
                byte[] pbkByte = asn1ObjectPublic.GetEncoded();
                resultKeypair.publicKey = Convert.ToBase64String(pbkByte);


                string alg      = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1
                byte[] salt     = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
                int    count    = 1000;
                char[] password = pwd.ToCharArray();
                EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                    alg,
                    password,
                    salt,
                    count,
                    keyPair.Private);

                byte[] prkByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
                resultKeypair.privateKey = Convert.ToBase64String(prkByte);

                return(true);
            }
            catch (Exception ex)
            {
                _error = ex.Message;
                return(false);
            }
        }
Beispiel #13
0
        /**
         * write out an RSA private key with its associated information
         * as described in Pkcs8.
         * <pre>
         *      PrivateKeyInfo ::= Sequence {
         *                              version Version,
         *                              privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
         *                              privateKey PrivateKey,
         *                              attributes [0] IMPLICIT Attributes OPTIONAL
         *                          }
         *      Version ::= Integer {v1(0)} (v1,...)
         *
         *      PrivateKey ::= OCTET STRING
         *
         *      Attributes ::= Set OF Attr
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(
                new DerInteger(0),
                algID,
                new DerOctetString(privKey.GetEncoded()));

            return(new DerSequence(v));
        }
Beispiel #14
0
 public PrivateKeyInfo(
     AlgorithmIdentifier algID,
     Asn1Object privateKey,
     Asn1Set attributes)
 {
     this.algID      = algID;
     this.privKey    = new DerOctetString(privateKey.GetEncoded(Asn1Encodable.Der));
     this.attributes = attributes;
 }
Beispiel #15
0
        public static string SavePublicKey(AsymmetricKeyParameter publicKey)
        {
            //保存公钥到文件
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            Asn1Object           aobject       = publicKeyInfo.ToAsn1Object();

            byte[] pubInfoByte = aobject.GetEncoded();
            return(Convert.ToBase64String(pubInfoByte));
        }
 public PrivateKeyInfo(
     AlgorithmIdentifier	algID,
     Asn1Object			privateKey,
     Asn1Set				attributes)
 {
     this.algID = algID;
     this.privKey = new DerOctetString(privateKey.GetEncoded(Asn1Encodable.Der));
     this.attributes = attributes;
 }
Beispiel #17
0
        private void TbsV2CertListGenerate()
        {
            V2TbsCertListGenerator gen = new V2TbsCertListGenerator();

            gen.SetIssuer(new X509Name("CN=AU,O=Bouncy Castle"));

            gen.AddCrlEntry(new DerInteger(1), new Time(MakeUtcDateTime(1970, 1, 1, 0, 0, 1)), ReasonFlags.AACompromise);

            gen.SetNextUpdate(new Time(MakeUtcDateTime(1970, 1, 1, 0, 0, 2)));

            gen.SetThisUpdate(new Time(MakeUtcDateTime(1970, 1, 1, 0, 0, 0, 500)));

            gen.SetSignature(new AlgorithmIdentifier(PkcsObjectIdentifiers.Sha1WithRsaEncryption, DerNull.Instance));

            //
            // extensions
            //
            IList                order      = new ArrayList();
            IDictionary          extensions = new Hashtable();
            SubjectPublicKeyInfo info       = new SubjectPublicKeyInfo(
                new AlgorithmIdentifier(
                    OiwObjectIdentifiers.ElGamalAlgorithm,
                    new ElGamalParameter(BigInteger.One, BigInteger.Two)),
                new DerInteger(3));

            order.Add(X509Extensions.AuthorityKeyIdentifier);
            order.Add(X509Extensions.IssuerAlternativeName);
            order.Add(X509Extensions.CrlNumber);
            order.Add(X509Extensions.IssuingDistributionPoint);

            extensions.Add(X509Extensions.AuthorityKeyIdentifier, new X509Extension(true, new DerOctetString(CreateAuthorityKeyId(info, new X509Name("CN=AU,O=Bouncy Castle,OU=Test 2"), 2))));
            extensions.Add(X509Extensions.IssuerAlternativeName, new X509Extension(false, new DerOctetString(GeneralNames.GetInstance(new DerSequence(new GeneralName(new X509Name("CN=AU,O=Bouncy Castle,OU=Test 3")))))));
            extensions.Add(X509Extensions.CrlNumber, new X509Extension(false, new DerOctetString(new DerInteger(1))));
            extensions.Add(X509Extensions.IssuingDistributionPoint, new X509Extension(true, new DerOctetString(IssuingDistributionPoint.GetInstance(DerSequence.Empty))));

            X509Extensions ex = new X509Extensions(order, extensions);

            gen.SetExtensions(ex);

            TbsCertificateList tbs = gen.GenerateTbsCertList();

            if (!Arrays.AreEqual(tbs.GetEncoded(), v2CertList))
            {
                Fail("failed v2 cert list generation");
            }

            //
            // read back test
            //
            Asn1InputStream aIn = new Asn1InputStream(v2CertList);
            Asn1Object      o   = aIn.ReadObject();

            if (!Arrays.AreEqual(o.GetEncoded(), v2CertList))
            {
                Fail("failed v2 cert list read back test");
            }
        }
Beispiel #18
0
 static byte[] toByteArray(Asn1Object primitive)
 {
     try
     {
         return(primitive.GetEncoded());
     }
     catch (IOException e)
     {
         throw new InvalidOperationException("Cannot get encoding: " + e.Message, e);
     }
 }
Beispiel #19
0
        public static Asn1Object ReadDerObject(byte[] encoding)
        {
            /*
             * NOTE: The current ASN.1 parsing code can't enforce DER-only parsing, but since DER is
             * canonical, we can check it by re-encoding the result and comparing to the original.
             */
            Asn1Object result = ReadAsn1Object(encoding);

            byte[] check = result.GetEncoded(Asn1Encodable.Der);
            if (!Arrays.AreEqual(check, encoding))
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }
            return(result);
        }
Beispiel #20
0
        protected X509Name(Asn1Sequence seq)
        {
            this.ordering = Platform.CreateArrayList();
            this.values   = Platform.CreateArrayList();
            this.added    = Platform.CreateArrayList();
            this.seq      = seq;
            IEnumerator enumerator = seq.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    Asn1Set instance = Asn1Set.GetInstance(((Asn1Encodable)enumerator.Current).ToAsn1Object());
                    for (int i = 0; i < instance.Count; i++)
                    {
                        Asn1Sequence sequence = Asn1Sequence.GetInstance(instance[i].ToAsn1Object());
                        if (sequence.Count != 2)
                        {
                            throw new ArgumentException("badly sized pair");
                        }
                        this.ordering.Add(DerObjectIdentifier.GetInstance(sequence[0].ToAsn1Object()));
                        Asn1Object obj2 = sequence[1].ToAsn1Object();
                        if ((obj2 is IAsn1String) && !(obj2 is DerUniversalString))
                        {
                            string source = ((IAsn1String)obj2).GetString();
                            if (Platform.StartsWith(source, "#"))
                            {
                                source = @"\" + source;
                            }
                            this.values.Add(source);
                        }
                        else
                        {
                            this.values.Add("#" + Hex.ToHexString(obj2.GetEncoded()));
                        }
                        this.added.Add(i != 0);
                    }
                }
            }
            finally
            {
                if (enumerator is IDisposable disposable)
                {
                    IDisposable disposable;
                    disposable.Dispose();
                }
            }
        }
        static PdfName getSignatureHashKey(PdfDictionary dic, bool encrypted)
        {
            PdfString contents = dic.GetAsString(PdfName.CONTENTS);

            byte[] bc = contents.GetOriginalBytes();
            if (PdfName.ETSI_RFC3161.Equals(PdfReader.GetPdfObject(dic.Get(PdfName.SUBFILTER))))
            {
                using (Asn1InputStream din = new Asn1InputStream(bc))
                {
                    Asn1Object pkcs = din.ReadObject();
                    bc = pkcs.GetEncoded();
                }
            }
            byte[] bt = hashBytesSha1(bc);
            return(new PdfName(Utilities.ConvertToHex(bt)));
        }
Beispiel #22
0
        private PdfName GetSignatureHashKey(String signatureName)
        {
            PdfDictionary dic      = acroFields.GetSignatureDictionary(signatureName);
            PdfString     contents = dic.GetAsString(PdfName.CONTENTS);

            byte[] bc = contents.GetOriginalBytes();
            byte[] bt = null;
            if (PdfName.ETSI_RFC3161.Equals(dic.GetAsName(PdfName.SUBFILTER)))
            {
                Asn1InputStream din  = new Asn1InputStream(new MemoryStream(bc));
                Asn1Object      pkcs = din.ReadObject();
                bc = pkcs.GetEncoded();
            }
            bt = HashBytesSha1(bc);
            return(new PdfName(Utilities.ConvertToHex(bt)));
        }
        /// <exception cref="Org.BouncyCastle.Security.SecurityUtilityException"/>
        /// <exception cref="System.IO.IOException"/>
        private PdfName GetSignatureHashKey(String signatureName)
        {
            PdfSignature sig      = sgnUtil.GetSignature(signatureName);
            PdfString    contents = sig.GetContents();

            byte[] bc = PdfEncodings.ConvertToBytes(contents.GetValue(), null);
            byte[] bt = null;
            if (PdfName.ETSI_RFC3161.Equals(sig.GetSubFilter()))
            {
                Asn1InputStream din  = new Asn1InputStream(new MemoryStream(bc));
                Asn1Object      pkcs = din.ReadObject();
                bc = pkcs.GetEncoded();
            }
            bt = HashBytesSha1(bc);
            return(new PdfName(ConvertToHex(bt)));
        }
Beispiel #24
0
 protected X509Name(Asn1Sequence seq)
 {
     //IL_007b: Unknown result type (might be due to invalid IL or missing references)
     this.seq = seq;
     global::System.Collections.IEnumerator enumerator = seq.GetEnumerator();
     try
     {
         while (enumerator.MoveNext())
         {
             Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator.get_Current();
             Asn1Set       instance      = Asn1Set.GetInstance(asn1Encodable.ToAsn1Object());
             for (int i = 0; i < instance.Count; i++)
             {
                 Asn1Sequence instance2 = Asn1Sequence.GetInstance(instance[i].ToAsn1Object());
                 if (instance2.Count != 2)
                 {
                     throw new ArgumentException("badly sized pair");
                 }
                 ordering.Add((object)DerObjectIdentifier.GetInstance(instance2[0].ToAsn1Object()));
                 Asn1Object asn1Object = instance2[1].ToAsn1Object();
                 if (asn1Object is IAsn1String && !(asn1Object is DerUniversalString))
                 {
                     string text = ((IAsn1String)asn1Object).GetString();
                     if (Platform.StartsWith(text, "#"))
                     {
                         text = "\\" + text;
                     }
                     values.Add((object)text);
                 }
                 else
                 {
                     values.Add((object)("#" + Hex.ToHexString(asn1Object.GetEncoded())));
                 }
                 added.Add((object)(i != 0));
             }
         }
     }
     finally
     {
         global::System.IDisposable disposable = enumerator as global::System.IDisposable;
         if (disposable != null)
         {
             disposable.Dispose();
         }
     }
 }
Beispiel #25
0
        /// <summary>
        /// 生成密钥对,正式使用时只需要调用一次,生成的密钥对需要保存,每次生成都不一样
        /// </summary>
        public static MapKeys CreateKey()
        {
            MapKeys mapkeys = new MapKeys();
            //生成密钥对
            RsaKeyPairGenerator        rsaKeyPairGenerator        = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters rsaKeyGenerationParameters = new RsaKeyGenerationParameters(BigInteger.ValueOf(3), new Org.BouncyCastle.Security.SecureRandom(), 1024, 25);

            rsaKeyPairGenerator.Init(rsaKeyGenerationParameters); //初始化参数
            AsymmetricCipherKeyPair keyPair    = rsaKeyPairGenerator.GenerateKeyPair();
            AsymmetricKeyParameter  publicKey  = keyPair.Public;  //公钥
            AsymmetricKeyParameter  privateKey = keyPair.Private; //私钥

            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo       privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            //生成byte密钥数据
            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded();
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();

            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded();

            //16进制密钥对
            string HexPublicKey  = StringHelper.ByteToHex(publicInfoByte);
            string HexPrivateKey = StringHelper.ByteToHex(privateInfoByte);

            mapkeys.HexPublicKey  = HexPublicKey;
            mapkeys.HexPrivateKey = HexPrivateKey;

            //Base64密钥对
            string Base64PublicKey  = StringHelper.HexToBase64String(HexPublicKey);
            string Base64PrivateKey = StringHelper.HexToBase64String(HexPrivateKey);

            mapkeys.Base64PublicKey  = Base64PublicKey;
            mapkeys.Base64PrivateKey = Base64PrivateKey;

            //Xml密钥对
            mapkeys.XmlPublicKey  = RSAPublicKeyJava2DotNet(Base64PublicKey);
            mapkeys.XmlPrivateKey = RSAPrivateKeyJava2DotNet(Base64PrivateKey);

            return(mapkeys);
        }
Beispiel #26
0
        /// <summary>
        /// save public key
        /// </summary>
        /// <param name="publicKey">public key</param>
        /// <param name="pkUrl">key file</param>
        /// <returns></returns>
        public static bool SavePubKey(AsymmetricKeyParameter publicKey, string pkUrl)
        {
            try
            {
                //save public key
                SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

                Asn1Object aobject     = publicKeyInfo.ToAsn1Object();
                byte[]     pubInfoByte = aobject.GetEncoded();
                FileStream fs          = new FileStream(pkUrl, FileMode.Create, FileAccess.Write);
                fs.Write(pubInfoByte, 0, pubInfoByte.Length);
                fs.Close();
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        private static void savetheKey(AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey)
        {
            //保存公钥到文件
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            Asn1Object           aobject       = publicKeyInfo.ToAsn1Object();

            byte[]     pubInfoByte = aobject.GetEncoded();
            FileStream fs          = new FileStream(pubKeyFile, FileMode.Create, FileAccess.Write);

            fs.Write(pubInfoByte, 0, pubInfoByte.Length);
            fs.Close();
            //保存私钥到文件

            /*
             * PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
             * aobject = privateKeyInfo.ToAsn1Object();
             * byte[] priInfoByte = aobject.GetEncoded();
             * fs = new FileStream(@"E:/Desktop/a.pri", FileMode.Create, FileAccess.Write);
             * fs.Write(priInfoByte, 0, priInfoByte.Length);
             * fs.Close();
             */
            string alg = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1

            byte[] salt  = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int    count = 1000;

            char[] password = "******".ToCharArray();
            EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg,
                password,
                salt,
                count,
                privateKey);

            byte[] priInfoByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
            fs = new FileStream(priKeyFile, FileMode.Create, FileAccess.Write);
            fs.Write(priInfoByte, 0, priInfoByte.Length);
            fs.Close();
            //还原
            //PrivateKeyInfo priInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enPrivateKeyInfo);
            //AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(priInfoByte);
        }
Beispiel #28
0
        public static SecurityKeyPair Generate()
        {
            RsaKeyPairGenerator generator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度
                25);

            //用参数初始化密钥构造器
            generator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();
            //获取公钥和密钥
            AsymmetricKeyParameter publicKey  = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024)
            {
                Console.WriteLine("failed key generation (1024) length test");
            }

            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo       privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded();
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();

            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded();

            //这里可以将密钥对保存到本地
            Console.WriteLine("PublicKey:\n" + Convert.ToBase64String(publicInfoByte));
            Console.WriteLine("PrivateKey:\n" + Convert.ToBase64String(privateInfoByte));

            return(new SecurityKeyPair {
                RSAPublicKeyJava = Convert.ToBase64String(publicInfoByte),
                RSAPrivateKeyJava = Convert.ToBase64String(privateInfoByte)
            });
        }
Beispiel #29
0
        private void AddCertsFromSet(IList certs, Asn1Set certSet)
        {
            X509CertificateParser x509CertificateParser = new X509CertificateParser();

            foreach (Asn1Encodable asn1Encodable in certSet)
            {
                try
                {
                    Asn1Object asn1Object = asn1Encodable.ToAsn1Object();
                    if (asn1Object is Asn1Sequence)
                    {
                        certs.Add(x509CertificateParser.ReadCertificate(asn1Object.GetEncoded()));
                    }
                }
                catch (Exception e)
                {
                    throw new CmsException("can't re-encode certificate!", e);
                }
            }
        }
Beispiel #30
0
        public void RsaKeysGenerate(string PrivateKeyFilename, string PublicKeyFilename, string passw)
        {
            RsaKeyPairGenerator        keyGenerator = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters param        = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 1024, 25);

            keyGenerator.Init(param);
            AsymmetricCipherKeyPair keyPair       = keyGenerator.GenerateKeyPair();
            AsymmetricKeyParameter  publicKey     = keyPair.Public;
            AsymmetricKeyParameter  privateKey    = keyPair.Private;
            SubjectPublicKeyInfo    publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            Asn1Object aobject = publicKeyInfo.ToAsn1Object();

            byte[] pubInfoByte      = aobject.GetEncoded();
            System.IO.FileStream fs = new System.IO.FileStream(PublicKeyFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            fs.Write(pubInfoByte, 0, pubInfoByte.Length);
            fs.Close();
            string alg = "1.2.840.113549.1.12.1.3";

            byte[] salt = new byte[]
            {
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                10
            };
            int count = 1000;

            char[] password = passw.ToCharArray();
            EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(alg, password, salt, count, privateKey);

            byte[] priInfoByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
            fs = new System.IO.FileStream(PrivateKeyFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            fs.Write(priInfoByte, 0, priInfoByte.Length);
            fs.Close();
        }
Beispiel #31
0
        /**
         * Constructor from Asn1Sequence
         *
         * the principal will be a list of constructed sets, each containing an (OID, string) pair.
         */
        protected X509Name(
            Asn1Sequence seq)
        {
            this.seq = seq;

            foreach (Asn1Encodable asn1Obj in seq)
            {
                Asn1Set asn1Set = Asn1Set.GetInstance(asn1Obj.ToAsn1Object());

                for (int i = 0; i < asn1Set.Count; i++)
                {
                    Asn1Sequence s = Asn1Sequence.GetInstance(asn1Set[i].ToAsn1Object());

                    if (s.Count != 2)
                    {
                        throw new ArgumentException("badly sized pair");
                    }

                    ordering.Add(DerObjectIdentifier.GetInstance(s[0].ToAsn1Object()));

                    Asn1Object derValue = s[1].ToAsn1Object();
                    if (derValue is IAsn1String && !(derValue is DerUniversalString))
                    {
                        string v = ((IAsn1String)derValue).GetString();
                        if (v.StartsWith("#"))
                        {
                            v = "\\" + v;
                        }

                        values.Add(v);
                    }
                    else
                    {
                        byte[] hex = Hex.Encode(derValue.GetEncoded());
                        values.Add("#" + Encoding.ASCII.GetString(hex, 0, hex.Length));
                    }

                    added.Add(i != 0);
                }
            }
        }