예제 #1
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);
        }
예제 #2
0
파일: SafeUtil.cs 프로젝트: cjf8134/demo
        public static string RSAPrivateKeyDotNet2Java(string privateKey)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(privateKey);

            BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));

            BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));

            BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));

            BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));

            BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));

            BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));

            BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));

            BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));


            RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);


            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);


            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();

            return(Convert.ToBase64String(serializedPrivateBytes));
        }
예제 #3
0
 public virtual void WritePem(PrivateKeyInfo privateKeyInfo, string filename = "id_econfig.pem")
 {
     using (var writer = new StreamWriter(filename))
     {
         new PemWriter(writer).WriteObject(new PemObject("RSA PRIVATE KEY", privateKeyInfo.ToAsn1Object().GetDerEncoded()));
     }
 }
예제 #4
0
        /// <summary>
        /// 获取RSA私钥
        /// </summary>
        /// <param name="p12CertData">P12/PFX证书</param>
        /// <param name="certPwdData">证书密码</param>
        /// <returns></returns>
        public static byte[] GetPrivateKeyFromPcks12(byte[] p12CertData, char[] certPwdData)
        {
            var            privateKeyParam = GetFromPcks12(p12CertData, certPwdData, (store, keyAlias) => store.GetKey(keyAlias).Key);
            PrivateKeyInfo privateKeyInfo  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);

            return(privateKeyInfo.ToAsn1Object().GetEncoded());
        }
예제 #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)
            });
        }
예제 #6
0
파일: RSA.cs 프로젝트: flyapy/Practices
        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);
        }
예제 #7
0
        private static byte[] CreatePfxFile(Org.BouncyCastle.X509.X509Certificate certificate, AsymmetricKeyParameter privateKey, string password = null)
        {
            // create certificate entry
            var    certEntry    = new X509CertificateEntry(certificate);
            string friendlyName = certificate.SubjectDN.ToString();

            // get bytes of private key.
            PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            byte[] keyBytes = keyInfo.ToAsn1Object().GetEncoded();

            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var store = builder.Build();

            // create store entry
            store.SetKeyEntry("", new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { certEntry });
            byte[] pfxBytes = null;
            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, password?.ToCharArray(), new SecureRandom());
                pfxBytes = stream.ToArray();
            }
            var result = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes);

            return(result);
        }
예제 #8
0
        /// <summary>
        /// RSA私钥格式转换 .net->Java
        /// </summary>
        /// <param name="privateKey">.net生成的私钥</param>
        /// <returns>JAVA用的私钥</returns>
        public static string ConvertRSAPrivateKey_DotNet2Java(string strPrivateDotnetRSAKey)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(strPrivateDotnetRSAKey);

                BigInteger m    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
                BigInteger exp  = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
                BigInteger d    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
                BigInteger p    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
                BigInteger q    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
                BigInteger dp   = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
                BigInteger dq   = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
                BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
                RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
                PrivateKeyInfo             privateKeyInfo  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
                byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
                return(Convert.ToBase64String(serializedPrivateBytes));
            }
            catch (Exception e)
            {
                Console.WriteLine($"[Error] Convert RSA private key (DotNet to Java) failed. Error = {e.ToString()}");
                return(string.Empty);
            }
        }
예제 #9
0
        /// <summary>
        /// 加载Pkcs1格式的私钥
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static AsymmetricKeyParameter loadPrivateKeyPk1(string privateKey)
        {
            AsymmetricCipherKeyPair keyPair = null;

            try
            {
                keyPair = ReadPem(privateKey); // 直接读取字符串生成密码钥
            }
            catch (Exception)
            {
                throw new Exception("密钥格式不正确");
            }
            try
            {
                AsymmetricKeyParameter private_key = keyPair.Private;
                // 前面私钥为pkcs1格式,经过下面处理后,变成pkcs8格式
                PrivateKeyInfo         privateKeyInfo    = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key);
                Asn1Object             asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
                AsymmetricKeyParameter priKey            = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(asn1ObjectPrivate));
                return(priKey);
            }
            catch (Exception)
            {
                throw new Exception("加载失败");
            }
        }
예제 #10
0
        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;
            }
        }
예제 #11
0
        /// <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("转换失败");
            }
        }
예제 #12
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));
        }
예제 #13
0
        public static string RSAPrivateKeyDotNet2Java(string privateKey, string keyFileName)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(privateKey);
            BigInteger m    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger exp  = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            BigInteger d    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
            BigInteger p    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
            BigInteger q    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
            BigInteger dp   = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
            BigInteger dq   = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
            BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
            RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
            PrivateKeyInfo             privateKeyInfo  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);

            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();

            if (!string.IsNullOrEmpty(keyFileName))
            {
                using (StreamWriter writer = new StreamWriter(string.Format("{0}.txt", keyFileName)))
                {
                    writer.Write(Convert.ToBase64String(serializedPrivateBytes));
                }
            }

            return(Convert.ToBase64String(serializedPrivateBytes));
        }
예제 #14
0
        public static byte[] GetSerializedPrivateKey(AsymmetricKeyParameter keyPair)
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair);

            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
            return(serializedPrivateBytes);
        }
예제 #15
0
        public static Models.KeyPair GenerateKeyPair()
        {
            RsaKeyPairGenerator _RSAKeyPairGnr = new RsaKeyPairGenerator();

            _RSAKeyPairGnr.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            AsymmetricCipherKeyPair _KeyPair = _RSAKeyPairGnr.GenerateKeyPair();

            PrivateKeyInfo _PrivateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(_KeyPair.Private);

            Byte[] _SerializedPrivateBytes = _PrivateKeyInfo.ToAsn1Object().GetDerEncoded();
            String _SerializedPrivate      = Convert.ToBase64String(_SerializedPrivateBytes);

            SubjectPublicKeyInfo _PublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_KeyPair.Public);

            Byte[] _SerializedPublicBytes = _PublicKeyInfo.ToAsn1Object().GetDerEncoded();
            String _SerializedPublic      = Convert.ToBase64String(_SerializedPublicBytes);

            if (Db.DbContextManager._Db.Accounts.Any(x => x.PublicKey == _SerializedPublic))
            {
                return(GenerateKeyPair());
            }

            Models.KeyPair _KP = new Models.KeyPair
            {
                PriveteKey = _SerializedPrivate,
                PublicKey  = _SerializedPublic
            };
            return(_KP);
        }
예제 #16
0
        public static string GetPrivateKeyBase64(AsymmetricKeyParameter key)
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key);

            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();

            return(Convert.ToBase64String(serializedPrivateBytes));
        }
예제 #17
0
파일: RasHelper.cs 프로젝트: SHNXJMG/Small
        /// <summary>
        /// 从 .Net RSA 算法私钥参数转换为 Java 格式的 RSA 私钥
        /// </summary>
        /// <param name="privateKey">.Net生成的私钥参数</param>
        /// <returns></returns>
        public static string ToJavaPrivateKey(this RSAParameters privateKey)
        {
            AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(privateKey);
            PrivateKeyInfo          info    = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);

            byte[] bytes = info.ToAsn1Object().GetEncoded();
            return(ToBase64(bytes));
        }
예제 #18
0
        internal static byte[] ToBytes(this RsaKeyParameters pubKey)
        {
            RsaPublicKeyStructure keyStruct = new RsaPublicKeyStructure(
                pubKey.Modulus,
                pubKey.Exponent);
            var privInfo = new PrivateKeyInfo(AlgID, keyStruct.ToAsn1Object());

            return(privInfo.ToAsn1Object().GetEncoded());
        }
예제 #19
0
        public static string SerializePrivateKey(this AsymmetricKeyParameter privateKey, bool encodeInHex = encodeInHexValue)
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
            string serializedPrivate      = encodeInHex ? serializedPrivateBytes.ToHex() : Convert.ToBase64String(serializedPrivateBytes);

            return(serializedPrivate);
        }
예제 #20
0
        public byte[] ToBytes()
        {
            RsaPublicKeyStructure keyStruct = new RsaPublicKeyStructure(
                _Key.Modulus,
                _Key.Exponent);
            var privInfo = new PrivateKeyInfo(RsaKey.algID, keyStruct.ToAsn1Object());

            return(privInfo.ToAsn1Object().GetEncoded());
        }
예제 #21
0
        public static string GetSerializedPrivateKey(RsaKeyParameters privateKey)
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
            string serializedPrivate      = Convert.ToBase64String(serializedPrivateBytes);

            return(serializedPrivate);
        }
        /// <summary>
        /// Genera el archivo pfx y devuelve el resultado con su contraseña
        /// </summary>
        /// <param name="rutaArchivoCer"></param>
        /// <param name="rutaArchivoKey"></param>
        /// <param name="secretArchivoKey"></param>
        /// <param name="rutaGuardado"></param>
        /// <param name="nombreArchivoPfx"></param>
        /// <param name="secretArchivoPfx"></param>
        /// <param name="conservarArchivo"></param>
        /// <returns>Pfx</returns>
        public static CfdiPfx generarArchivoPfx(string rutaArchivoCer, string rutaArchivoKey, string secretArchivoKey, string rutaGuardado, string nombreArchivoPfx, string secretArchivoPfx, Boolean conservarArchivo)
        {
            try
            {
                string rutaArchivoPfx = Path.Combine(rutaGuardado, nombreArchivoPfx);

                if (!Directory.Exists(rutaGuardado))
                {
                    Directory.CreateDirectory(rutaGuardado);
                }

                if (File.Exists(rutaArchivoPfx))
                {
                    File.Delete(rutaArchivoPfx);
                }

                X509Certificate2 certificado = new X509Certificate2(rutaArchivoCer);
                Org.BouncyCastle.X509.X509Certificate certificate = DotNetUtilities.FromX509Certificate(certificado);

                byte[] bytesArchivoKey            = File.ReadAllBytes(rutaArchivoKey);
                AsymmetricKeyParameter privateKey = PrivateKeyFactory.DecryptKey(secretArchivoKey.ToCharArray(), bytesArchivoKey);

                var    certEntry    = new X509CertificateEntry(certificate);
                string friendlyName = certificate.SubjectDN.ToString();

                PrivateKeyInfo keyInfo  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
                byte[]         keyBytes = keyInfo.ToAsn1Object().GetEncoded();

                var builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                var store = builder.Build();

                store.SetKeyEntry("PrivateKeyAlias", new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { certEntry });

                byte[] pfxBytes = null;

                using (MemoryStream stream = new MemoryStream())
                {
                    store.Save(stream, secretArchivoPfx.ToCharArray(), new SecureRandom());
                    pfxBytes = stream.ToArray(); // Este sirve para la cancelacion
                }

                var result = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes);

                if (conservarArchivo)
                {
                    File.WriteAllBytes(rutaArchivoPfx, result);
                }

                return(new CfdiPfx(result, secretArchivoPfx));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #23
0
        public DecFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
            // 載入私鑰.
            AsymmetricCipherKeyPair keyPair        = ReadPem(this.pri_key);
            PrivateKeyInfo          privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
            Asn1Object asn1ObjectPrivate           = privateKeyInfo.ToAsn1Object();

            this.priKey = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(asn1ObjectPrivate));
        }
예제 #24
0
        protected byte[] GetPrivateKey(AsymmetricKeyParameter key)
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key);

            byte[] privateKeyContent = privateKeyInfo
                                       .ToAsn1Object()
                                       .GetDerEncoded();

            return(privateKeyContent);
        }
예제 #25
0
        /// <summary>
        /// Converts the 32 byte private key to a 25 word mnemonic, including a checksum.
        /// Refer to the mnemonic package for additional documentation.
        /// </summary>
        /// <returns>return string a 25 word mnemonic</returns>
        public string ToMnemonic()
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(this.privateKeyPair.Private);

            byte[]         X509enc = privateKeyInfo.ToAsn1Object().GetEncoded();
            PrivateKeyInfo pkinfo  = PrivateKeyInfo.GetInstance(X509enc);
            var            keyOcts = pkinfo.ParsePrivateKey();

            byte[] res = Asn1OctetString.GetInstance(keyOcts).GetOctets();
            return(Mnemonic.FromKey(res));
        }
예제 #26
0
        public static (string pub, string priv) SerializeKeyPair(this AsymmetricCipherKeyPair pair, bool encodeInHex = encodeInHexValue)
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);

            byte[] serializedPrivateBytes      = privateKeyInfo.ToAsn1Object().GetDerEncoded();
            string serializedPrivate           = encodeInHex ? serializedPrivateBytes.ToHex() : Convert.ToBase64String(serializedPrivateBytes);
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public);

            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            string serializedPublic      = encodeInHex ? serializedPublicBytes.ToHex() : Convert.ToBase64String(serializedPublicBytes);

            return(serializedPublic, serializedPrivate);
        }
예제 #27
0
        /// <summary>
        /// eth Sign
        /// </summary>
        /// <param name="macdata"></param>
        /// <param name="ecdsaPrivateKey"></param>
        /// <returns>r,s,v</returns>
        public static Tuple <byte[], byte[], byte[]> Sign(byte[] macdata, ECPrivateKeyParameters ecdsaPrivateKey)
        {
            MessageSigner  signer         = new MessageSigner();
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecdsaPrivateKey);
            PemObject      pemObj         = new PemObject("PRIVATE KEY", privateKeyInfo.ToAsn1Object().GetEncoded());
            StringWriter   strPri         = new StringWriter();

            Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemW = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(strPri);
            pemW.WriteObject(pemObj);
            var signData = signer.SignAndCalculateV(macdata, ConvertPrikToHexString(strPri.ToString()));

            return(new Tuple <byte[], byte[], byte[]>(signData.R, signData.S, signData.V));
        }
예제 #28
0
        /// <summary>
        /// save private key
        /// </summary>
        /// <param name="privateKey">private key</param>
        /// <param name="pkUrl">key file</param>
        public static void SavePriKey(AsymmetricKeyParameter privateKey, string pkUrl)
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            PemObject      pemObj         = new PemObject("PRIVATE KEY", privateKeyInfo.ToAsn1Object().GetEncoded());
            StringWriter   strPri         = new StringWriter();

            Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemW = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(strPri);
            pemW.WriteObject(pemObj);
            byte[]     priInfoByte = System.Text.Encoding.UTF8.GetBytes(strPri.ToString());
            FileStream fs          = new FileStream(pkUrl, FileMode.Create, FileAccess.Write);

            fs.Write(priInfoByte, 0, priInfoByte.Length);
            fs.Close();
        }
예제 #29
0
        /// <summary>
        /// Returns a byte array containing the private key in PEM format.
        /// </summary>
        public static byte[] ExportPrivateKeyAsPEM(
            X509Certificate2 certificate
            )
        {
            RsaPrivateCrtKeyParameters privateKeyParameter = X509Utils.GetPrivateKeyParameter(certificate);

            using (TextWriter textWriter = new StringWriter())
            {
                // write private key as PKCS#8
                PrivateKeyInfo privateKeyInfo         = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParameter);
                byte[]         serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
                return(EncodeAsPEM(serializedPrivateBytes, "PRIVATE KEY"));
            }
        }
예제 #30
0
        public static void RSA_GeneratePEMKey()
        {
            if (RSA != null)
            {
                return;
            }
            RsaKeyPairGenerator g = new RsaKeyPairGenerator();

            g.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
            var            pair           = g.GenerateKeyPair();
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);

            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
            /////PEM秘钥
            PemPrivateKey = Convert.ToBase64String(serializedPrivateBytes);
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public);

            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            //PEM公钥
            PemPublicKey = Convert.ToBase64String(serializedPublicBytes);

            RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(PemPrivateKey));
            RsaKeyParameters           publicKey  = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(PemPublicKey));
            RSACryptoServiceProvider   rcsp       = new RSACryptoServiceProvider();
            RSAParameters parms = new RSAParameters();

            //So the thing changed is offcourse the ToByteArrayUnsigned() instead of
            //ToByteArray()
            parms.Modulus  = privateKey.Modulus.ToByteArrayUnsigned();
            parms.P        = privateKey.P.ToByteArrayUnsigned();
            parms.Q        = privateKey.Q.ToByteArrayUnsigned();
            parms.DP       = privateKey.DP.ToByteArrayUnsigned();
            parms.DQ       = privateKey.DQ.ToByteArrayUnsigned();
            parms.InverseQ = privateKey.QInv.ToByteArrayUnsigned();
            parms.D        = privateKey.Exponent.ToByteArrayUnsigned();
            parms.Exponent = privateKey.PublicExponent.ToByteArrayUnsigned();
            //So now this now appears to work.
            rcsp.ImportParameters(parms);
            RSA = rcsp;
            //string privateKeyXmlText = rcsp.ToXmlString(true);//XML秘钥
            //string publicKeyXmlText = rcsp.ToXmlString(false);//XML公钥
            //加密解密
            //string texta1 = "abc", texta2 = "", textb1 = "";
            //byte[] cipherbytes;
            //cipherbytes = rcsp.Encrypt(Encoding.UTF8.GetBytes(texta1), false);
            //texta2 = Convert.ToBase64String(cipherbytes);
            //cipherbytes = rcsp.Decrypt(Convert.FromBase64String(texta2), false);
            //textb1 = Encoding.UTF8.GetString(cipherbytes);
        }