Пример #1
0
        public void TestECDsa191bitBinary()
        {
            BigInteger r = new BigInteger("87194383164871543355722284926904419997237591535066528048");
            BigInteger s = new BigInteger("308992691965804947361541664549085895292153777025772063598");

            byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("1542725565216523985789236956265265265235675811949404040041"));

            SecureRandom k = FixedSecureRandom.From(kData);

            F2mCurve curve = new F2mCurve(
                191,                                                                     // m
                9,                                                                       //k
                new BigInteger("2866537B676752636A68F56554E12640276B649EF7526267", 16),  // a
                new BigInteger("2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("0436B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D765BE73433B3F95E332932E70EA245CA2418EA0EF98018FB")), // G
                new BigInteger("1569275433846670190958947355803350458831205595451630533029"),                                                        // n
                BigInteger.Two);                                                                                                                     // h

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("1275552191113212300012030439187146164646146646466749494799"), // d
                parameters);

            ECDsaSigner          ecdsa = new ECDsaSigner();
            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ecdsa.Init(true, param);

            byte[]       message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig     = ecdsa.GenerateSignature(message);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                     + " expecting: " + r + SimpleTest.NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("045DE37E756BD55D72E3768CB396FFEB962614DEA4CE28A2E755C0E0E02F5FB132CAF416EF85B229BBB8E1352003125BA1")), // Q
                parameters);

            ecdsa.Init(false, pubKey);
            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Пример #2
0
        public virtual void Init(bool forSigning, ICipherParameters parameters)
        {
            SecureRandom providedRandom = null;

            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                    providedRandom = rParam.Random;
                    parameters     = rParam.Parameters;
                }

                if (!(parameters is DsaPrivateKeyParameters))
                {
                    throw new InvalidKeyException("DSA private key required for signing");
                }

                this.key = (DsaPrivateKeyParameters)parameters;
            }
            else
            {
                if (!(parameters is DsaPublicKeyParameters))
                {
                    throw new InvalidKeyException("DSA public key required for verification");
                }

                this.key = (DsaPublicKeyParameters)parameters;
            }

            this.random = InitSecureRandom(forSigning && !kCalculator.IsDeterministic, providedRandom);
        }
Пример #3
0
        public virtual void Init(
            bool forSigning,
            ICipherParameters parameters)
        {
            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                    this.random = rParam.Random;
                    parameters  = rParam.Parameters;
                }
                else
                {
                    this.random = new SecureRandom();
                }

                if (!(parameters is ECPrivateKeyParameters))
                {
                    throw new InvalidKeyException("EC private key required for signing");
                }

                this.key = (ECPrivateKeyParameters)parameters;
            }
            else
            {
                if (!(parameters is ECPublicKeyParameters))
                {
                    throw new InvalidKeyException("EC public key required for verification");
                }

                this.key = (ECPublicKeyParameters)parameters;
            }
        }
Пример #4
0
        /**
         * initialise the ElGamal engine.
         *
         * @param forEncryption true if we are encrypting, false otherwise.
         * @param param the necessary ElGamal key parameters.
         */
        public void Init(
            bool forEncryption,
            ICipherParameters parameters)
        {
            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom)parameters;

                this.key    = (ElGamalKeyParameters)p.Parameters;
                this.random = p.Random;
            }
            else
            {
                this.key    = (ElGamalKeyParameters)parameters;
                this.random = new SecureRandom();
            }

            this.forEncryption = forEncryption;
            this.bitSize       = key.Parameters.P.BitLength;

            if (forEncryption)
            {
                if (!(key is ElGamalPublicKeyParameters))
                {
                    throw new ArgumentException("ElGamalPublicKeyParameters are required for encryption.");
                }
            }
            else
            {
                if (!(key is ElGamalPrivateKeyParameters))
                {
                    throw new ArgumentException("ElGamalPrivateKeyParameters are required for decryption.");
                }
            }
        }
Пример #5
0
        /// <summary>Initialise the generator for signing.</summary>
        public void InitSign(
            int sigType,
            PgpPrivateKey key,
            SecureRandom random)
        {
            this.privKey       = key;
            this.signatureType = sigType;

            try
            {
                ICipherParameters cp = key.Key;
                if (random != null)
                {
                    cp = new ParametersWithRandom(key.Key, random);
                }

                sig.Init(true, cp);
            }
            catch (InvalidKeyException e)
            {
                throw new PgpException("invalid key.", e);
            }

            dig.Reset();
            lastb = 0;
        }
Пример #6
0
        public void Init(
            ICipherParameters parameters)
        {
            AsymmetricKeyParameter kParam;

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                this.random = rParam.Random;
                kParam      = (AsymmetricKeyParameter)rParam.Parameters;
            }
            else
            {
                this.random = new SecureRandom();
                kParam      = (AsymmetricKeyParameter)parameters;
            }

            if (!(kParam is DHPrivateKeyParameters))
            {
                throw new ArgumentException("DHEngine expects DHPrivateKeyParameters");
            }

            this.key      = (DHPrivateKeyParameters)kParam;
            this.dhParams = key.Parameters;
        }
Пример #7
0
        public void Init(bool forEncryption, ICipherParameters parameters)
        {
            AsymmetricKeyParameter kParam;

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                this.random = rParam.Random;
                kParam      = (AsymmetricKeyParameter)rParam.Parameters;
            }
            else
            {
                this.random = new SecureRandom();
                kParam      = (AsymmetricKeyParameter)parameters;
            }

            engine.Init(forEncryption, parameters);

            this.forPrivateKey = kParam.IsPrivate;
            this.forEncryption = forEncryption;
            this.blockBuffer   = new byte[engine.GetOutputBlockSize()];

            if (pLen > 0 && fallback == null && random == null)
            {
                throw new ArgumentException("encoder requires random");
            }
        }
Пример #8
0
        public void Init(
            bool forSigning,
            ICipherParameters parameters)
        {
            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                    this.random = rParam.Random;
                    parameters  = rParam.Parameters;
                }
                else
                {
                    this.random = new SecureRandom();
                }

                if (!(parameters is Gost3410PrivateKeyParameters))
                {
                    throw new InvalidKeyException("GOST3410 private key required for signing");
                }

                this.key = (Gost3410PrivateKeyParameters)parameters;
            }
            else
            {
                if (!(parameters is Gost3410PublicKeyParameters))
                {
                    throw new InvalidKeyException("GOST3410 public key required for signing");
                }

                this.key = (Gost3410PublicKeyParameters)parameters;
            }
        }
Пример #9
0
        /**
         * initialise the RSA engine.
         *
         * @param forEncryption true if we are encrypting, false otherwise.
         * @param param the necessary RSA key parameters.
         */
        public virtual void Init(
            bool forEncryption,
            ICipherParameters param)
        {
            core.Init(forEncryption, param);

            if (param is ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                this.key = (RsaKeyParameters)rParam.Parameters;

                if (key is RsaPrivateCrtKeyParameters)
                {
                    this.random = rParam.Random;
                }
                else
                {
                    this.random = null;
                }
            }
            else
            {
                this.key = (RsaKeyParameters)param;

                if (key is RsaPrivateCrtKeyParameters)
                {
                    this.random = new SecureRandom();
                }
                else
                {
                    this.random = null;
                }
            }
        }
Пример #10
0
        private static IAsymmetricBlockCipher createCipher(bool forEncryption, IAsymmetricKey key, IParameters <Algorithm> parameters, SecureRandom random)
        {
            IAsymmetricBlockCipher engine = FipsRsa.ENGINE_PROVIDER.CreateEngine(EngineUsage.GENERAL);

            ICipherParameters lwParams;

            if (key is AsymmetricRsaPublicKey)
            {
                AsymmetricRsaPublicKey k = (AsymmetricRsaPublicKey)key;

                lwParams = FipsRsa.GetPublicKeyParameters(k, AsymmetricRsaKey.Usage.EncryptOrDecrypt);
            }
            else
            {
                AsymmetricRsaPrivateKey k = (AsymmetricRsaPrivateKey)key;

                lwParams = FipsRsa.GetPrivateKeyParameters(k, AsymmetricRsaKey.Usage.EncryptOrDecrypt);
            }

            if (parameters.Algorithm.Equals(WrapPkcs1v15.Algorithm))
            {
                engine = new Pkcs1Encoding(engine);
            }

            if (random != null)
            {
                lwParams = new ParametersWithRandom(lwParams, random);
            }

            engine.Init(forEncryption, lwParams);

            return(engine);
        }
Пример #11
0
        public static byte[] SignTransaction(byte[] data, byte[] privateKey)
        {
            ECDsaSigner        signer = new ECDsaSigner();
            X9ECParameters     spec   = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domain = new ECDomainParameters(spec.Curve, spec.G, spec.N);

            ECPrivateKeyParameters privateKeyParms =
                new ECPrivateKeyParameters(new BigInteger(1, privateKey), domain);
            ParametersWithRandom paramxs = new ParametersWithRandom(privateKeyParms);

            signer.Init(true, paramxs);

            var signature = signer.GenerateSignature(data); //sign and get R and S

            //return as DER format
            using (MemoryStream outStream = new MemoryStream(80))
            {
                DerSequenceGenerator seq = new DerSequenceGenerator(outStream);
                seq.AddObject(new DerInteger(signature[0]));                                                              //r
                seq.AddObject(new DerInteger(signature[1]));                                                              //s
                seq.AddObject(new DerInteger(GetRecoveryId(signature[0].ToByteArray(),
                                                           signature[1].ToByteArray(), data, GetPublicKey(privateKey)))); //v
                seq.Close();
                return(outStream.ToArray());
            }
        }
Пример #12
0
        public virtual void Init(bool forEncryption, ICipherParameters param)
        {
            this.mForEncryption = forEncryption;

            if (forEncryption)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                mECKey    = (ECKeyParameters)rParam.Parameters;
                mECParams = mECKey.Parameters;

                ECPoint s = ((ECPublicKeyParameters)mECKey).Q.Multiply(mECParams.H);
                if (s.IsInfinity)
                {
                    throw new ArgumentException("invalid key: [h]Q at infinity");
                }

                mRandom = rParam.Random;
            }
            else
            {
                mECKey    = (ECKeyParameters)param;
                mECParams = mECKey.Parameters;
            }

            mCurveLength = (mECParams.Curve.FieldSize + 7) / 8;
        }
Пример #13
0
        /// <summary>
        /// Creates ECDSA from imported data
        /// </summary>
        /// <param name="type">0 or 1 (1 faster)</param>
        /// <param name="forSign">if created for signing, otherwise for verifying</param>
        /// <param name="import">Imporeted public or private key</param>
        public ECDSAWrapper(int type, bool forSign, byte[] import)
        {
            this.initCurveandParams(type);

            if (forSign)
            {
                try
                {
                    //import - D (BigInteger)
                    SecureRandom           random            = new SecureRandom();
                    BigInteger             Drec              = new BigInteger(import);
                    ECPrivateKeyParameters ecPrivImported    = new ECPrivateKeyParameters(Drec, this.parameters);
                    ParametersWithRandom   ecPrivImportedpwr = new ParametersWithRandom(ecPrivImported, random);
                    this.ecdsa.Init(true, ecPrivImportedpwr);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error while creating ECDSAWrapper from import for signing", ex);
                }
            }
            else
            {
                try
                {
                    //import - Q (ECPoint)
                    ECPoint Qrec = this.ecCurve.DecodePoint(import);
                    ECPublicKeyParameters recPub = new ECPublicKeyParameters(Qrec, this.parameters);
                    this.ecdsa.Init(false, recPub);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error while creating ECDSAWrapperfom import for verifying", ex);
                }
            }
        }
Пример #14
0
        public void TestECDsa239bitBinary()
        {
            BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
            BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174");

            byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));

            SecureRandom k = FixedSecureRandom.From(kData);

            F2mCurve curve = new F2mCurve(
                239,                                                                                 // m
                36,                                                                                  //k
                new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16),  // a
                new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G
                new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"),                                                                  // n
                BigInteger.ValueOf(4));                                                                                                                                      // h

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
                parameters);

            ECDsaSigner          ecdsa = new ECDsaSigner();
            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ecdsa.Init(true, param);

            byte[]       message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig     = ecdsa.GenerateSignature(message);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                     + " expecting: " + r + SimpleTest.NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
                parameters);

            ecdsa.Init(false, pubKey);
            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Пример #15
0
        public virtual void  init(bool forSigning, CipherParameters param)
        {
            RSAKeyParameters kParam = null;

            if (param is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom)param;

                kParam = (RSAKeyParameters)p.getParameters();
                random = p.getRandom();
            }
            else
            {
                kParam = (RSAKeyParameters)param;
                if (forSigning)
                {
                    random = new SecureRandom();
                }
            }

            cipher.init(forSigning, kParam);

            emBits = kParam.getModulus().bitLength() - 1;

            block = new byte[(emBits + 7) / 8];

            reset();
        }
Пример #16
0
        public void TestECDsa192bitPrime()
        {
            BigInteger r = new BigInteger("3342403536405981729393488334694600415596881826869351677613");
            BigInteger s = new BigInteger("5735822328888155254683894997897571951568553642892029982342");

            byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("6140507067065001063065065565667405560006161556565665656654"));

            SecureRandom k = FixedSecureRandom.From(kData);

            FpCurve curve = new FpCurve(
                new BigInteger("6277101735386680763835789423207666416083908700390324961279"),           // q
                new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),                 // a
                new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16));                // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")),           // G
                new BigInteger("6277101735386680763835789423176059013767194773182842284081"));                 // n

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("651056770906015076056810763456358567190100156695615665659"),                 // d
                parameters);

            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ECDsaSigner ecdsa = new ECDsaSigner();

            ecdsa.Init(true, param);

            byte[]       message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig     = ecdsa.GenerateSignature(message);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                     + " expecting: " + r + SimpleTest.NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")),                 // Q
                parameters);

            ecdsa.Init(false, pubKey);
            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("verification fails");
            }
        }
Пример #17
0
        /// <summary>
        /// Encrypts a plain array of bytes using a public key
        /// </summary>
        /// <param name="publicKey">the public key used for encryption</param>
        /// <param name="plainBytes">the plain bytes to encrypt</param>
        /// <returns></returns>
        public byte[] EncryptBytes(byte[] publicKey, byte[] plainBytes)
        {
            var pubKey           = (ECPublicKeyParameters)CreateAsymmetricKeyParameterFromPublicKeyInfo(publicKey);
            var pubKeyWithRandom = new ParametersWithRandom(pubKey, new SecureRandom());

            cipher.Init(true, pubKeyWithRandom);
            return(cipher.ProcessBlock(plainBytes, 0, plainBytes.Length));
        }
Пример #18
0
 public static ICipherParameters WithRandom(ICipherParameters cp, SecureRandom random)
 {
     if (random != null)
     {
         cp = new ParametersWithRandom(cp, random);
     }
     return(cp);
 }
Пример #19
0
        public void TestECDsa239bitPrime()
        {
            BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176");
            BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783");

            byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));

            SecureRandom k = FixedSecureRandom.From(kData);

            FpCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),         // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),                 // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));                // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")),             // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"));                 // n

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"),                 // d
                parameters);

            ECDsaSigner          ecdsa = new ECDsaSigner();
            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ecdsa.Init(true, param);

            byte[]       message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig     = ecdsa.GenerateSignature(message);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                     + " expecting: " + r + SimpleTest.NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")),                 // Q
                parameters);

            ecdsa.Init(false, pubKey);
            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Пример #20
0
        public IStreamCalculator CreateCalculator()
        {
            var param = new ParametersWithRandom(privateKey, new SecureRandom());
            var gst   = new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411_2012_256Digest());

            gst.Init(true, param);

            return(new DefaultSignatureCalculator(gst));
        }
Пример #21
0
        public virtual void Init(bool forSigning, ICipherParameters parameters)
        {
            ICipherParameters baseParam;

            byte[] userID;

            if (parameters is ParametersWithID)
            {
                baseParam = ((ParametersWithID)parameters).Parameters;
                userID    = ((ParametersWithID)parameters).GetID();

                if (userID.Length >= 8192)
                {
                    throw new ArgumentException("SM2 user ID must be less than 2^16 bits long");
                }
            }
            else
            {
                baseParam = parameters;
                // the default value, string value is "1234567812345678"
                userID = Hex.Decode("31323334353637383132333435363738");
            }

            if (forSigning)
            {
                if (baseParam is ParametersWithRandom)
                {
                    ParametersWithRandom rParam = (ParametersWithRandom)baseParam;

                    ecKey    = (ECKeyParameters)rParam.Parameters;
                    ecParams = ecKey.Parameters;
                    kCalculator.Init(ecParams.N, rParam.Random);
                }
                else
                {
                    ecKey    = (ECKeyParameters)baseParam;
                    ecParams = ecKey.Parameters;
                    kCalculator.Init(ecParams.N, new SecureRandom());
                }
                pubPoint = CreateBasePointMultiplier().Multiply(ecParams.G, ((ECPrivateKeyParameters)ecKey).D).Normalize();
            }
            else
            {
                ecKey    = (ECKeyParameters)baseParam;
                ecParams = ecKey.Parameters;
                pubPoint = ((ECPublicKeyParameters)ecKey).Q;
            }

            digest.Reset();
            z = GetZ(userID);

            digest.BlockUpdate(z, 0, z.Length);
        }
Пример #22
0
        public override void Init(bool forEncryption, ICipherParameters parameters)
        {
            this.forEncryption = forEncryption;
            ParametersWithRandom parametersWithRandom = parameters as ParametersWithRandom;

            if (parametersWithRandom != null)
            {
                parameters = parametersWithRandom.Parameters;
            }
            Reset();
            cipher.Init(forEncryption, parameters);
        }
Пример #23
0
        public IStreamCalculator CreateCalculator()
        {
            ISigner           sig = SignerUtilities.GetSigner(algorithm);
            ICipherParameters cp  = privateKey;

            if (random != null)
            {
                cp = new ParametersWithRandom(cp, random);
            }
            sig.Init(true, cp);
            return(new SigCalculator(sig));
        }
Пример #24
0
        /**
         * sm2加密
         *
         */
        public static byte[] Encrypt(byte[] pubkey, byte[] srcData)
        {
            X9ECParameters        sm2p256v1        = GMNamedCurves.GetByName("sm2p256v1");
            SecureRandom          random           = new SecureRandom();
            ECDomainParameters    parameters       = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N);
            ECPublicKeyParameters pubKeyParameters = new ECPublicKeyParameters(sm2p256v1.Curve.DecodePoint(pubkey), parameters);
            SM2Engine             engine           = new SM2Engine();
            ParametersWithRandom  pwr = new ParametersWithRandom(pubKeyParameters, new SecureRandom());

            engine.Init(true, pwr);
            return(encodeSM2CipherToDER(engine.ProcessBlock(srcData, 0, srcData.Length)));
        }
Пример #25
0
        /**
         * Test Sign and Verify with test parameters
         * see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
         * gostR3410-2001-TestParamSet  P.46
         */
        private void ecGOST3410_TestParam()
        {
            SecureRandom random = new SecureRandom();

            BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p
            BigInteger mod_q = new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619");

            FpCurve curve = new FpCurve(
                mod_p,                                                                                           // p
                new BigInteger("7"),                                                                             // a
                new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414"), // b
                mod_q, BigInteger.One);

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),                                                                             // x
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")), // y
                mod_q);

            ECKeyPairGenerator        pGen     = new ECKeyPairGenerator();
            ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
                parameters,
                random);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);

            ECGost3410Signer ecgost3410 = new ECGost3410Signer();

            ecgost3410.Init(true, param);

            //get hash message using the digest GOST3411.
            byte[]         message  = Encoding.ASCII.GetBytes("Message for sign");
            Gost3411Digest gost3411 = new Gost3411Digest();

            gost3411.BlockUpdate(message, 0, message.Length);
            byte[] hashmessage = new byte[gost3411.GetDigestSize()];
            gost3411.DoFinal(hashmessage, 0);

            BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);

            ecgost3410.Init(false, pair.Public);

            if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Пример #26
0
 public virtual void Init(bool forEncryption, ICipherParameters param)
 {
     this.core.Init(forEncryption, param);
     if (param is ParametersWithRandom)
     {
         ParametersWithRandom parametersWithRandom = (ParametersWithRandom)param;
         this.key    = (RsaKeyParameters)parametersWithRandom.Parameters;
         this.random = parametersWithRandom.Random;
         return;
     }
     this.key    = (RsaKeyParameters)param;
     this.random = new SecureRandom();
 }
Пример #27
0
        /**
         * Method init
         *
         * @param forWrapping
         * @param param
         */
        public virtual void Init(
            bool forWrapping,
            ICipherParameters parameters)
        {
            this.forWrapping = forWrapping;
            this.engine      = new CbcBlockCipher(new DesEdeEngine());

            SecureRandom sr;

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom pr = (ParametersWithRandom)parameters;
                parameters = pr.Parameters;
                sr         = pr.Random;
            }
            else
            {
                sr = new SecureRandom();
            }

            if (parameters is KeyParameter)
            {
                this.param = (KeyParameter)parameters;
                if (this.forWrapping)
                {
                    // Hm, we have no IV but we want to wrap ?!?
                    // well, then we have to create our own IV.
                    this.iv = new byte[8];
                    sr.NextBytes(iv);

                    this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
                }
            }
            else if (parameters is ParametersWithIV)
            {
                if (!forWrapping)
                {
                    throw new ArgumentException("You should not supply an IV for unwrapping");
                }

                this.paramPlusIV = (ParametersWithIV)parameters;
                this.iv          = this.paramPlusIV.GetIV();
                this.param       = (KeyParameter)this.paramPlusIV.Parameters;

                if (this.iv.Length != 8)
                {
                    throw new ArgumentException("IV is not 8 octets", "parameters");
                }
            }
        }
Пример #28
0
 public void Init(bool forEncryption, ICipherParameters param)
 {
     if (param is ParametersWithRandom)
     {
         ParametersWithRandom parametersWithRandom = (ParametersWithRandom)param;
         random = parametersWithRandom.Random;
     }
     else
     {
         random = new SecureRandom();
     }
     engine.Init(forEncryption, param);
     this.forEncryption = forEncryption;
 }
Пример #29
0
        /**
         * sm2解密
         */
        public static byte[] Decrypt(byte[] privkey, byte[] srcData)
        {
            X9ECParameters     sm2p256v1  = GMNamedCurves.GetByName("sm2p256v1");
            SecureRandom       random     = new SecureRandom();
            ECDomainParameters parameters = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N);

            ECPrivateKeyParameters priKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, privkey), parameters);
            SM2Engine            engine             = new SM2Engine();
            ParametersWithRandom pwr = new ParametersWithRandom(priKeyParameters, new SecureRandom());

            engine.Init(false, priKeyParameters);
            byte[] c1c2c3 = decodeDERSM2Cipher(srcData);
            return(engine.ProcessBlock(c1c2c3, 0, c1c2c3.Length));
        }
Пример #30
0
        public virtual void Init(bool forSigning, ICipherParameters parameters)
        {
            //IL_0041: Unknown result type (might be due to invalid IL or missing references)
            //IL_007b: Unknown result type (might be due to invalid IL or missing references)
            RsaKeyParameters rsaKeyParameters;

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom parametersWithRandom = (ParametersWithRandom)parameters;
                rsaKeyParameters = (RsaKeyParameters)parametersWithRandom.Parameters;
                if (forSigning)
                {
                    random = parametersWithRandom.Random;
                }
            }
            else if (parameters is ParametersWithSalt)
            {
                if (!forSigning)
                {
                    throw new ArgumentException("ParametersWithSalt only valid for signing", "parameters");
                }
                ParametersWithSalt parametersWithSalt = (ParametersWithSalt)parameters;
                rsaKeyParameters = (RsaKeyParameters)parametersWithSalt.Parameters;
                standardSalt     = parametersWithSalt.GetSalt();
                if (standardSalt.Length != saltLength)
                {
                    throw new ArgumentException("Fixed salt is of wrong length");
                }
            }
            else
            {
                rsaKeyParameters = (RsaKeyParameters)parameters;
                if (forSigning)
                {
                    random = new SecureRandom();
                }
            }
            cipher.Init(forSigning, rsaKeyParameters);
            keyBits = rsaKeyParameters.Modulus.BitLength;
            block   = new byte[(keyBits + 7) / 8];
            if (trailer == 188)
            {
                mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 1];
            }
            else
            {
                mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 2];
            }
            Reset();
        }