Exemplo n.º 1
0
        private byte[] bigIntToBytes(
            BigInteger r)
        {
            int byteLength = X9IntegerConverter.GetByteLength(privKey.Parameters.G.X);

            return(X9IntegerConverter.IntegerToBytes(r, byteLength));
        }
Exemplo n.º 2
0
        /**
         * return the field element encoded with point compression. (S 4.3.6)
         */
        public override byte[] GetEncoded()
        {
            if (this.IsInfinity)
            {
                return(new byte[1]);
            }

            // Note: some of the tests rely on calculating byte length from the field element
            // (since the test cases use mismatching fields for curve/elements)
            var byteLength = X9IntegerConverter.GetByteLength(this.X);
            var x          = X9IntegerConverter.IntegerToBytes(this.X.ToBigInteger(), byteLength);

            byte[] po;

            if (this.IsCompressed)
            {
                po    = new byte[1 + x.Length];
                po[0] = (byte)(YTilde ? 0x03 : 0x02);
            }
            else
            {
                var y = X9IntegerConverter.IntegerToBytes(this.Y.ToBigInteger(), byteLength);
                po = new byte[1 + x.Length + y.Length];

                po[0] = 0x04;

                y.CopyTo(po, 1 + x.Length);
            }

            x.CopyTo(po, 1);

            return(po);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creates an ECDSA instance by recovering a public key given a hash, recovery ID, and r and s components of the resulting signature of the hash. Throws an exception if recovery is not possible.
        /// </summary>
        /// <param name="hash">The hash of the data which was signed.</param>
        /// <param name="recoveryId">The recovery ID of ECDSA during signing.</param>
        /// <param name="ecdsa_r">The r component of the ECDSA signature for the provided hash.</param>
        /// <param name="ecdsa_s">The s component of the ECDSA signature for the provided hash.</param>
        /// <returns>Returns the quotient/public key which was used to sign this hash.</returns>
        public static new EthereumEcdsaBouncyCastle Recover(Span <byte> hash, byte recoveryId, BigInteger ecdsa_r, BigInteger ecdsa_s)
        {
            // Source: http://www.secg.org/sec1-v2.pdf (Section 4.1.6 - Public Key Recovery Operation)

            // Recovery ID must be between 0 and 4 (0 and 1 is all that should be used, but we support multiple cases in case)
            if (recoveryId < 0 || recoveryId > 3)
            {
                throw new ArgumentException($"ECDSA public key recovery must have a v parameter between [0, 3]. Value provided is {recoveryId.ToString(CultureInfo.InvariantCulture)}");
            }

            // NOTES:
            // First bit of recoveryID being set means y is odd, otherwise it is even.
            // The second bit indicates which item of the two to choose.

            // If the hash is null, we'll assume it's a zero length byte array
            if (hash == null)
            {
                hash = Array.Empty <byte>();
            }

            // Obtain our elliptic curve parameters
            Org.BouncyCastle.Math.BigInteger r = ecdsa_r.ToBouncyCastleBigInteger();
            Org.BouncyCastle.Math.BigInteger s = ecdsa_s.ToBouncyCastleBigInteger();
            Org.BouncyCastle.Math.BigInteger j = Org.BouncyCastle.Math.BigInteger.ValueOf((long)recoveryId >> 1);
            Org.BouncyCastle.Math.BigInteger x = j.Multiply(Secp256k1Curve.Parameters.N).Add(r);

            // To obtain our curve point R, we decode it with an extra byte for Y descriptor which mentions if Y is even or odd.
            int curveLength = X9IntegerConverter.GetByteLength(Secp256k1Curve.Parameters.Curve);

            byte[] xdata = X9IntegerConverter.IntegerToBytes(x, curveLength + 1);
            xdata[0] = (byte)(0x2 | (recoveryId & 1));
            ECPoint r1 = Secp256k1Curve.Parameters.Curve.DecodePoint(xdata);

            // nR should be infinity.
            if (!r1.Multiply(Secp256k1Curve.Parameters.N).IsInfinity)
            {
                throw new ArgumentException("ECDSA's nR should be the point at infinity.");
            }

            // We obtain an integer representation of our hash.
            Org.BouncyCastle.Math.BigInteger e = new Org.BouncyCastle.Math.BigInteger(1, hash.ToArray());

            // Next we'll want the multiplicative inverse of r (~r)
            Org.BouncyCastle.Math.BigInteger rInverse = r.ModInverse(Secp256k1Curve.Parameters.N);

            // Next we get the additive inverse of our hash, subtracting it from zero, and bounding it accordingly.
            Org.BouncyCastle.Math.BigInteger eAddInverse = Org.BouncyCastle.Math.BigInteger.Zero.Subtract(e).Mod(Secp256k1Curve.Parameters.N);

            // Using the inverse of r we have, we can multiply it by s to get our ~r * s.
            Org.BouncyCastle.Math.BigInteger rsInverse = rInverse.Multiply(s).Mod(Secp256k1Curve.Parameters.N);

            // Using the inverse of r we have, and the inverse of e, we can have ~r * -e
            Org.BouncyCastle.Math.BigInteger reInverse = rInverse.Multiply(eAddInverse).Mod(Secp256k1Curve.Parameters.N);

            // Q = ((~r * s) * R) + ((~r * -e) * G) => (~r * sR) + (~r * -eG) => ~r (sR - eG)
            ECPoint q = ECAlgorithms.SumOfTwoMultiplies(Secp256k1Curve.Parameters.G, reInverse, r1, rsInverse).Normalize();

            // Obtain our public key from this
            return(new EthereumEcdsaBouncyCastle(Secp256k1Curve.Parameters.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false), EthereumEcdsaKeyType.Public));
        }
Exemplo n.º 4
0
        /**
         * return the field element encoded with point compression. (S 4.3.6)
         */
        public override byte[] GetEncoded()
        {
            if (this.IsInfinity)
            {
                throw new ArithmeticException("Point at infinity cannot be encoded");
            }

            int qLength = X9IntegerConverter.GetByteLength(x);

            byte[] X = X9IntegerConverter.IntegerToBytes(this.X.ToBigInteger(), qLength);
            byte[] PO;

            if (withCompression)
            {
                PO = new byte[1 + X.Length];

                PO[0] = (byte)(this.Y.ToBigInteger().TestBit(0) ? 0x03 : 0x02);
            }
            else
            {
                byte[] Y = X9IntegerConverter.IntegerToBytes(this.Y.ToBigInteger(), qLength);
                PO = new byte[1 + X.Length + Y.Length];

                PO[0] = 0x04;

                Y.CopyTo(PO, 1 + X.Length);
            }

            X.CopyTo(PO, 1);

            return(PO);
        }
Exemplo n.º 5
0
 private static ECPoint DecompressKey(BigInteger xBN, bool yBit)
 {
   var curve = Secp256k1.Curve;
   var compEnc = X9IntegerConverter.IntegerToBytes(xBN, 1 + X9IntegerConverter.GetByteLength(curve));
   compEnc[0] = (byte)(yBit ? 0x03 : 0x02);
   return curve.DecodePoint(compEnc);
 }
Exemplo n.º 6
0
        /**
         * return the field element encoded with point compression. (S 4.3.6)
         */
        public override byte[] GetEncoded(bool compressed)
        {
            if (this.IsInfinity)
            {
                return(new byte[1]);
            }

            // Note: some of the tests rely on calculating byte length from the field element
            // (since the test cases use mismatching fields for curve/elements)
            int byteLength = X9IntegerConverter.GetByteLength(x);

            byte[] X = X9IntegerConverter.IntegerToBytes(this.X.ToBigInteger(), byteLength);
            byte[] PO;

            if (compressed)
            {
                PO = new byte[1 + X.Length];

                PO[0] = (byte)(YTilde ? 0x03 : 0x02);
            }
            else
            {
                byte[] Y = X9IntegerConverter.IntegerToBytes(this.Y.ToBigInteger(), byteLength);
                PO = new byte[1 + X.Length + Y.Length];

                PO[0] = 0x04;

                Y.CopyTo(PO, 1 + X.Length);
            }

            X.CopyTo(PO, 1);

            return(PO);
        }
Exemplo n.º 7
0
        private static ECPoint DecompressKey(NBitcoin.BouncyCastle.Math.BigInteger xBN, bool yBit)
        {
            var curve = ECKey.Secp256k1.Curve;

            byte[] compEnc = X9IntegerConverter.IntegerToBytes(xBN, 1 + X9IntegerConverter.GetByteLength(curve));
            compEnc[0] = (byte)(yBit ? 0x03 : 0x02);
            return(curve.DecodePoint(compEnc));
        }
Exemplo n.º 8
0
        private static ECPoint DecompressKey(BigInteger xBn, bool yBit)
        {
            var byteLength = 1 + X9IntegerConverter.GetByteLength(_curve.Curve);
            var compEnc    = X9IntegerConverter.IntegerToBytes(xBn, byteLength);

            compEnc[0] = (byte)(yBit ? 0x03 : 0x02);
            return(_curve.Curve.DecodePoint(compEnc));
        }
Exemplo n.º 9
0
        public static byte GetRecoveryId(byte[] sigR, byte[] sigS, byte[] message, byte[] publicKey)
        {
            //ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1");
            X9ECParameters spec = ECNamedCurveTable.GetByName("secp256k1");

            BigInteger pointN = spec.N;

            for (int recoveryId = 0; recoveryId < 2; recoveryId++)
            {
                try
                {
                    BigInteger pointX = new BigInteger(1, sigR);

                    byte[] compEnc =
                        X9IntegerConverter.IntegerToBytes(pointX, 1 + X9IntegerConverter.GetByteLength(spec.Curve));
                    compEnc[0] = (byte)((recoveryId & 1) == 1 ? 0x03 : 0x02);
                    ECPoint pointR = spec.Curve.DecodePoint(compEnc);
                    if (!pointR.Multiply(pointN).IsInfinity)
                    {
                        continue;
                    }

                    BigInteger pointE        = new BigInteger(1, message);
                    BigInteger pointEInv     = BigInteger.Zero.Subtract(pointE).Mod(pointN);
                    BigInteger pointRInv     = new BigInteger(1, sigR).ModInverse(pointN);
                    BigInteger srInv         = pointRInv.Multiply(new BigInteger(1, sigS)).Mod(pointN);
                    BigInteger pointEInvRInv = pointRInv.Multiply(pointEInv).Mod(pointN);
                    ECPoint    pointQ        = ECAlgorithms.SumOfTwoMultiplies(spec.G, pointEInvRInv, pointR, srInv);
                    byte[]     pointQBytes   = pointQ.GetEncoded(false);
                    bool       matchedKeys   = true;
                    for (int j = 0; j < publicKey.Length; j++)
                    {
                        if (pointQBytes[j] != publicKey[j])
                        {
                            matchedKeys = false;
                            break;
                        }
                    }

                    if (!matchedKeys)
                    {
                        continue;
                    }

                    return((byte)(0xFF & recoveryId));
                }
                catch (Exception e)
                {
                    continue;
                    Console.WriteLine(" Failed: GET recoveryID");
                }
            }

            return((byte)0xFF);
        }
Exemplo n.º 10
0
        public static ECPoint DecompressKey(string compressedKey)
        {
            string     x      = compressedKey.Substring(0, 64);
            BigInteger xCoord = new BigInteger(x, 16);
            int        yOdd   = int.Parse(compressedKey.Substring(64));
            bool       yBit   = Convert.ToBoolean(yOdd);

            var curve   = Secp256k1.Curve;
            var encoded = X9IntegerConverter.IntegerToBytes(
                xCoord, 1 + X9IntegerConverter.GetByteLength(curve));

            encoded[0] = (byte)(yBit ? 0x03 : 0x02);
            return(curve.DecodePoint(encoded));
        }
Exemplo n.º 11
0
        /* (non-Javadoc)
         * @see Org.BouncyCastle.Math.EC.ECPoint#getEncoded()
         */
        public override byte[] GetEncoded()
        {
            if (this.IsInfinity)
            {
                throw new ArithmeticException("Point at infinity cannot be encoded");
            }

            int byteCount = X9IntegerConverter.GetByteLength(this.x);

            byte[] X = X9IntegerConverter.IntegerToBytes(this.X.ToBigInteger(), byteCount);
            byte[] PO;

            if (withCompression)
            {
                // See X9.62 4.3.6 and 4.2.2
                PO = new byte[byteCount + 1];

                PO[0] = 0x02;
                // X9.62 4.2.2 and 4.3.6:
                // if x = 0 then ypTilde := 0, else ypTilde is the rightmost
                // bit of y * x^(-1)
                // if ypTilde = 0, then PC := 02, else PC := 03
                // Note: PC === PO[0]
                if (this.X.ToBigInteger().SignValue != 0)
                {
                    if (this.Y.Multiply(this.X.Invert())
                        .ToBigInteger().TestBit(0))
                    {
                        // ypTilde = 1, hence PC = 03
                        PO[0] = 0x03;
                    }
                }

                Array.Copy(X, 0, PO, 1, byteCount);
            }
            else
            {
                byte[] Y = X9IntegerConverter.IntegerToBytes(this.Y.ToBigInteger(), byteCount);

                PO = new byte[byteCount + byteCount + 1];

                PO[0] = 0x04;
                Array.Copy(X, 0, PO, 1, byteCount);
                Array.Copy(Y, 0, PO, byteCount + 1, byteCount);
            }

            return(PO);
        }
Exemplo n.º 12
0
        private KeyParameter CalculateAgreedWrapKey(
            string wrapAlg,
            AsymmetricKeyParameter senderPublicKey,
            AsymmetricKeyParameter receiverPrivateKey)
        {
            DerObjectIdentifier agreeAlgID = keyEncAlg.Algorithm;

            ICipherParameters senderPublicParams    = senderPublicKey;
            ICipherParameters receiverPrivateParams = receiverPrivateKey;

            if (agreeAlgID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                byte[] ukmEncoding        = info.UserKeyingMaterial.GetOctets();
                MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.GetInstance(
                    Asn1Object.FromByteArray(ukmEncoding));

                AsymmetricKeyParameter ephemeralKey = GetPublicKeyFromOriginatorPublicKey(
                    receiverPrivateKey, ukm.EphemeralPublicKey);

                senderPublicParams = new MqvPublicParameters(
                    (ECPublicKeyParameters)senderPublicParams,
                    (ECPublicKeyParameters)ephemeralKey);
                receiverPrivateParams = new MqvPrivateParameters(
                    (ECPrivateKeyParameters)receiverPrivateParams,
                    (ECPrivateKeyParameters)receiverPrivateParams);
            }

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                agreeAlgID, wrapAlg);

            agreement.Init(receiverPrivateParams);
            BigInteger agreedValue = agreement.CalculateAgreement(senderPublicParams);

            int wrapKeySize = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;

            byte[] wrapKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, wrapKeySize);
            return(ParameterUtilities.CreateKeyParameter(wrapAlg, wrapKeyBytes));
        }
        private KeyParameter CalculateAgreedWrapKey(string wrapAlg, AsymmetricKeyParameter senderPublicKey, AsymmetricKeyParameter receiverPrivateKey)
        {
            DerObjectIdentifier objectID          = this.keyEncAlg.ObjectID;
            ICipherParameters   cipherParameters  = senderPublicKey;
            ICipherParameters   cipherParameters2 = receiverPrivateKey;

            if (objectID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                byte[] octets = this.info.UserKeyingMaterial.GetOctets();
                MQVuserKeyingMaterial  instance = MQVuserKeyingMaterial.GetInstance(Asn1Object.FromByteArray(octets));
                AsymmetricKeyParameter publicKeyFromOriginatorPublicKey = this.GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, instance.EphemeralPublicKey);
                cipherParameters  = new MqvPublicParameters((ECPublicKeyParameters)cipherParameters, (ECPublicKeyParameters)publicKeyFromOriginatorPublicKey);
                cipherParameters2 = new MqvPrivateParameters((ECPrivateKeyParameters)cipherParameters2, (ECPrivateKeyParameters)cipherParameters2);
            }
            IBasicAgreement basicAgreementWithKdf = AgreementUtilities.GetBasicAgreementWithKdf(objectID, wrapAlg);

            basicAgreementWithKdf.Init(cipherParameters2);
            BigInteger s       = basicAgreementWithKdf.CalculateAgreement(cipherParameters);
            int        qLength = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;

            byte[] keyBytes = X9IntegerConverter.IntegerToBytes(s, qLength);
            return(ParameterUtilities.CreateKeyParameter(wrapAlg, keyBytes));
        }
Exemplo n.º 14
0
        /**
         * Recover the public key that corresponds to the private key, which signed this message.
         */
        public static byte[] RecoverPublicKey(byte[] sigR, byte[] sigS, byte[] sigV, byte[] message)
        {
            //ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1");
            X9ECParameters spec = ECNamedCurveTable.GetByName("secp256k1");

            BigInteger pointN = spec.N;

            try
            {
                BigInteger pointX = new BigInteger(1, sigR);


                byte[] compEnc =
                    X9IntegerConverter.IntegerToBytes(pointX, 1 + X9IntegerConverter.GetByteLength(spec.Curve));
                compEnc[0] = (byte)((sigV[0] & 1) == 1 ? 0x03 : 0x02);
                ECPoint pointR = spec.Curve.DecodePoint(compEnc);
                if (!pointR.Multiply(pointN).IsInfinity)
                {
                    return(new byte[0]);
                }

                BigInteger pointE        = new BigInteger(1, message);
                BigInteger pointEInv     = BigInteger.Zero.Subtract(pointE).Mod(pointN);
                BigInteger pointRInv     = new BigInteger(1, sigR).ModInverse(pointN);
                BigInteger srInv         = pointRInv.Multiply(new BigInteger(1, sigS)).Mod(pointN);
                BigInteger pointEInvRInv = pointRInv.Multiply(pointEInv).Mod(pointN);
                ECPoint    pointQ        = ECAlgorithms.SumOfTwoMultiplies(spec.G, pointEInvRInv, pointR, srInv);
                byte[]     pointQBytes   = pointQ.GetEncoded(false);
                return(pointQBytes);
            }
            catch (Exception e)
            {
            }

            return(new byte[0]);
        }
Exemplo n.º 15
0
    private byte[] BigIntToBytes(BigInteger r)
    {
        int byteLength = X9IntegerConverter.GetByteLength(privParams.StaticPrivateKey.Parameters.Curve);

        return(X9IntegerConverter.IntegerToBytes(r, byteLength));
    }
        private byte[] BigIntToBytes(IBigInteger r)
        {
            var byteLength = X9IntegerConverter.GetByteLength(PrivKey.Parameters.G.X);

            return(X9IntegerConverter.IntegerToBytes(r, byteLength));
        }
Exemplo n.º 17
0
    public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
    {
        byte[] key = contentEncryptionKey.GetKey();
        AsymmetricKeyParameter    @public          = senderKeyPair.Public;
        ICipherParameters         cipherParameters = senderKeyPair.Private;
        OriginatorIdentifierOrKey originator;

        try
        {
            originator = new OriginatorIdentifierOrKey(CreateOriginatorPublicKey(@public));
        }
        catch (IOException arg)
        {
            throw new InvalidKeyException("cannot extract originator public key: " + arg);
        }
        Asn1OctetString ukm = null;

        if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
        {
            try
            {
                IAsymmetricCipherKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                keyPairGenerator.Init(((ECPublicKeyParameters)@public).CreateKeyGenerationParameters(random));
                AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair();
                ukm = new DerOctetString(new MQVuserKeyingMaterial(CreateOriginatorPublicKey(asymmetricCipherKeyPair.Public), null));
                cipherParameters = new MqvPrivateParameters((ECPrivateKeyParameters)cipherParameters, (ECPrivateKeyParameters)asymmetricCipherKeyPair.Private, (ECPublicKeyParameters)asymmetricCipherKeyPair.Public);
            }
            catch (IOException arg2)
            {
                throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + arg2);
            }
            catch (SecurityUtilityException arg3)
            {
                throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + arg3);
            }
        }
        DerSequence         parameters             = new DerSequence(keyEncryptionOID, DerNull.Instance);
        AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(keyAgreementOID, parameters);
        Asn1EncodableVector asn1EncodableVector    = new Asn1EncodableVector();

        foreach (X509Certificate recipientCert in recipientCerts)
        {
            TbsCertificateStructure instance;
            try
            {
                instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
            }
            catch (Exception)
            {
                throw new ArgumentException("can't extract TBS structure from certificate");
            }
            IssuerAndSerialNumber       issuerSerial      = new IssuerAndSerialNumber(instance.Issuer, instance.SerialNumber.Value);
            KeyAgreeRecipientIdentifier id                = new KeyAgreeRecipientIdentifier(issuerSerial);
            ICipherParameters           cipherParameters2 = recipientCert.GetPublicKey();
            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                cipherParameters2 = new MqvPublicParameters((ECPublicKeyParameters)cipherParameters2, (ECPublicKeyParameters)cipherParameters2);
            }
            IBasicAgreement basicAgreementWithKdf = AgreementUtilities.GetBasicAgreementWithKdf(keyAgreementOID, keyEncryptionOID.Id);
            basicAgreementWithKdf.Init(new ParametersWithRandom(cipherParameters, random));
            BigInteger   s           = basicAgreementWithKdf.CalculateAgreement(cipherParameters2);
            int          qLength     = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
            byte[]       keyBytes    = X9IntegerConverter.IntegerToBytes(s, qLength);
            KeyParameter parameters2 = ParameterUtilities.CreateKeyParameter(keyEncryptionOID, keyBytes);
            IWrapper     wrapper     = Helper.CreateWrapper(keyEncryptionOID.Id);
            wrapper.Init(forWrapping: true, new ParametersWithRandom(parameters2, random));
            byte[]          str          = wrapper.Wrap(key, 0, key.Length);
            Asn1OctetString encryptedKey = new DerOctetString(str);
            asn1EncodableVector.Add(new RecipientEncryptedKey(id, encryptedKey));
        }
        return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncryptionAlgorithm, new DerSequence(asn1EncodableVector))));
    }
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            AsymmetricKeyParameter senderPublicKey     = senderKeyPair.Public;
            ICipherParameters      senderPrivateParams = senderKeyPair.Private;


            OriginatorIdentifierOrKey originator;

            try
            {
                originator = new OriginatorIdentifierOrKey(
                    CreateOriginatorPublicKey(senderPublicKey));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }


            Asn1OctetString ukm = null;

            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator ephemKPG =
                        GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    ephemKPG.Init(
                        ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random));

                    AsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair();

                    ukm = new DerOctetString(
                        new MQVuserKeyingMaterial(
                            CreateOriginatorPublicKey(ephemKP.Public), null));

                    senderPrivateParams = new MqvPrivateParameters(
                        (ECPrivateKeyParameters)senderPrivateParams,
                        (ECPrivateKeyParameters)ephemKP.Private,
                        (ECPublicKeyParameters)ephemKP.Public);
                }
                catch (IOException e)
                {
                    throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e);
                }
                catch (SecurityUtilityException e)
                {
                    throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e);
                }
            }


            DerSequence paramSeq = new DerSequence(
                keyEncryptionOID,
                DerNull.Instance);
            AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq);


            Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector();

            foreach (X509Certificate recipientCert in recipientCerts)
            {
                TbsCertificateStructure tbsCert;
                try
                {
                    tbsCert = TbsCertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
                }
                catch (Exception)
                {
                    throw new ArgumentException("can't extract TBS structure from certificate");
                }

                // TODO Should there be a SubjectKeyIdentifier-based alternative?
                IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(
                    tbsCert.Issuer, tbsCert.SerialNumber.Value);
                KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial);

                ICipherParameters recipientPublicParams = recipientCert.GetPublicKey();
                if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                {
                    recipientPublicParams = new MqvPublicParameters(
                        (ECPublicKeyParameters)recipientPublicParams,
                        (ECPublicKeyParameters)recipientPublicParams);
                }

                // Use key agreement to choose a wrap key for this recipient
                IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    keyAgreementOID, keyEncryptionOID.Id);
                keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random));
                BigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams);

                int          keyEncryptionKeySize  = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                byte[]       keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize);
                KeyParameter keyEncryptionKey      = ParameterUtilities.CreateKeyParameter(
                    keyEncryptionOID, keyEncryptionKeyBytes);

                // Wrap the content encryption key with the agreement key
                IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id);
                keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
                byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

                Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes);

                recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey));
            }

            return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg,
                                                               new DerSequence(recipientEncryptedKeys))));
        }
Exemplo n.º 19
0
 public static ECPoint DecompressKey(BigInteger xBN, bool yBit)
 {
     byte[] compEnc = X9IntegerConverter.IntegerToBytes(xBN, 1 + X9IntegerConverter.GetByteLength(ECKeyPair.CURVE.Curve));
     compEnc[0] = (byte)(yBit ? 0x03 : 0x02);
     return(ECKeyPair.CURVE.Curve.DecodePoint(compEnc));
 }
Exemplo n.º 20
0
        private void EncodePublicKey()
        {
            X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3);

            if (X9IntegerConverter.GetByteLength(ecP.Curve) != 30)
            {
                Fail("wrong byte length reported for curve");
            }

            if (ecP.Curve.FieldSize != 239)
            {
                Fail("wrong field size reported for curve");
            }

            //
            // named curve
            //
            X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1);

            X9ECPoint pPoint = new X9ECPoint(
                new FPPoint(ecP.Curve, new FPFieldElement(BigInteger.Two, BigInteger.One),
                            new FPFieldElement(BigInteger.ValueOf(4), BigInteger.ValueOf(3)),
                            true));

            Asn1OctetString p = (Asn1OctetString)pPoint.ToAsn1Object();

            if (p == null)
            {
                Fail("failed to convert to ASN.1");
            }

            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets());

            if (!Arrays.AreEqual(info.GetEncoded(), namedPub))
            {
                Fail("failed public named generation");
            }

            Asn1Object o = Asn1Object.FromByteArray(namedPub);

            if (!info.Equals(o))
            {
                Fail("failed public named equality");
            }

            //
            // explicit curve parameters
            //
            _params = new X962Parameters(ecP);

            info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets());

            if (!Arrays.AreEqual(info.GetEncoded(), expPub))
            {
                Fail("failed public explicit generation");
            }

            o = Asn1Object.FromByteArray(expPub);

            if (!info.Equals(o))
            {
                Fail("failed public explicit equality");
            }
        }
Exemplo n.º 21
0
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            //IL_002f: Expected O, but got Unknown
            //IL_00c8: Expected O, but got Unknown
            //IL_0169: Unknown result type (might be due to invalid IL or missing references)
            byte[] key = contentEncryptionKey.GetKey();
            AsymmetricKeyParameter    @public          = senderKeyPair.Public;
            ICipherParameters         cipherParameters = senderKeyPair.Private;
            OriginatorIdentifierOrKey originator;

            try
            {
                originator = new OriginatorIdentifierOrKey(CreateOriginatorPublicKey(@public));
            }
            catch (IOException val)
            {
                IOException val2 = val;
                throw new InvalidKeyException(string.Concat((object)"cannot extract originator public key: ", (object)val2));
            }
            Asn1OctetString ukm = null;

            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    keyPairGenerator.Init(((ECPublicKeyParameters)@public).CreateKeyGenerationParameters(random));
                    AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair();
                    ukm = new DerOctetString(new MQVuserKeyingMaterial(CreateOriginatorPublicKey(asymmetricCipherKeyPair.Public), null));
                    cipherParameters = new MqvPrivateParameters((ECPrivateKeyParameters)cipherParameters, (ECPrivateKeyParameters)asymmetricCipherKeyPair.Private, (ECPublicKeyParameters)asymmetricCipherKeyPair.Public);
                }
                catch (IOException val3)
                {
                    IOException val4 = val3;
                    throw new InvalidKeyException(string.Concat((object)"cannot extract MQV ephemeral public key: ", (object)val4));
                }
                catch (SecurityUtilityException ex)
                {
                    throw new InvalidKeyException(string.Concat((object)"cannot determine MQV ephemeral key pair parameters from public key: ", (object)ex));
                }
            }
            DerSequence         parameters             = new DerSequence(keyEncryptionOID, DerNull.Instance);
            AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(keyAgreementOID, parameters);
            Asn1EncodableVector asn1EncodableVector    = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)recipientCerts).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    X509Certificate         x509Certificate = (X509Certificate)enumerator.get_Current();
                    TbsCertificateStructure instance;
                    try
                    {
                        instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(x509Certificate.GetTbsCertificate()));
                    }
                    catch (global::System.Exception)
                    {
                        throw new ArgumentException("can't extract TBS structure from certificate");
                    }
                    IssuerAndSerialNumber       issuerSerial      = new IssuerAndSerialNumber(instance.Issuer, instance.SerialNumber.Value);
                    KeyAgreeRecipientIdentifier id                = new KeyAgreeRecipientIdentifier(issuerSerial);
                    ICipherParameters           cipherParameters2 = x509Certificate.GetPublicKey();
                    if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                    {
                        cipherParameters2 = new MqvPublicParameters((ECPublicKeyParameters)cipherParameters2, (ECPublicKeyParameters)cipherParameters2);
                    }
                    IBasicAgreement basicAgreementWithKdf = AgreementUtilities.GetBasicAgreementWithKdf(keyAgreementOID, keyEncryptionOID.Id);
                    basicAgreementWithKdf.Init(new ParametersWithRandom(cipherParameters, random));
                    BigInteger   s           = basicAgreementWithKdf.CalculateAgreement(cipherParameters2);
                    int          qLength     = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                    byte[]       keyBytes    = X9IntegerConverter.IntegerToBytes(s, qLength);
                    KeyParameter parameters2 = ParameterUtilities.CreateKeyParameter(keyEncryptionOID, keyBytes);
                    IWrapper     wrapper     = Helper.CreateWrapper(keyEncryptionOID.Id);
                    wrapper.Init(forWrapping: true, new ParametersWithRandom(parameters2, random));
                    byte[]          str          = wrapper.Wrap(key, 0, key.Length);
                    Asn1OctetString encryptedKey = new DerOctetString(str);
                    asn1EncodableVector.Add(new RecipientEncryptedKey(id, encryptedKey));
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncryptionAlgorithm, new DerSequence(asn1EncodableVector))));
        }
Exemplo n.º 22
0
        private void EncodePublicKey()
        {
            X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3);

            if (X9IntegerConverter.GetByteLength(ecP.Curve) != 30)
            {
                Fail("wrong byte length reported for curve");
            }

            if (ecP.Curve.FieldSize != 239)
            {
                Fail("wrong field size reported for curve");
            }

            //
            // named curve
            //
            X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1);
            ECPoint        point   = ecP.G.Multiply(BigInteger.ValueOf(100));

            DerOctetString p = new DerOctetString(point.GetEncoded(true));

            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets());

            if (!Arrays.AreEqual(info.GetEncoded(), namedPub))
            {
                Fail("failed public named generation");
            }

            X9ECPoint x9P = new X9ECPoint(ecP.Curve, p);

            if (!Arrays.AreEqual(p.GetOctets(), x9P.Point.GetEncoded()))
            {
                Fail("point encoding not preserved");
            }

            Asn1Object o = Asn1Object.FromByteArray(namedPub);

            if (!info.Equals(o))
            {
                Fail("failed public named equality");
            }

            //
            // explicit curve parameters
            //
            _params = new X962Parameters(ecP);

            info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets());

            if (!Arrays.AreEqual(info.GetEncoded(), expPub))
            {
                Fail("failed public explicit generation");
            }

            o = Asn1Object.FromByteArray(expPub);

            if (!info.Equals(o))
            {
                Fail("failed public explicit equality");
            }
        }