Example #1
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);
        }
        /// <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("转换失败");
            }
        }
Example #3
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)
            });
        }
Example #4
0
        public byte[] GetPublicKey()
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(this.keyPair.Public);

            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return(serializedPublicBytes);
        }
Example #5
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);
        }
        internal static byte[] GetPublicKeyInBytes(AsymmetricKeyParameter publicKey)
        {
            SubjectPublicKeyInfo publicKeyInfo =
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            return(publicKeyInfo.ToAsn1Object().GetDerEncoded());
        }
Example #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);
        }
Example #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));
        }
Example #9
0
        public static byte[] GetSerializedPublicKey(AsymmetricKeyParameter keyPair)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair);

            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return(serializedPublicBytes);
        }
        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;
            }
        }
        public static string GetPublicKeyBase64(AsymmetricKeyParameter key)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key);

            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();

            return(Convert.ToBase64String(serializedPublicBytes));
        }
Example #12
0
        public static byte[] EncodeKeyParameter(AsymmetricKeyParameter key)
        {
            SubjectPublicKeyInfo publicKeyInfo
                = SubjectPublicKeyInfoFactory
                  .CreateSubjectPublicKeyInfo(key);

            return(publicKeyInfo.ToAsn1Object().GetDerEncoded());
        }
Example #13
0
        public byte [] GenerateEncodedPublicKeyInfo()
        {
            SubjectPublicKeyInfo publicKeyInfo
                = SubjectPublicKeyInfoFactory
                  .CreateSubjectPublicKeyInfo(GetPublicKeyParameter());

            return(publicKeyInfo.ToAsn1Object().GetDerEncoded());
        }
Example #14
0
        /// <summary>
        /// 从 .Net RSA 算法公钥参数转换为 Java 格式的 RSA 公钥
        /// </summary>
        /// <param name="publicKey">.Net生成的公钥参数</param>
        /// <returns></returns>
        public static string ToJavaPublicKey(this RSAParameters publicKey)
        {
            RsaKeyParameters     para = DotNetUtilities.GetRsaPublicKey(publicKey);
            SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(para);

            byte[] bytes = info.ToAsn1Object().GetDerEncoded();
            return(ToBase64(bytes));
        }
Example #15
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);
            }
        }
Example #16
0
        public static string PrintPublicKey(AsymmetricCipherKeyPair keys)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public);

            byte[] serializedBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            string serialized      = Convert.ToBase64String(serializedBytes);

            return("Key==>" + serialized);
        }
Example #17
0
        public static string SavePublicKey(AsymmetricKeyParameter publicKey)
        {
            //保存公钥到文件
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            Asn1Object           aobject       = publicKeyInfo.ToAsn1Object();

            byte[] pubInfoByte = aobject.GetEncoded();
            return(Convert.ToBase64String(pubInfoByte));
        }
Example #18
0
        public static string SerializePublicKey(this AsymmetricKeyParameter publicKey, bool encodeInHex = encodeInHexValue)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

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

            return(serializedPublic);
        }
Example #19
0
        public static string GetSerializedPublicKey(RsaKeyParameters publicKey)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

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

            return(serializedPublic);
        }
        public string getRSAPublicKey()
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rsaKeyPair.Public);

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

            return(serializedPublic);
        }
Example #21
0
        protected byte[] GetPublicKey(AsymmetricKeyParameter key)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key);

            byte[] publicKeyContent = publicKeyInfo
                                      .ToAsn1Object()
                                      .GetDerEncoded();

            return(publicKeyContent);
        }
        /// <summary>
        /// Get the public key fingerprint(hash) of an Aysmmetric Cipher Key Pair
        /// </summary>
        /// <param name="keyPair">Key pair to fingerprint</param>
        /// <returns>MD5 Hash of the given keypair</returns>
        public static string GetPublicKeyFingerprint(AsymmetricCipherKeyPair keyPair)
        {
            if (keyPair == null)
            {
                throw new ArgumentNullException(KEYPAIR_NULL);
            }
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);

            byte[] serializedPublicKey = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return(ComputeHash(serializedPublicKey));
        }
Example #23
0
    /// <summary>
    /// RSA公钥格式转换,.net->java
    /// </summary>
    /// <param name="publicKey">.net生成的公钥</param>
    /// <returns></returns>
    public static string RSAPublicKeyDotNet2Java(string publicKey)
    {
        XmlDocument          doc           = new XmlDocument(); doc.LoadXml(publicKey);
        BigInteger           m             = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
        BigInteger           p             = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
        RsaKeyParameters     pub           = new RsaKeyParameters(false, m, p);
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);

        byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
        return(Convert.ToBase64String(serializedPublicBytes));
    }
Example #24
0
        public byte[] GetPublicKey()
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            Console.WriteLine("Public Key -> exported as ASN1.DER Encoded");
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            Console.WriteLine("Public Key: -> \n" + Utils.HexDump(serializedPublicBytes));
            Console.WriteLine("Public Key -> pad bits = " + publicKeyInfo.PublicKeyData.PadBits);
            Console.WriteLine("Public Key -> Exponent = " + publicKey.Exponent.ToString());
            //return BitConverter.ToString(serializedPublicBytes).Replace("-", string.Empty);
            return(serializedPublicBytes);
        }
        private void GenerateKey(string fileName)
        {
            string fileNamePublic = fileName + ".pub";

            if (File.Exists(fileNamePublic) &&
                ShowMessageBox("Overwrite", "File " + fileNamePublic + " already exists. Overwrite?", MessageBoxButtons.YesNo,
                               MessageBoxIcon.Warning) == DialogResult.No)
            {
                return;
            }

            RsaKeyPairGenerator g = new RsaKeyPairGenerator();

            g.Init(new KeyGenerationParameters(new SecureRandom(), Convert.ToInt32(cbKeyLength.Text, 10)));
            AsymmetricCipherKeyPair pair = g.GenerateKeyPair();

            //PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);
            //byte [] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();

            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public);

            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();

            //Save private key to filename
            try
            {
                using (StreamWriter file = new StreamWriter(fileName))
                {
                    PemWriter pWrt = new PemWriter(file);
                    pWrt.WriteObject(pair);
                    pWrt.Writer.Close();
                }

                //Save public key to filename
                using (StreamWriter file = new StreamWriter(fileNamePublic))
                {
                    PemWriter pWrt = new PemWriter(file);
                    pWrt.WriteObject(pair.Public);
                    pWrt.Writer.Close();
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox("Key file error.", "Couldn't save key pair:\n" + ex.Message, MessageBoxButtons.OK,
                               MessageBoxIcon.Error);
                return;
            }


            UpdateSuggestedDns(Convert.ToBase64String(serializedPublicBytes));
            SetDomainKeyPath(fileName);
        }
Example #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);
        }
Example #27
0
        //XML 公鑰轉換為 PEM 公鑰
        public static string publicKeyXml2Pem(string publicXmlKeyString)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(publicXmlKeyString);
            BigInteger           m             = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger           p             = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            RsaKeyParameters     pub           = new RsaKeyParameters(false, m, p);
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);

            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return("-----BEGIN PUBLIC KEY-----\n" + Convert.ToBase64String(serializedPublicBytes) + "\n-----END PUBLIC KEY-----");
        }
Example #28
0
        /// <summary>
        /// RSA 公钥格式转换,.net => java
        /// </summary>
        /// <param name="publicKey">.net生成的公钥</param>
        /// <returns></returns>
        public static string RsaPublicKeyDotNet2Java(this string publicKey)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(publicKey);
            BigInteger modulus        = doc.GetBigInteger("Modulus");
            BigInteger publicExponent = doc.GetBigInteger("Exponent");

            RsaKeyParameters     publicKeyParam = new RsaKeyParameters(false, modulus, publicExponent);
            SubjectPublicKeyInfo publicKeyInfo  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKeyParam);

            byte[] serializePublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return(Convert.ToBase64String(serializePublicBytes));
        }
Example #29
0
        /// <summary>
        /// 把XML格式的秘钥转为Java格式
        /// </summary>
        /// <param name="XML">XML秘钥</param>
        /// <returns>Java秘钥</returns>
        private static string PublicKeyToJavaFormat(string XML)
        {
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(XML);
            BigInteger       m   = new BigInteger(1, Convert.FromBase64String(xmlDocument.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger       p   = new BigInteger(1, Convert.FromBase64String(xmlDocument.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            RsaKeyParameters pub = new RsaKeyParameters(false, m, p);

            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);

            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return(Convert.ToBase64String(serializedPublicBytes));
        }
Example #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);
        }