Пример #1
0
        /// <summary>
        /// RSA私钥格式转换,pem->xml
        /// </summary>
        /// <param name="pemPrivateKey">pem格式的RSA私钥</param>
        /// <returns>xml格式的RSA私钥</returns>
        public static string XmlPrivateKeyByPem(string pemPrivateKey)
        {
            byte[] bytes           = Convert.FromBase64String(pemPrivateKey);
            var    privateKeyParam = PrivateKeyFactory.CreateKey(bytes) as RsaPrivateCrtKeyParameters;
            string modulus         = Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned());
            string exponent        = Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned());
            string p      = Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned());
            string q      = Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned());
            string dp     = Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned());
            string dq     = Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned());
            string qinv   = Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned());
            string d      = Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned());
            string pemKey = string.Format(@"<RSAKeyValue>
                                               <Modulus>{0}</Modulus>
                                               <Exponent>{1}</Exponent>
                                               <P>{2}</P>
                                               <Q>{3}</Q>
                                               <DP>{4}</DP>
                                               <DQ>{5}</DQ>
                                               <InverseQ>{6}</InverseQ>
                                               <D>{7}</D>
                                            </RSAKeyValue>", modulus, exponent, p, q, dp, dq, qinv, d);

            return(pemKey);
        }
Пример #2
0
    /// <summary>
    /// 基于BouncyCastle的RSA签名
    /// </summary>
    /// <param name="data"></param>
    /// <param name="privateKeyJava"></param>
    /// <param name="hashAlgorithm">JAVA的和.NET的不一样,如:MD5(.NET)等同于MD5withRSA(JAVA)</param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public static string RSASignJavaBouncyCastle(string data, string privateKeyJava,
                                                 string hashAlgorithm = "PSSwithRSA", string encoding = "UTF-8")
    {
        RsaKeyParameters privateKeyParam;

        try
        {
            var keyBytes = Convert.FromBase64String(privateKeyJava);
            var asymmetricKeyParameter = PrivateKeyFactory.CreateKey(keyBytes);
            privateKeyParam = (RsaKeyParameters)asymmetricKeyParameter;
        }
        catch (Exception ex)
        {
            return("Unable to load private key");
            //throw new Exception("Unable to load private key");
        }
        //RsaKeyParameters privateKeyParam =
        //    (RsaKeyParameters) PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKeyJava));
        ISigner signer = SignerUtilities.GetSigner(hashAlgorithm);

        signer.Init(true, privateKeyParam); //参数为true验签,参数为false加签
        var dataByte = Encoding.GetEncoding(encoding).GetBytes(data);

        signer.BlockUpdate(dataByte, 0, dataByte.Length);
        //return Encoding.GetEncoding(encoding).GetString(signer.GenerateSignature()); //签名结果 非Base64String
        return(Convert.ToBase64String(signer.GenerateSignature()));
    }
Пример #3
0
        public void TestElGamal()
        {
            BigInteger ELGamalParaG = new BigInteger(Base64.Decode("QAZPRcsH8kHVKS5065R1Xy6QtsPvDkmDZtPuq18EJkvLrCIZivE/m5puQp3/VKJrG7dKgz4NBGpONp3HT+Cn/g=="));
            BigInteger ELGamalParaP = new BigInteger(Base64.Decode("AKXmAwgkudDLI/Yxk6wk3APn+mSjX5QSyDwpchmegSIi1ZNC0Jb+IbxjroKNhRTBKjtv4/JTXtJS6IqaZv9uKes="));
            BigInteger ELGamalPubY  = new BigInteger(Base64.Decode("AJ/gXuZuCA2X044otNkzs8FI36XuFu1L/YHg5cEmDvICTigycRN2E1DnhP+CTqxEqgEqX8rBe5tuGDlkTLwgNqM="));
            BigInteger ELGamalPriv  = new BigInteger(Base64.Decode("CqVr+K0TpuJKQnc76MjKhxrJzGr93jnuE3mTpth486Meymt8uWEVAQj1tGc9DTt14F9aV9WIT2oYYbvLJRcwow=="));



            ElGamalParameters elPara = new ElGamalParameters(ELGamalParaP, ELGamalParaG);

            ElGamalPrivateKeyParameters elPriv = new ElGamalPrivateKeyParameters(ELGamalPriv, elPara);
            ElGamalPublicKeyParameters  elPub  = new ElGamalPublicKeyParameters(ELGamalPubY, elPara);

            SubjectPublicKeyInfo subInfo  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(elPub);
            PrivateKeyInfo       privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(elPriv);

            ElGamalPrivateKeyParameters telPriv = (ElGamalPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);
            ElGamalPublicKeyParameters  telPub  = (ElGamalPublicKeyParameters)PublicKeyFactory.CreateKey(subInfo);


            // Console.WriteLine(telPriv.Equals(elPriv));



            Assert.IsTrue(telPriv.Equals(elPriv), "ELGamal Private key to into back to private key.");
            Assert.IsTrue(telPub.Equals(elPub), "ELGamal Public key to into back to private key.");

            Assert.IsTrue(true, "ELGamal Test worked.");
        }
Пример #4
0
        /// <summary>
        /// 私钥加密 RSA解密密文大小
        /// </summary>
        /// <param name="privateKey"></param>
        /// <param name="contentData"></param>
        /// <param name="encoding"></param>
        /// <param name="algorithm"></param>
        /// <param name="forEncryption"></param>
        /// <returns></returns>
        public static string DecryptByPrivateKey(string privateKey, string contentData, string encoding = "UTF-8", string algorithm = "RSA/ECB/PKCS1Padding", bool forEncryption = false)
        {
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
            var c = CipherUtilities.GetCipher(algorithm);

            c.Init(forEncryption, new ParametersWithRandom(privateKeyParam));
            byte[]       data     = Encoding.GetEncoding(encoding).GetBytes(contentData);
            int          inputLen = data.Length;
            MemoryStream ms       = new MemoryStream();
            int          offSet   = 0;

            byte[] cache;
            int    i = 0;

            // 对数据分段加�?
            while (inputLen - offSet > 0)
            {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK)
                {
                    cache = c.DoFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                }
                else
                {
                    cache = c.DoFinal(data, offSet, inputLen - offSet);
                }
                ms.Write(cache, 0, cache.Length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = ms.ToArray();
            ms.Close();
            return(Convert.ToBase64String(encryptedData));
        }
Пример #5
0
        /// <summary>
        /// Create an RSA parameter based on the xml format private key
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        protected sealed override RSAParameters CreateRsapFromPrivateKey(string privateKey)
        {
            privateKey = RsaPemFormatHelper.Pkcs1PrivateKeyFormat(privateKey);

            PemReader pr = new PemReader(new StringReader(privateKey));

            if (!(pr.ReadObject() is AsymmetricCipherKeyPair asymmetricCipherKeyPair))
            {
                throw new Exception("Private key format is incorrect");
            }
            RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters =
                (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(
                    PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricCipherKeyPair.Private));
            var rsap = new RSAParameters();

            rsap.Modulus  = rsaPrivateCrtKeyParameters.Modulus.ToByteArrayUnsigned();
            rsap.Exponent = rsaPrivateCrtKeyParameters.PublicExponent.ToByteArrayUnsigned();
            rsap.P        = rsaPrivateCrtKeyParameters.P.ToByteArrayUnsigned();
            rsap.Q        = rsaPrivateCrtKeyParameters.Q.ToByteArrayUnsigned();
            rsap.DP       = rsaPrivateCrtKeyParameters.DP.ToByteArrayUnsigned();
            rsap.DQ       = rsaPrivateCrtKeyParameters.DQ.ToByteArrayUnsigned();
            rsap.InverseQ = rsaPrivateCrtKeyParameters.QInv.ToByteArrayUnsigned();
            rsap.D        = rsaPrivateCrtKeyParameters.Exponent.ToByteArrayUnsigned();

            return(rsap);
        }
Пример #6
0
        public static string RSAPrivateKeyJava2DotNet(string privateKey, string keyFileName)
        {
            var pk = "";
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));

            pk = string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                               Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
                               Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
                               Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
                               Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
                               Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
                               Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
                               Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
                               Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));

            if (!string.IsNullOrEmpty(keyFileName))
            {
                using (StreamWriter writer = new StreamWriter(string.Format("{0}.xml", keyFileName)))
                {
                    writer.Write(pk);
                }
            }

            return(pk);
        }
Пример #7
0
    internal static ECPrivateKeyParameters PrivateParamsFromDerOrRaw(ReadOnlyMemory <byte> privateKey)
    {
        AsymmetricKeyParameter asymmetricKeyParameter;

        try
        {
            if (privateKey.Length == 32)
            {
                return(new ECPrivateKeyParameters(new BigInteger(privateKey.ToArray()), domain));
            }
            asymmetricKeyParameter = PrivateKeyFactory.CreateKey(privateKey.ToArray());
        }
        catch (Exception ex)
        {
            if (privateKey.Length == 0)
            {
                throw new ArgumentOutOfRangeException("Private Key cannot be empty.", ex);
            }
            throw new ArgumentOutOfRangeException("The private key was not provided in a recognizable ECDSA Secp256K1 format.", ex);
        }
        if (asymmetricKeyParameter is ECPrivateKeyParameters ecPrivateKeyParameters)
        {
            if (ecPrivateKeyParameters.IsPrivate)
            {
                return(ecPrivateKeyParameters);
            }
            throw new ArgumentOutOfRangeException("This is not an ECDSA Secp256K1 private key, it appears to be a public key.");
        }
        throw new ArgumentOutOfRangeException("The private key does not appear to be encoded in ECDSA Secp256K1 format.");
    }
Пример #8
0
    internal static (KeyType keyType, AsymmetricKeyParameter publicKeyParam) ParsePrivateKeyFromDerBytes(ReadOnlyMemory <byte> privateKey)
    {
        AsymmetricKeyParameter asymmetricKeyParameter;

        try
        {
            asymmetricKeyParameter = PrivateKeyFactory.CreateKey(privateKey.ToArray());
        }
        catch (Exception ex)
        {
            throw new ArgumentOutOfRangeException("The private key does not appear to be encoded as a recognizable private key format.", ex);
        }
        if (asymmetricKeyParameter is Ed25519PrivateKeyParameters ed25519PrivateKeyParameters)
        {
            if (ed25519PrivateKeyParameters.IsPrivate)
            {
                return(KeyType.Ed25519, ed25519PrivateKeyParameters);
            }
            throw new ArgumentOutOfRangeException("This is not an Ed25519 private key, it appears to be a public key.");
        }
        if (asymmetricKeyParameter is ECPrivateKeyParameters ecPrivateKeyParameters)
        {
            if (ecPrivateKeyParameters.IsPrivate)
            {
                return(KeyType.ECDSASecp256K1, ecPrivateKeyParameters);
            }
            throw new ArgumentOutOfRangeException("This is not an ECDSA Secp256K1 private key, it appears to be a public key.");
        }
        throw new ArgumentOutOfRangeException("The private key does not appear to be encoded in Ed25519 format.");
    }
Пример #9
0
        public void TestRsa()
        {
            BigInteger                 rsaPubMod   = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
            BigInteger                 rsaPubExp   = new BigInteger(Base64.Decode("EQ=="));
            BigInteger                 rsaPrivMod  = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
            BigInteger                 rsaPrivDP   = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ=="));
            BigInteger                 rsaPrivDQ   = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ=="));
            BigInteger                 rsaPrivExp  = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E="));
            BigInteger                 rsaPrivP    = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE="));
            BigInteger                 rsaPrivQ    = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0="));
            BigInteger                 rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg=="));
            RsaKeyParameters           rsaPublic   = new RsaKeyParameters(false, rsaPubMod, rsaPubExp);
            RsaPrivateCrtKeyParameters rsaPrivate  = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);

            SubjectPublicKeyInfo subInfo    = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rsaPublic);
            RsaKeyParameters     testResult = (RsaKeyParameters)PublicKeyFactory.CreateKey(subInfo);

            // check RSA public key.

            Assert.IsFalse(!testResult.Equals(rsaPublic), "RSA: test failed on public key to info and back to public key.");

            PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(rsaPrivate);

            testResult = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privInfo);

            Assert.IsFalse(!testResult.Equals(rsaPrivate), "RSA: private key to info back to private key.");

            Assert.IsTrue(true, "RSATest worked.");
        }
Пример #10
0
        public void TestDSA()
        {
            BigInteger DSAParaG    = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            BigInteger DSAParaP    = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            BigInteger DSAParaQ    = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            BigInteger DSAPublicY  = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters           para    = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters  dsaPub  = new DsaPublicKeyParameters(DSAPublicY, para);

            SubjectPublicKeyInfo subInfo    = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(dsaPub);
            DsaKeyParameters     testResult = (DsaKeyParameters)PublicKeyFactory.CreateKey(subInfo);

            // check RSA public key.

            Assert.IsFalse(!testResult.Equals(dsaPub), "DSA: test failed on public key to info and back to public key.");

            PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(dsaPriv);

            testResult = (DsaPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);

            Assert.IsFalse(!testResult.Equals(dsaPriv), "DSA: private key to info back to private key.");

            Assert.IsTrue(true, "DSATest worked.");
        }
Пример #11
0
        AsymmetricKeyParameter DecryptAsymmetricKeyParameter(byte[] buffer, int length)
        {
            using (var memory = new MemoryStream(buffer, 0, length, false)) {
                using (var asn1 = new Asn1InputStream(memory)) {
                    var sequence = asn1.ReadObject() as Asn1Sequence;
                    if (sequence == null)
                    {
                        return(null);
                    }

                    var encrypted = EncryptedPrivateKeyInfo.GetInstance(sequence);
                    var algorithm = encrypted.EncryptionAlgorithm;
                    var encoded   = encrypted.GetEncryptedData();

                    var cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher;
                    if (cipher == null)
                    {
                        return(null);
                    }

                    var cipherParameters = PbeUtilities.GenerateCipherParameters(algorithm, passwd);

                    cipher.Init(false, cipherParameters);

                    var decrypted = cipher.DoFinal(encoded);
                    var keyInfo   = PrivateKeyInfo.GetInstance(decrypted);

                    return(PrivateKeyFactory.CreateKey(keyInfo));
                }
            }
        }
Пример #12
0
        public static ECPrivateKeyParameters DeserializePrivateKey(string priv, bool encodeInHex = encodeInHexValue)
        {
            var keyByteArray = encodeInHex ? FromHex(priv) : Convert.FromBase64String(priv);
            ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(keyByteArray);

            return(privateKey);
        }
Пример #13
0
        private void cryptInitPrivate()
        {
            RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(pgpKey);

            encryptEngine = new Pkcs1Encoding(new RsaEngine());
            encryptEngine.Init(true, privateKey);             // ????
        }
Пример #14
0
        /// <summary>
        /// Get the signature based on the timestamp.  If the timestamp is null, create
        /// a new timestamp.
        /// </summary>
        /// <param name="timeStamp">
        /// The time stamp.
        /// </param>
        /// <returns>
        /// The calculate signature <see cref="string"/>.
        /// </returns>
        public string GetSignature(string timeStamp)
        {
            this.TimeStamp = timeStamp ?? GetTimestampInJavaMillis();

            // Append values into string for signing
            var message = this.ConsumerId + "\n" + this.RequestUrl + "\n" +
                          this.RequestMethod.ToUpper() + "\n" + this.TimeStamp + "\n";

            RsaKeyParameters rsaKeyParameter;

            try
            {
                var keyBytes = Convert.FromBase64String(this.PrivateKey);
                var asymmetricKeyParameter = PrivateKeyFactory.CreateKey(keyBytes);
                rsaKeyParameter = (RsaKeyParameters)asymmetricKeyParameter;
            }
            catch (System.Exception)
            {
                throw new Exception("Unable to load private key");
            }

            var signer = SignerUtilities.GetSigner("SHA256withRSA");

            signer.Init(true, rsaKeyParameter);
            var messageBytes = Encoding.UTF8.GetBytes(message);

            signer.BlockUpdate(messageBytes, 0, messageBytes.Length);
            var signed = signer.GenerateSignature();
            var hashed = Convert.ToBase64String(signed);

            return(hashed);
        }
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator pGen     = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters        genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25);

            pGen.Init(genParam);

            IAsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            //
            // set up the parameters
            //
            byte[] salt           = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int    iterationCount = 100;

            //
            // set up the key
            //
            char[] password1 = { 'h', 'e', 'l', 'l', 'o' };

            EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(alg, password1, salt, iterationCount, PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private));

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password1, encInfo);

            IAsymmetricKeyParameter key = PrivateKeyFactory.CreateKey(info);

            if (!key.Equals(pair.Private))
            {
                Fail("Key corrupted");
            }

            doOpensslTestKeys();
        }
Пример #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Sensus.Encryption.AsymmetricEncryption"/> class.
        /// </summary>
        /// <param name="publicKeyString">Public key string. Can be generated following the generation of the private key (see below)
        /// using the following command:
        ///
        ///   openssl rsa -in private.pem -outform PEM -pubout -out public.pem
        ///
        /// </param>
        /// <param name="privateKeyString">Private key string. Only necessary if you want to be able to decrypt using this object. Can
        /// be generated with the following commands:
        ///
        ///   openssl genrsa -des3 -out private.pem 2048
        ///   openssl pkcs8 -topk8 -nocrypt -in private.pem
        ///
        /// </param>
        public AsymmetricEncryption(string publicKeyString, string privateKeyString)
        {
            // the following is adapted from http://stackoverflow.com/questions/9283716/c-sharp-net-crypto-using-base64-encoded-public-key-to-verify-rsa-signature/9290086#9290086

            if (publicKeyString != null)
            {
                byte[]           publicKeyBytes   = Convert.FromBase64String(publicKeyString);
                RsaKeyParameters rsaKeyParameters = PublicKeyFactory.CreateKey(publicKeyBytes) as RsaKeyParameters;

                _rsaPublicParameters          = new RSAParameters();
                _rsaPublicParameters.Modulus  = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
                _rsaPublicParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
            }

            if (privateKeyString != null)
            {
                byte[] privateKeyBytes = Convert.FromBase64String(privateKeyString);
                RsaPrivateCrtKeyParameters privateKeyParameters = PrivateKeyFactory.CreateKey(privateKeyBytes) as RsaPrivateCrtKeyParameters;

                _rsaPrivateParameters          = new RSAParameters();
                _rsaPrivateParameters.DP       = privateKeyParameters.DP.ToByteArrayUnsigned();
                _rsaPrivateParameters.DQ       = privateKeyParameters.DQ.ToByteArrayUnsigned();
                _rsaPrivateParameters.P        = privateKeyParameters.P.ToByteArrayUnsigned();
                _rsaPrivateParameters.Q        = privateKeyParameters.Q.ToByteArrayUnsigned();
                _rsaPrivateParameters.InverseQ = privateKeyParameters.QInv.ToByteArrayUnsigned();
                _rsaPrivateParameters.Modulus  = privateKeyParameters.Modulus.ToByteArrayUnsigned();
                _rsaPrivateParameters.Exponent = privateKeyParameters.PublicExponent.ToByteArrayUnsigned();
            }
        }
Пример #17
0
        static byte[] GetPfxCertificateByteArray(ref string certString, ref string privateKey)
        {
            byte[] certArray       = Convert.FromBase64String(certString);
            byte[] privateKeyArray = Convert.FromBase64String(privateKey);


            //Translate to Pkcs#12
            var store = new Pkcs12StoreBuilder().Build();

            Org.BouncyCastle.X509.X509Certificate certTranslate = new X509CertificateParser().ReadCertificate(certArray);

            var certEntry = new X509CertificateEntry(certTranslate);
            var pk        = PrivateKeyFactory.CreateKey(privateKeyArray);
            var keyEntry  = new AsymmetricKeyEntry(pk);

            store.SetKeyEntry("", keyEntry, new X509CertificateEntry[] { certEntry });


            MemoryStream stream = new MemoryStream();

            store.Save(stream, new char[] { }, new SecureRandom());

            stream.Dispose();
            //FromString
            byte[] pfxByteArray = stream.ToArray();

            return(pfxByteArray);
        }
        /// <summary>
        /// Creates a private key <see cref="AsymmetricKeyParameter"/> from a byte array containing the exponent and modulus
        /// </summary>
        /// <param name="publicKey">the byte array conatining the exponent and the modulus</param>
        /// <returns>The private key parameter object</returns>
        protected AsymmetricKeyParameter CreateAsymmetricKeyParameterFromPrivateKeyInfo(byte[] privateKeyInfo)
        {
            AsymmetricKeyParameter privateKey = null;

            try
            {
                privateKey = PrivateKeyFactory.CreateKey(privateKeyInfo);
            }
            catch (SecurityUtilityException exception)
            {
                string message = "Private Key Import Failed!\n" +
                                 $"{exception.Message}.\n" +
                                 "The contents of the source do not represent a usable object identifier\n" +
                                 "Verify that the public key is not corrupted";
                throw new CryptoException(message, exception);
            }
            catch (IOException exception)
            {
                string message = "Private Key Import Failed!\n" +
                                 $"{exception.Message}.\n" +
                                 "The contents of source do not represent an ASN1 - BER - encoded PKCS#8 structure.\n" +
                                 "Verify that the public key is not corrupted";
                throw new CryptoException(message, exception);
            }
            catch (ArgumentException exception)
            {
                string message = "Private Key Import Failed!\n" +
                                 $"{exception.Message}\n" +
                                 "The contents of source do not represent an ASN.1 - BER - encoded PKCS#8 structure.\n" +
                                 "Verify that the private key is not corrupted";
                throw new CryptoException(message, exception);
            }
            return(privateKey);
        }
Пример #19
0
        /// <summary>
        /// Private Key Convert Pkcs8->xml
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyPkcs8ToXml(string privateKey)
        {
            privateKey = RsaPemFormatHelper.Pkcs8PrivateKeyFormatRemove(privateKey);
            RsaPrivateCrtKeyParameters privateKeyParam =
                (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));

            XElement privatElement = new XElement("RSAKeyValue");
            //Modulus
            XElement primodulus = new XElement("Modulus", Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()));
            //Exponent
            XElement priexponent = new XElement("Exponent", Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()));
            //P
            XElement prip = new XElement("P", Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()));
            //Q
            XElement priq = new XElement("Q", Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()));
            //DP
            XElement pridp = new XElement("DP", Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()));
            //DQ
            XElement pridq = new XElement("DQ", Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()));
            //InverseQ
            XElement priinverseQ = new XElement("InverseQ", Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()));
            //D
            XElement prid = new XElement("D", Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));

            privatElement.Add(primodulus);
            privatElement.Add(priexponent);
            privatElement.Add(prip);
            privatElement.Add(priq);
            privatElement.Add(pridp);
            privatElement.Add(pridq);
            privatElement.Add(priinverseQ);
            privatElement.Add(prid);

            return(privatElement.ToString());
        }
Пример #20
0
        private AsymmetricCipherKeyPair ReadECPrivateKey(
            string endMarker)
        {
            try
            {
                byte[] bytes = ReadBytes(endMarker);
                ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(
                    (Asn1Sequence)Asn1Object.FromByteArray(bytes));
                AlgorithmIdentifier algId = new AlgorithmIdentifier(
                    X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());

                PrivateKeyInfo       privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());
                SubjectPublicKeyInfo pubInfo  = new SubjectPublicKeyInfo(algId, pKey.GetPublicKey().GetBytes());

                // TODO Are the keys returned here ECDSA, as Java version forces?
                return(new AsymmetricCipherKeyPair(
                           PublicKeyFactory.CreateKey(pubInfo),
                           PrivateKeyFactory.CreateKey(privInfo)));
            }
            catch (InvalidCastException e)
            {
                throw new IOException("wrong ASN.1 object found in stream.", e);
            }
            catch (Exception e)
            {
                throw new IOException("problem parsing EC private key.", e);
            }
        }
Пример #21
0
        public void TestRfc4134Ex5_1()
        {
            byte[] data = Hex.Decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e");

//			KeyFactory kFact = KeyFactory.GetInstance("RSA");
//			Key key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt));
            AsymmetricKeyParameter key = PrivateKeyFactory.CreateKey(bobPrivRsaEncrypt);

            CmsEnvelopedData ed = new CmsEnvelopedData(rfc4134ex5_1);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

            Assert.AreEqual("1.2.840.113549.3.7", ed.EncryptionAlgOid);

            ICollection c = recipients.GetRecipients();

            Assert.AreEqual(1, c.Count);

            foreach (RecipientInformation recipient in c)
            {
                byte[] recData = recipient.GetContent(key);

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

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

                    Key key;

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

                    case DsaPrivateKeyParameters dsa:

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

                        key = KeyFromBouncyCastle(dsa);
                        break;

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

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

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

                    return(new ImportedKeySet(key, purpose, "imported from pkcs file"));
                }
            }
Пример #23
0
        private static AsymmetricKeyParameter GetPrivateKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            var privateInfoByte = Convert.FromBase64String(s);
            var priKey          = PrivateKeyFactory.CreateKey(privateInfoByte);

            return(priKey);
        }
Пример #24
0
        public PKCS12KeyStore(string keyAlias, RSAKeyPair keyPair, X509CertificateBase certificate)
        {
            m_KeyStore = new Pkcs12StoreBuilder().SetUseDerEncoding(true).Build();

            m_KeyStore.SetKeyEntry(keyAlias,
                                   new AsymmetricKeyEntry(PrivateKeyFactory.CreateKey(keyPair.PrivateKey)),
                                   new[] { new X509CertificateEntry(new X509CertificateParser().ReadCertificate(certificate.GetEncoded())) });
        }
Пример #25
0
        private AsymmetricKeyParameter GetPrivateKeyParameter(string keyBase64)
        {
            keyBase64 = keyBase64.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty);
            var privateInfoByte = Convert.FromBase64String(keyBase64);
            var priKey          = PrivateKeyFactory.CreateKey(privateInfoByte);

            return(priKey);
        }
Пример #26
0
        /// <summary>
        ///     Loads RSA private key.
        /// </summary>
        /// <param name="key">RSA private key DER encoded.</param>
        /// <returns>RSA Private Key</returns>
        public static RsaPrivateCrtKeyParameters LoadPrivateKey(byte[] key)
        {
            var algorithm           = new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance);
            var privateKeyStructure = RsaPrivateKeyStructure.GetInstance(Asn1Sequence.GetInstance(key));
            var privateKeyInfo      = new PrivateKeyInfo(algorithm, privateKeyStructure);

            return(PrivateKeyFactory.CreateKey(privateKeyInfo) as RsaPrivateCrtKeyParameters);
        }
Пример #27
0
 public UserKeyPair(byte[] privatKeyByte)
 {
     if (privatKeyByte == null)
     {
         throw new NullReferenceException("private key value cannot be null");
     }
     PrivatKey = (RsaKeyParameters)PrivateKeyFactory.CreateKey(privatKeyByte);
 }
Пример #28
0
        public void TestECKeyAgreeVectors()
        {
            AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(ecKeyAgreeKey);

            VerifyECKeyAgreeVectors(privKey, "2.16.840.1.101.3.4.1.42", ecKeyAgreeMsgAES256);
            VerifyECKeyAgreeVectors(privKey, "2.16.840.1.101.3.4.1.2", ecKeyAgreeMsgAES128);
            VerifyECKeyAgreeVectors(privKey, "1.2.840.113549.3.7", ecKeyAgreeMsgDESEDE);
        }
Пример #29
0
 public static AsymEncryption Decryptor(byte[] privateKey)
 {
     return(new AsymEncryption
     {
         // FIX there is a problem here. we serialize the PrivateKeyInfo, not the PrivateKey
         PrivateKey = PrivateKeyFactory.CreateKey(privateKey)
     });
 }
Пример #30
0
        public void LoadPrivateKeyFromHexed(string privateKeyAsHex)
        {
            var privateKey     = PrivateKeyFactory.CreateKey(Hex.ToByte(privateKeyAsHex));
            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            File.WritePem(privateKeyInfo);
            logger.Info($"Loaded key to {Directory.GetCurrentDirectory()}\\id_econfig.pem.");
        }