public void DKIMSign(ISigner signer, CanonicalizationType headerCanonicalization, CanonicalizationType bodyCanonicalization, HashingAlgorithm hashAlgorithm, string domain, string selector)
        {
            if (IsSigned)
                throw new InvalidOperationException("Message already have DKIM header.");
            IsSigned = true;

            string hashtype = hashAlgorithm == HashingAlgorithm.RSASha1 ? "sha1" : "sha256";

            StringBuilder dkim = new StringBuilder(300)
                .Append("v=1;") // version
                .Append("a=").Append("rsa-").Append(hashtype).Append(";") // hash algorithm
                .Append("c=").Append(string.Format("{0}/{1}", headerCanonicalization, bodyCanonicalization).ToLower()).Append(";") // canonicalization types headers/body
                .Append("d=").Append(domain).Append(";") // domain for diim check
                .Append("s=").Append(selector).Append(";") // TXT record selector
                .Append("t=").Append(Convert.ToInt64((DateTime.Now.ToUniversalTime() - DateTime.SpecifyKind(DateTime.Parse("00:00:00 January 1, 1970"), DateTimeKind.Utc)).TotalSeconds).ToString()).Append(";") // creation time
                .Append("bh=").Append(GetBodyHash(bodyCanonicalization, hashtype)).Append(";"); // body hash

            var headers = ComputedHeaders;

            List<string> h = new List<string>();
            foreach (string header in headers)
                foreach (string value in headers.GetValues(header))
                    h.Add(header);

            dkim.Append("h=").Append(string.Join(":", h)).Append(";") // headers for hashing
            .Append("b="); // signature data

            var canonialized = DKIMCanonicalizer.CanonicalizeHeader(headerCanonicalization, headers) + "dkim-signature:" + dkim.ToString();
            var bytes = (HeadersEncoding ?? Encoding.UTF8).GetBytes(canonialized);

            lock (signer)
            {
                signer.BlockUpdate(bytes, 0, bytes.Length);
                bytes = signer.GenerateSignature();//computing signature
                signer.Reset();
            }

            dkim.Append(Convert.ToBase64String(bytes));

            Headers.Add("dkim-signature", dkim.ToString());// adding DKIM header
        }
示例#2
0
        public void TestECDsa239BitBinary()
        {
            BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
            BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174");

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

            SecureRandom k = FixedSecureRandom.From(kData);

//			EllipticCurve curve = new EllipticCurve(
//				new ECFieldF2m(239, // m
//							new int[] { 36 }), // k
//				new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a
//				new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b
            ECCurve curve = new F2mCurve(
                239,                                                                                 // m
                36,                                                                                  // k
                new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16),  // a
                new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b

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

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

            ECPublicKeyParameters vKey = new ECPublicKeyParameters(
                "ECDSA",
//				ECPointUtil.DecodePoint(curve, Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
                curve.DecodePoint(Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
                parameters);

            ISigner sgr = SignerUtilities.GetSigner("ECDSA");

//			KeyFactory f = KeyFactory.getInstance("ECDSA");
//			AsymmetricKeyParameter sKey = f.generatePrivate(priKeySpec);
//			AsymmetricKeyParameter vKey = f.generatePublic(pubKeySpec);
            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("239 Bit EC verification failed");
            }

            BigInteger[] sig = derDecode(sigBytes);

            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]);
            }
        }
示例#3
0
            public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm,
                                       byte[] calculatedDigest)
            {
                try
                {
                    string digestName    = Helper.GetDigestAlgName(_digestOID);
                    string signatureName = digestName + "with" + _encName;

//					AlgorithmIdentifier digAlgId = DigestAlgorithmID;
//
//					byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)];
//					outer._digests[_digestOID] = hash.Clone();

                    byte[] bytesToSign = calculatedDigest;

                    /* RFC 3852 5.4
                     * The result of the message digest calculation process depends on
                     * whether the signedAttrs field is present.  When the field is absent,
                     * the result is just the message digest of the content as described
                     *
                     * above.  When the field is present, however, the result is the message
                     * digest of the complete DER encoding of the SignedAttrs value
                     * contained in the signedAttrs field.
                     */
                    Asn1Set signedAttr = null;
                    if (_sAttr != null)
                    {
                        IDictionary parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);

//						Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
                        Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters);

                        if (contentType == null) //counter signature
                        {
                            if (signed != null && signed[CmsAttributes.ContentType] != null)
                            {
                                IDictionary tmpSigned = signed.ToDictionary();
                                tmpSigned.Remove(CmsAttributes.ContentType);
                                signed = new Asn1.Cms.AttributeTable(tmpSigned);
                            }
                        }

                        signedAttr = outer.GetAttributeSet(signed);

                        // sig must be composed from the DER encoding.
                        bytesToSign = signedAttr.GetEncoded(Asn1Encodable.Der);
                    }
                    else
                    {
                        // Note: Need to use raw signatures here since we have already calculated the digest
                        if (_encName.Equals("RSA"))
                        {
                            DigestInfo dInfo = new DigestInfo(digestAlgorithm, calculatedDigest);
                            bytesToSign = dInfo.GetEncoded(Asn1Encodable.Der);
                        }
                    }

                    _sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
                    byte[] sigBytes = _sig.GenerateSignature();

                    Asn1Set unsignedAttr = null;
                    if (_unsAttr != null)
                    {
                        IDictionary parameters = outer.GetBaseParameters(
                            contentType, digestAlgorithm, calculatedDigest);
                        parameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//						Asn1.Cms.AttributeTable unsigned = _unsAttr.getAttributes(Collections.unmodifiableMap(parameters));
                        Asn1.Cms.AttributeTable unsigned = _unsAttr.GetAttributes(parameters);

                        unsignedAttr = outer.GetAttributeSet(unsigned);
                    }

                    // TODO[RSAPSS] Need the ability to specify non-default parameters
                    Asn1Encodable       sigX509Parameters         = SignerUtilities.GetDefaultX509Parameters(signatureName);
                    AlgorithmIdentifier digestEncryptionAlgorithm = Helper.GetEncAlgorithmIdentifier(
                        new DerObjectIdentifier(_encOID), sigX509Parameters);

                    return(new SignerInfo(_signerIdentifier, digestAlgorithm,
                                          signedAttr, digestEncryptionAlgorithm, new DerOctetString(sigBytes), unsignedAttr));
                }
                catch (IOException e)
                {
                    throw new CmsStreamException("encoding error.", e);
                }
                catch (SignatureException e)
                {
                    throw new CmsStreamException("error creating signature.", e);
                }
            }
示例#4
0
            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType,
                CmsProcessable content,
                SecureRandom random,
                bool isCounterSignature)
            {
                AlgorithmIdentifier digAlgId = DigestAlgorithmID;
                string  digestName           = Helper.GetDigestAlgName(digestOID);
                IDigest dig = Helper.GetDigestInstance(digestName);

                string  signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
                ISigner sig           = Helper.GetSignatureInstance(signatureName);

                // TODO Optimise the case where more than one signer with same digest
                if (content != null)
                {
                    content.Write(new DigOutputStream(dig));
                }

                byte[] hash = DigestUtilities.DoFinal(dig);
                outer._digests.Add(digestOID, hash.Clone());

                sig.Init(true, new ParametersWithRandom(key, random));
                Stream sigStr = new BufferedStream(new SigOutputStream(sig));

                Asn1Set signedAttr = null;

                if (sAttr != null)
                {
                    IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

//					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
                    Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters);

                    if (isCounterSignature)
                    {
                        Hashtable tmpSigned = signed.ToHashtable();
                        tmpSigned.Remove(CmsAttributes.ContentType);
                        signed = new Asn1.Cms.AttributeTable(tmpSigned);
                    }

                    // TODO Validate proposed signed attributes

                    signedAttr = outer.GetAttributeSet(signed);

                    // sig must be composed from the DER encoding.
                    new DerOutputStream(sigStr).WriteObject(signedAttr);
                }
                else if (content != null)
                {
                    // TODO Use raw signature of the hash value instead
                    content.Write(sigStr);
                }

                sigStr.Close();
                byte[] sigBytes = sig.GenerateSignature();

                Asn1Set unsignedAttr = null;

                if (unsAttr != null)
                {
                    IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                    baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
                    Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);

                    // TODO Validate proposed unsigned attributes

                    unsignedAttr = outer.GetAttributeSet(unsigned);
                }

                // TODO[RSAPSS] Need the ability to specify non-default parameters
                Asn1Encodable       sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
                AlgorithmIdentifier encAlgId          = CmsSignedGenerator.GetEncAlgorithmIdentifier(
                    new DerObjectIdentifier(encOID), sigX509Parameters);

                return(new SignerInfo(signerIdentifier, digAlgId,
                                      signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr));
            }
示例#5
0
        private BasicOcspResp GenerateResponse(
            string signatureName,
            AsymmetricKeyParameter privateKey,
            X509Certificate[]               chain,
            DateTime producedAt,
            SecureRandom random)
        {
            DerObjectIdentifier signingAlgorithm;

            try
            {
                signingAlgorithm = OcspUtilities.GetAlgorithmOid(signatureName);
            }
            catch (Exception e)
            {
                throw new ArgumentException("unknown signing algorithm specified", e);
            }

            Asn1EncodableVector responses = new Asn1EncodableVector();

            foreach (ResponseObject respObj in list)
            {
                try
                {
                    responses.Add(respObj.ToResponse());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);

            ISigner sig = null;

            try
            {
                sig = SignerUtilities.GetSigner(signatureName);

                if (random != null)
                {
                    sig.Init(true, new ParametersWithRandom(privateKey, random));
                }
                else
                {
                    sig.Init(true, privateKey);
                }
            }
            catch (Exception e)
            {
                throw new OcspException("exception creating signature: " + e, e);
            }

            DerBitString bitSig = null;

            try
            {
                byte[] encoded = tbsResp.GetDerEncoded();
                sig.BlockUpdate(encoded, 0, encoded.Length);

                bitSig = new DerBitString(sig.GenerateSignature());
            }
            catch (Exception e)
            {
                throw new OcspException("exception processing TBSRequest: " + e, e);
            }

            AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

            DerSequence chainSeq = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector v = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        v.Add(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException e)
                {
                    throw new OcspException("error processing certs", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new OcspException("error encoding certs", e);
                }

                chainSeq = new DerSequence(v);
            }

            return(new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq)));
        }
示例#6
0
        public void TestDsa2Parameters()
        {
            byte[] seed = Hex.Decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0");

            //AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
            //a.init(2048, new DSATestSecureRandom(seed));
            DsaParametersGenerator a = new DsaParametersGenerator(new Sha256Digest());

            a.Init(new DsaParameterGenerationParameters(2048, 256, 80, new DsaTestSecureRandom(seed)));

            //AlgorithmParameters parameters = a.generateParameters();

            //DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(DSAParameterSpec.class);
            DsaParameters dsaP = a.GenerateParameters();

            if (!dsaP.Q.Equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16)))
            {
                Fail("Q incorrect");
            }

            if (!dsaP.P.Equals(new BigInteger(
                                   "F56C2A7D366E3EBDEAA1891FD2A0D099" +
                                   "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
                                   "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
                                   "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
                                   "5909132627F51A0C866877E672E555342BDF9355347DBD43" +
                                   "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
                                   "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
                                   "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
                                   "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
                                   "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
                                   "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16)))
            {
                Fail("P incorrect");
            }

            if (!dsaP.G.Equals(new BigInteger(
                                   "8DC6CC814CAE4A1C05A3E186A6FE27EA" +
                                   "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
                                   "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
                                   "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
                                   "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
                                   "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
                                   "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
                                   "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
                                   "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
                                   "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
                                   "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)))
            {
                Fail("G incorrect");
            }

            //KeyPairGenerator    g = KeyPairGenerator.getInstance("DSA", "BC");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            //g.initialize(dsaP, FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")));
            g.Init(new DsaKeyGenerationParameters(FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), dsaP));
            //KeyPair p = g.generateKeyPair();
            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            //DSAPrivateKey  sKey = (DSAPrivateKey)p.getPrivate();
            //DSAPublicKey   vKey = (DSAPublicKey)p.getPublic();
            DsaPrivateKeyParameters sKey = (DsaPrivateKeyParameters)p.Private;
            DsaPublicKeyParameters  vKey = (DsaPublicKeyParameters)p.Public;

            if (!vKey.Y.Equals(new BigInteger(
                                   "2828003D7C747199143C370FDD07A286" +
                                   "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
                                   "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
                                   "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
                                   "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
                                   "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
                                   "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
                                   "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
                                   "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
                                   "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
                                   "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16)))
            {
                Fail("Y value incorrect");
            }

            if (!sKey.X.Equals(
                    new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16)))
            {
                Fail("X value incorrect");
            }

            //byte[] encodeParams = parameters.getEncoded();
            byte[] encodeParams = new DsaParameter(dsaP.P, dsaP.Q, dsaP.G).GetDerEncoded();

            //AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
            //a2.init(encodeParams);
            DsaParameter  dsaP2 = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams));
            DsaParameters p2    = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G);

            // a and a2 should be equivalent!
            //byte[] encodeParams_2 = a2.GetEncoded();
            byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded();

            if (!AreEqual(encodeParams, encodeParams_2))
            {
                Fail("encode/decode parameters failed");
            }

            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }
        }
示例#7
0
        /// <summary>
        /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
        /// </summary>
        ///<param name="signatureAlgorithm">Name of Sig Alg.</param>
        /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param>
        /// <param name="publicKey">Public Key to be included in cert reqest.</param>
        /// <param name="attributes">ASN1Set of Attributes.</param>
        /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param>
        public Pkcs10CertificationRequest(
            string signatureAlgorithm,
            X509Name subject,
            IAsymmetricKeyParameter publicKey,
            Asn1Set attributes,
            IAsymmetricKeyParameter signingKey)
        {
            if (signatureAlgorithm == null)
            {
                throw new ArgumentNullException("signatureAlgorithm");
            }
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }
            if (publicKey.IsPrivate)
            {
                throw new ArgumentException(@"expected public key", "publicKey");
            }
            if (!signingKey.IsPrivate)
            {
                throw new ArgumentException(@"key for signing must be private", "signingKey");
            }

//			DerObjectIdentifier sigOid = SignerUtilities.GetObjectIdentifier(signatureAlgorithm);
            string algorithmName       = Platform.StringToUpper(signatureAlgorithm);
            DerObjectIdentifier sigOid = (DerObjectIdentifier)algorithms[algorithmName];

            if (sigOid == null)
            {
                try
                {
                    sigOid = new DerObjectIdentifier(algorithmName);
                }
                catch (Exception e)
                {
                    throw new ArgumentException("Unknown signature type requested", e);
                }
            }

            if (noParams.Contains(sigOid))
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid);
            }
            else if (exParams.Contains(algorithmName))
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid, (Asn1Encodable)exParams[algorithmName]);
            }
            else
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid, DerNull.Instance);
            }

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);

            ISigner sig = SignerUtilities.GetSigner(signatureAlgorithm);

            sig.Init(true, signingKey);

            try
            {
                // Encode.
                byte[] b = reqInfo.GetDerEncoded();
                sig.BlockUpdate(b, 0, b.Length);
            }
            catch (Exception e)
            {
                throw new ArgumentException("exception encoding TBS cert request", e);
            }

            // Generate Signature.
            sigBits = new DerBitString(sig.GenerateSignature());
        }
示例#8
0
        public void TestGeneration()
        {
            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[]       data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            SecureRandom rand = new SecureRandom();

            // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            // test exception
            //

            doTestBadStrength(513);
            doTestBadStrength(510);
            doTestBadStrength(1025);

            //g.initialize(512, rand);
            {
                DsaParametersGenerator pGen = new DsaParametersGenerator();
                pGen.Init(512, 80, rand);

                g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters()));
            }

            IAsymmetricCipherKeyPair p = g.GenerateKeyPair();

            IAsymmetricKeyParameter sKey = p.Private;
            IAsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }



            //
            // ECDSA Fp generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

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

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

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }

            //
            // ECDSA F2m generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

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

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

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }
        }
        /// <summary>Return a signature object containing the current signature state.</summary>
        public PgpSignature Generate()
        {
            ISignatureSubpacket[] hPkts = _hashed, unhPkts = _unhashed;
            if (!PacketPresent(_hashed, SignatureSubpacketTag.CreationTime))
            {
                hPkts = InsertSubpacket(hPkts, new SignatureCreationTime(false, DateTime.UtcNow));
            }

            if (!PacketPresent(_hashed, SignatureSubpacketTag.IssuerKeyId) &&
                !PacketPresent(_unhashed, SignatureSubpacketTag.IssuerKeyId))
            {
                unhPkts = InsertSubpacket(unhPkts, new IssuerKeyId(false, _privKey.KeyId));
            }

            const int version = 4;

            byte[] hData;

            try
            {
                using (var hOut = new MemoryStream())
                {
                    for (var i = 0; i != hPkts.Length; i++)
                    {
                        hPkts[i].Encode(hOut);
                    }

                    var data = hOut.ToArray();

                    using (var sOut = new MemoryStream(data.Length + 6))
                    {
                        sOut.WriteByte(version);
                        sOut.WriteByte((byte)_signatureType);
                        sOut.WriteByte((byte)_keyAlgorithm);
                        sOut.WriteByte((byte)_hashAlgorithm);
                        sOut.WriteByte((byte)(data.Length >> 8));
                        sOut.WriteByte((byte)data.Length);
                        sOut.Write(data, 0, data.Length);


                        hData = sOut.ToArray();
                    }
                }
            }
            catch (IOException e)
            {
                throw new PgpException("exception encoding hashed data.", e);
            }

            _sig.BlockUpdate(hData, 0, hData.Length);
            _dig.BlockUpdate(hData, 0, hData.Length);

            hData = new byte[]
            {
                version,
                0xff,
                (byte)(hData.Length >> 24),
                (byte)(hData.Length >> 16),
                (byte)(hData.Length >> 8),
                (byte)hData.Length
            };

            _sig.BlockUpdate(hData, 0, hData.Length);
            _dig.BlockUpdate(hData, 0, hData.Length);

            var sigBytes    = _sig.GenerateSignature();
            var digest      = DigestUtilities.DoFinal(_dig);
            var fingerPrint = new[] { digest[0], digest[1] };

            // an RSA signature
            var isRsa = _keyAlgorithm == PublicKeyAlgorithmTag.RsaSign ||
                        _keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral;

            var sigValues = isRsa
                ? PgpUtilities.RsaSigToMpi(sigBytes)
                : PgpUtilities.DsaSigToMpi(sigBytes);

            return(new PgpSignature(new SignaturePacket(_signatureType, _privKey.KeyId, _keyAlgorithm, _hashAlgorithm, hPkts, unhPkts, fingerPrint, sigValues)));
        }
示例#10
0
        private OcspReq GenerateRequest(
            DerObjectIdentifier signingAlgorithm,
            AsymmetricKeyParameter privateKey,
            X509Certificate[]               chain,
            SecureRandom random)
        {
            Asn1EncodableVector requests = new Asn1EncodableVector();

            foreach (RequestObject reqObj in list)
            {
                try
                {
                    requests.Add(reqObj.ToRequest());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            TbsRequest tbsReq = new TbsRequest(requestorName, new DerSequence(requests), requestExtensions);

            ISigner   sig       = null;
            Signature signature = null;

            if (signingAlgorithm != null)
            {
                if (requestorName == null)
                {
                    throw new OcspException("requestorName must be specified if request is signed.");
                }

                try
                {
                    sig = SignerUtilities.GetSigner(signingAlgorithm.Id);
                    if (random != null)
                    {
                        sig.Init(true, new ParametersWithRandom(privateKey, random));
                    }
                    else
                    {
                        sig.Init(true, privateKey);
                    }
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating signature: " + e, e);
                }

                DerBitString bitSig = null;

                try
                {
                    byte[] encoded = tbsReq.GetEncoded();
                    sig.BlockUpdate(encoded, 0, encoded.Length);

                    bitSig = new DerBitString(sig.GenerateSignature());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception processing TBSRequest: " + e, e);
                }

                AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance);

                if (chain != null && chain.Length > 0)
                {
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    try
                    {
                        for (int i = 0; i != chain.Length; i++)
                        {
                            v.Add(
                                X509CertificateStructure.GetInstance(
                                    Asn1Object.FromByteArray(chain[i].GetEncoded())));
                        }
                    }
                    catch (IOException e)
                    {
                        throw new OcspException("error processing certs", e);
                    }
                    catch (CertificateEncodingException e)
                    {
                        throw new OcspException("error encoding certs", e);
                    }

                    signature = new Signature(sigAlgId, bitSig, new DerSequence(v));
                }
                else
                {
                    signature = new Signature(sigAlgId, bitSig);
                }
            }

            return(new OcspReq(new OcspRequest(tbsReq, signature)));
        }
示例#11
0
        private void generationTest()
        {
            byte[]  data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            ISigner s    = SignerUtilities.GetSigner("GOST3410");

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // default initialisation test
            //
            s = SignerUtilities.GetSigner("GOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            // TODO This is supposed to be a 'default initialisation' test, but don't have a factory
            // These values are defaults from JCE provider
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // encoded test
            //
            //KeyFactory f = KeyFactory.getInstance("GOST3410");
            //X509EncodedKeySpec  x509s = new X509EncodedKeySpec(vKey.GetEncoded());
            //Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)f.generatePublic(x509s);
            byte[] vKeyEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
            Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)
                                             PublicKeyFactory.CreateKey(vKeyEnc);

            if (!k1.Y.Equals(((Gost3410PublicKeyParameters)vKey).Y))
            {
                Fail("public number not decoded properly");
            }

            //PKCS8EncodedKeySpec  pkcs8 = new PKCS8EncodedKeySpec(sKey.GetEncoded());
            //Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)f.generatePrivate(pkcs8);
            byte[] sKeyEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
            Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)
                                              PrivateKeyFactory.CreateKey(sKeyEnc);

            if (!k2.X.Equals(((Gost3410PrivateKeyParameters)sKey).X))
            {
                Fail("private number not decoded properly");
            }

            //
            // ECGOST3410 generation test
            //
            s = SignerUtilities.GetSigner("ECGOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

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

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

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")),
                mod_q, BigInteger.One);

            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECGOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECGOST3410 verification failed");
            }
        }
    private OcspReq GenerateRequest(DerObjectIdentifier signingAlgorithm, AsymmetricKeyParameter privateKey, X509Certificate[] chain, SecureRandom random)
    {
        Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

        foreach (RequestObject item in list)
        {
            try
            {
                asn1EncodableVector.Add(item.ToRequest());
            }
            catch (Exception e)
            {
                throw new OcspException("exception creating Request", e);
            }
        }
        TbsRequest tbsRequest        = new TbsRequest(requestorName, new DerSequence(asn1EncodableVector), requestExtensions);
        ISigner    signer            = null;
        Signature  optionalSignature = null;

        if (signingAlgorithm != null)
        {
            if (requestorName == null)
            {
                throw new OcspException("requestorName must be specified if request is signed.");
            }
            try
            {
                signer = SignerUtilities.GetSigner(signingAlgorithm.Id);
                if (random != null)
                {
                    signer.Init(forSigning: true, new ParametersWithRandom(privateKey, random));
                }
                else
                {
                    signer.Init(forSigning: true, privateKey);
                }
            }
            catch (Exception ex)
            {
                throw new OcspException("exception creating signature: " + ex, ex);
            }
            DerBitString derBitString = null;
            try
            {
                byte[] encoded = tbsRequest.GetEncoded();
                signer.BlockUpdate(encoded, 0, encoded.Length);
                derBitString = new DerBitString(signer.GenerateSignature());
            }
            catch (Exception ex2)
            {
                throw new OcspException("exception processing TBSRequest: " + ex2, ex2);
            }
            AlgorithmIdentifier signatureAlgorithm = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance);
            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        asn1EncodableVector2.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException e2)
                {
                    throw new OcspException("error processing certs", e2);
                }
                catch (CertificateEncodingException e3)
                {
                    throw new OcspException("error encoding certs", e3);
                }
                optionalSignature = new Signature(signatureAlgorithm, derBitString, new DerSequence(asn1EncodableVector2));
            }
            else
            {
                optionalSignature = new Signature(signatureAlgorithm, derBitString);
            }
        }
        return(new OcspReq(new OcspRequest(tbsRequest, optionalSignature)));
    }
示例#13
0
        public void doTestECDsa(
            string name)
        {
//			ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
            ECDomainParameters ecSpec = GetCurveParameters(name);

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            ISigner sgr = SignerUtilities.GetSigner("ECDSA");
            AsymmetricCipherKeyPair pair = g.GenerateKeyPair();
            AsymmetricKeyParameter  sKey = pair.Private;
            AsymmetricKeyParameter  vKey = pair.Public;

            sgr.Init(true, sKey);

            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail(name + " verification failed");
            }

            //
            // public key encoding test
            //
//			byte[]              pubEnc = vKey.getEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();

//			KeyFactory          keyFac = KeyFactory.getInstance("ECDH");
//			X509EncodedKeySpec  pubX509 = new X509EncodedKeySpec(pubEnc);
//			ECPublicKey         pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);

//			if (!pubKey.getW().Equals(((ECPublicKey)vKey).getW()))
            if (!pubKey.Q.Equals(((ECPublicKeyParameters)vKey).Q))
            {
                Fail("public key encoding (Q test) failed");
            }

            // TODO Put back in?
//			if (!(pubKey.Parameters is ECNamedCurveSpec))
//			{
//				Fail("public key encoding not named curve");
//			}

            //
            // private key encoding test
            //
//			byte[]              privEnc = sKey.getEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
            ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

//			if (!privKey.getS().Equals(((ECPrivateKey)sKey).getS()))
            if (!privKey.D.Equals(((ECPrivateKeyParameters)sKey).D))
            {
                Fail("private key encoding (D test) failed");
            }

            // TODO Put back in?
//			if (!(privKey.Parameters is ECNamedCurveSpec))
//			{
//				Fail("private key encoding not named curve");
//			}
//
//			ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams();
//			if (!privSpec.GetName().EqualsIgnoreCase(name)
//				&& !privSpec.GetName().EqualsIgnoreCase((string) CurveAliases[name]))
//			{
//				Fail("private key encoding wrong named curve. Expected: " + name + " got " + privSpec.GetName());
//			}
        }
            internal Asn1.Cms.SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType,
                CmsProcessable content)
            {
                AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance);
                AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid);
                string  digestName           = Helper.GetDigestAlgName(digestOID);
                string  signatureName        = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
                ISigner sig = Helper.GetSignatureInstance(signatureName);
                IDigest dig = Helper.GetDigestInstance(digestName);

                byte[] hash = null;

                if (content != null)
                {
                    content.Write(new DigOutputStream(dig));

                    hash = DigestUtilities.DoFinal(dig);

                    outer._digests.Add(digestOID, hash.Clone());
                }

                IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

                Asn1.Cms.AttributeTable signed = (sAttr != null)
//					?	sAttr.GetAttributes(Collections.unmodifiableMap(parameters))
                                        ?       sAttr.GetAttributes(parameters)
                                        :       null;

                Asn1Set signedAttr = outer.GetAttributeSet(signed);


                //
                // sig must be composed from the DER encoding.
                //
                byte[] tmp;
                if (signedAttr != null)
                {
                    tmp = signedAttr.GetDerEncoded();
                }
                else
                {
                    MemoryStream bOut = new MemoryStream();
                    content.Write(bOut);
                    tmp = bOut.ToArray();
                }

                sig.Init(true, key);
                sig.BlockUpdate(tmp, 0, tmp.Length);

                Asn1OctetString encDigest = new DerOctetString(sig.GenerateSignature());

                IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);

                baseParameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone();

                Asn1.Cms.AttributeTable unsigned = (unsAttr != null)
//					?	unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters))
                                        ?       unsAttr.GetAttributes(baseParameters)
                                        :       null;

                Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned);

                X509Certificate         cert = this.GetCertificate();
                TbsCertificateStructure tbs  = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(cert.GetTbsCertificate()));

                Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber(
                    tbs.Issuer, tbs.SerialNumber.Value);

                return(new Asn1.Cms.SignerInfo(new SignerIdentifier(encSid), digAlgId,
                                               signedAttr, encAlgId, encDigest, unsignedAttr));
            }
示例#15
0
        private OcspReq GenerateRequest(DerObjectIdentifier signingAlgorithm, AsymmetricKeyParameter privateKey, X509Certificate[] chain, SecureRandom random)
        {
            //IL_018f: Expected O, but got Unknown
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)list).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    RequestObject requestObject = (RequestObject)enumerator.get_Current();
                    try
                    {
                        asn1EncodableVector.Add(requestObject.ToRequest());
                    }
                    catch (global::System.Exception e)
                    {
                        throw new OcspException("exception creating Request", e);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            TbsRequest tbsRequest        = new TbsRequest(requestorName, new DerSequence(asn1EncodableVector), requestExtensions);
            ISigner    signer            = null;
            Signature  optionalSignature = null;

            if (signingAlgorithm != null)
            {
                if (requestorName == null)
                {
                    throw new OcspException("requestorName must be specified if request is signed.");
                }
                try
                {
                    signer = SignerUtilities.GetSigner(signingAlgorithm.Id);
                    if (random != null)
                    {
                        signer.Init(forSigning: true, new ParametersWithRandom(privateKey, random));
                    }
                    else
                    {
                        signer.Init(forSigning: true, privateKey);
                    }
                }
                catch (global::System.Exception ex)
                {
                    throw new OcspException(string.Concat((object)"exception creating signature: ", (object)ex), ex);
                }
                DerBitString derBitString = null;
                try
                {
                    byte[] encoded = tbsRequest.GetEncoded();
                    signer.BlockUpdate(encoded, 0, encoded.Length);
                    derBitString = new DerBitString(signer.GenerateSignature());
                }
                catch (global::System.Exception ex2)
                {
                    throw new OcspException(string.Concat((object)"exception processing TBSRequest: ", (object)ex2), ex2);
                }
                AlgorithmIdentifier signatureAlgorithm = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance);
                if (chain != null && chain.Length > 0)
                {
                    Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();
                    try
                    {
                        for (int i = 0; i != chain.Length; i++)
                        {
                            asn1EncodableVector2.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(chain[i].GetEncoded())));
                        }
                    }
                    catch (IOException val)
                    {
                        IOException e2 = val;
                        throw new OcspException("error processing certs", (global::System.Exception)(object) e2);
                    }
                    catch (CertificateEncodingException e3)
                    {
                        throw new OcspException("error encoding certs", e3);
                    }
                    optionalSignature = new Signature(signatureAlgorithm, derBitString, new DerSequence(asn1EncodableVector2));
                }
                else
                {
                    optionalSignature = new Signature(signatureAlgorithm, derBitString);
                }
            }
            return(new OcspReq(new OcspRequest(tbsRequest, optionalSignature)));
        }
示例#16
0
 public byte[] DoFinal()
 {
     return(sig.GenerateSignature());
 }
示例#17
0
        public void TestParameters()
        {
//			AlgorithmParameterGenerator a = AlgorithmParameterGenerator.GetInstance("DSA");
//			a.init(512, random);
            DsaParametersGenerator a = new DsaParametersGenerator();

            a.Init(512, 20, random);

//			AlgorithmParameters parameters = a.generateParameters();
            DsaParameters p = a.GenerateParameters();

//			byte[] encodeParams = parameters.GetEncoded();
            byte[] encodeParams = new DsaParameter(p.P, p.Q, p.G).GetDerEncoded();

//			AlgorithmParameters a2 = AlgorithmParameters.GetInstance("DSA");
//			a2.init(encodeParams);
            DsaParameter  dsaP = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams));
            DsaParameters p2   = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G);

            // a and a2 should be equivalent!
//			byte[] encodeParams_2 = a2.GetEncoded();
            byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded();

            if (!AreEqual(encodeParams, encodeParams_2))
            {
                Fail("encode/Decode parameters failed");
            }

//			DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(typeof(DSAParameterSpec));

//			KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

//			g.initialize(dsaP, new SecureRandom());
            g.Init(new DsaKeyGenerationParameters(new SecureRandom(), p));
//			KeyPair p = g.generateKeyPair();
            AsymmetricCipherKeyPair pair = g.GenerateKeyPair();

//			PrivateKey sKey = p.Private;
//			PublicKey vKey = p.Public;
            AsymmetricKeyParameter sKey = pair.Private;
            AsymmetricKeyParameter vKey = pair.Public;

            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }
        }
示例#18
0
        public override void PerformTest()
        {
            ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA");

            fact.Init(
                new RsaKeyGenerationParameters(
                    BigInteger.ValueOf(0x10001),
                    new SecureRandom(),
                    768,
                    25));

            AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            AsymmetricKeyParameter signingKey = keyPair.Private;
            AsymmetricKeyParameter verifyKey  = keyPair.Public;

            doTestBadSig(signingKey, verifyKey);

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA1 verification failed");
            }

            sig = SignerUtilities.GetSigner("MD2WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD2 verification failed");
            }

            sig = SignerUtilities.GetSigner("MD5WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD5 verification failed");
            }

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160 verification failed");
            }

            //
            // RIPEMD-128
            //
            sig = SignerUtilities.GetSigner("RIPEMD128WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD128 verification failed");
            }

            //
            // RIPEMD256
            //
            sig = SignerUtilities.GetSigner("RIPEMD256WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD256 verification failed");
            }

            //
            // SHA-224
            //
            sig = SignerUtilities.GetSigner("SHA224WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA224 verification failed");
            }

            //
            // SHA-256
            //
            sig = SignerUtilities.GetSigner("SHA256WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA256 verification failed");
            }

            //
            // SHA-384
            //
            sig = SignerUtilities.GetSigner("SHA384WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA384 verification failed");
            }

            //
            // SHA-512
            //
            sig = SignerUtilities.GetSigner("SHA512WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA512 verification failed");
            }

            //
            // ISO Sigs.
            //
            sig = SignerUtilities.GetSigner("MD5WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD5/ISO verification failed");
            }

            sig = SignerUtilities.GetSigner("SHA1WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA1/ISO verification failed");
            }

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160/ISO verification failed");
            }

            //
            // standard vector test - B.1.3 RIPEMD160, implicit.
            //
            BigInteger mod = new BigInteger("ffffffff78f6c55506c59785e871211ee120b0b5dd644aa796d82413a47b24573f1be5745b5cd9950f6b389b52350d4e01e90009669a8720bf265a2865994190a661dea3c7828e2e7ca1b19651adc2d5", 16);
            BigInteger pub = new BigInteger("03", 16);
            BigInteger pri = new BigInteger("2aaaaaaa942920e38120ee965168302fd0301d73a4e60c7143ceb0adf0bf30b9352f50e8b9e4ceedd65343b2179005b2f099915e4b0c37e41314bb0821ad8330d23cba7f589e0f129b04c46b67dfce9d", 16);

//			KeyFactory  f = KeyFactory.getInstance("RSA");
//			AsymmetricKeyParameter privKey = f.generatePrivate(new RSAPrivateKeySpec(mod, pri));
//			AsymmetricKeyParameter pubKey = f.generatePublic(new RSAPublicKeySpec(mod, pub));
            AsymmetricKeyParameter privKey = new RsaKeyParameters(true, mod, pri);
            AsymmetricKeyParameter pubKey  = new RsaKeyParameters(false, mod, pub);

            byte[] testSig = Hex.Decode("5cf9a01854dbacaec83aae8efc563d74538192e95466babacd361d7c86000fe42dcb4581e48e4feb862d04698da9203b1803b262105104d510b365ee9c660857ba1c001aa57abfd1c8de92e47c275cae");

            data = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSA/ISO9796-2");

            sig.Init(true, privKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            if (!AreEqual(testSig, sigBytes))
            {
                Fail("SigTest: failed ISO9796-2 generation Test");
            }

            sig.Init(false, pubKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160/ISO verification failed");
            }
        }
示例#19
0
 public byte[] Collect()
 {
     return(sig.GenerateSignature());
 }
示例#20
0
        public void TestAlgorithms()
        {
            //
            // RSA parameters
            //
            BigInteger rsaMod    = new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16);
            BigInteger rsaPubExp = new BigInteger("10001", 16);

            BigInteger rsaPrivExp  = new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16);
            BigInteger rsaPrivP    = new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16);
            BigInteger rsaPrivQ    = new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16);
            BigInteger rsaPrivDP   = new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16);
            BigInteger rsaPrivDQ   = new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16);
            BigInteger rsaPrivQinv = new BigInteger("4bb8064e1eff7e9efc3c4578fcedb59ca4aef0993a8312dfdcb1b3decf458aa6650d3d0866f143cbf0d3825e9381181170a0a1651eefcd7def786b8eb356555d9fa07c85b5f5cbdd74382f1129b5e36b4166b6cc9157923699708648212c484958351fdc9cf14f218dbe7fbf7cbd93a209a4681fe23ceb44bab67d66f45d1c9d", 16);

            RsaKeyParameters           rsaPublic  = new RsaKeyParameters(false, rsaMod, rsaPubExp);
            RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(
                rsaMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);

            //
            // ECDSA parameters
            //
            BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            BigInteger ECParraH  = new BigInteger(Base64.Decode("AQ=="));
            BigInteger ECParraN  = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            BigInteger ECPubQX   = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            BigInteger ECPubQY   = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            BigInteger ECPrivD   = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));

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

            ECDomainParameters ecDomain = new ECDomainParameters(curve,
                                                                 new FpPoint(curve,
                                                                             curve.FromBigInteger(ECParraGX),
                                                                             curve.FromBigInteger(ECParraGY)),
                                                                 ECParraN);

            ECPublicKeyParameters ecPub = new ECPublicKeyParameters(
                new FpPoint(curve,
                            curve.FromBigInteger(ECPubQX),
                            curve.FromBigInteger(ECPubQY)),
                ecDomain);

            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain);

            //
            // DSA parameters
            //
            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);

            //
            // ECGOST3410 parameters
            //
            IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

            ecGostKpg.Init(
                new ECKeyGenerationParameters(
                    CryptoProObjectIdentifiers.GostR3410x2001CryptoProA,
                    new SecureRandom()));

            AsymmetricCipherKeyPair ecGostPair = ecGostKpg.GenerateKeyPair();

            //
            // GOST3410 parameters
            //
            IAsymmetricCipherKeyPairGenerator gostKpg = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            gostKpg.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair gostPair = gostKpg.GenerateKeyPair();



            //
            // signer loop
            //
            byte[] shortMsg = new byte[] { 1, 4, 5, 6, 8, 8, 4, 2, 1, 3 };
            byte[] longMsg  = new byte[100];
            new SecureRandom().NextBytes(longMsg);

            foreach (string algorithm in SignerUtilities.Algorithms)
            {
                ISigner signer = SignerUtilities.GetSigner(algorithm);

                string upper   = algorithm.ToUpperInvariant();
                int    withPos = upper.LastIndexOf("WITH");

                string cipherName = withPos < 0
                    ?   upper
                    :   upper.Substring(withPos + "WITH".Length);

                ICipherParameters signParams = null, verifyParams = null;

                if (cipherName == "RSA" || cipherName == "RSAANDMGF1")
                {
                    signParams   = rsaPrivate;
                    verifyParams = rsaPublic;
                }
                else if (cipherName == "ECDSA")
                {
                    signParams   = ecPriv;
                    verifyParams = ecPub;
                }
                else if (cipherName == "DSA")
                {
                    signParams   = dsaPriv;
                    verifyParams = dsaPub;
                }
                else if (cipherName == "ECGOST3410")
                {
                    signParams   = ecGostPair.Private;
                    verifyParams = ecGostPair.Public;
                }
                else if (cipherName == "GOST3410")
                {
                    signParams   = gostPair.Private;
                    verifyParams = gostPair.Public;
                }
                else
                {
                    Assert.Fail("Unknown algorithm encountered: " + cipherName);
                }

                signer.Init(true, signParams);
                foreach (byte b in shortMsg)
                {
                    signer.Update(b);
                }
                signer.BlockUpdate(longMsg, 0, longMsg.Length);
                byte[] sig = signer.GenerateSignature();

                signer.Init(false, verifyParams);
                foreach (byte b in shortMsg)
                {
                    signer.Update(b);
                }
                signer.BlockUpdate(longMsg, 0, longMsg.Length);

                Assert.IsTrue(signer.VerifySignature(sig), cipherName + " signer " + algorithm + " failed.");
            }
        }
示例#21
0
        /**
         * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
         * in the signerInfo can also be set, OR a time-stamp-authority client
         * may be provided.
         * @param secondDigest the digest in the authenticatedAttributes
         * @param signingTime the signing time in the authenticatedAttributes
         * @param tsaClient TSAClient - null or an optional time stamp authority client
         * @return byte[] the bytes for the PKCS7SignedData object
         * @since   2.1.6
         */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, /*ITSAClient tsaClient,*/ byte[] ocsp)
        {
            //if (externalDigest != null)
            //{
            //    digest = externalDigest;
            //    if (RSAdata != null)
            //        RSAdata = externalRSAdata;
            //}
            //else if (externalRSAdata != null && RSAdata != null)
            //{
            //    RSAdata = externalRSAdata;
            //    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
            //    digest = sig.GenerateSignature();
            //}
            //else
            {
                if (RSAdata != null)
                {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }

            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();

            foreach (string dal in digestalgos.Keys)
            {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }

            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(ID_PKCS7_DATA));
            if (RSAdata != null)
            {
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            }
            DerSequence contentinfo = new DerSequence(v);

            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs)
            {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }

            DerSet dercertificates = new DerSet(v);

            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();

            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));

            v = new Asn1EncodableVector();
            v.Add(GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));

            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            //// add the authenticated attribute if present
            //if (secondDigest != null /*&& signingTime != null*/)
            //{
            //    signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp)));
            //}

            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // Add the digest
            signerinfo.Add(new DerOctetString(digest));

            //// When requested, go get and add the timestamp. May throw an exception.
            //// Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            //// Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            //if (tsaClient != null)
            //{
            //    byte[] tsImprint = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(digest);
            //    byte[] tsToken = tsaClient.GetTimeStampToken(this, tsImprint);
            //    if (tsToken != null)
            //    {
            //        Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
            //        if (unauthAttributes != null)
            //        {
            //            signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
            //        }
            //    }
            //}

            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();

            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));

//                if (crls.Count > 0) {
//                    v = new Asn1EncodableVector();
//                    for (Iterator i = crls.Iterator();i.HasNext();) {
//                        Asn1InputStream t = new Asn1InputStream(new ByteArrayInputStream((((X509CRL)i.Next()).GetEncoded())));
//                        v.Add(t.ReadObject());
//                    }
//                    DERSet dercrls = new DERSet(v);
//                    body.Add(new DERTaggedObject(false, 1, dercrls));
//                }

            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));

            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();

            whole.Add(new DerObjectIdentifier(ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));

            MemoryStream bOut = new MemoryStream();

            Asn1OutputStream dout = new Asn1OutputStream(bOut);

            dout.WriteObject(new DerSequence(whole));
            dout.Close();

            return(bOut.ToArray());
        }
        public PgpSignature Generate()
        {
            //IL_006b: Unknown result type (might be due to invalid IL or missing references)
            //IL_0072: Expected O, but got Unknown
            //IL_009e: Unknown result type (might be due to invalid IL or missing references)
            //IL_00a5: Expected O, but got Unknown
            //IL_010c: Expected O, but got Unknown
            SignatureSubpacket[] array  = hashed;
            SignatureSubpacket[] array2 = unhashed;
            if (!packetPresent(hashed, SignatureSubpacketTag.CreationTime))
            {
                array = insertSubpacket(array, new SignatureCreationTime(critical: false, global::System.DateTime.get_UtcNow()));
            }
            if (!packetPresent(hashed, SignatureSubpacketTag.IssuerKeyId) && !packetPresent(unhashed, SignatureSubpacketTag.IssuerKeyId))
            {
                array2 = insertSubpacket(array2, new IssuerKeyId(critical: false, privKey.KeyId));
            }
            int num = 4;

            byte[] array4;
            try
            {
                MemoryStream val = new MemoryStream();
                for (int i = 0; i != array.Length; i++)
                {
                    array[i].Encode((Stream)(object)val);
                }
                byte[]       array3 = val.ToArray();
                MemoryStream val2   = new MemoryStream(array3.Length + 6);
                ((Stream)val2).WriteByte((byte)num);
                ((Stream)val2).WriteByte((byte)signatureType);
                ((Stream)val2).WriteByte((byte)keyAlgorithm);
                ((Stream)val2).WriteByte((byte)hashAlgorithm);
                ((Stream)val2).WriteByte((byte)(array3.Length >> 8));
                ((Stream)val2).WriteByte((byte)array3.Length);
                ((Stream)val2).Write(array3, 0, array3.Length);
                array4 = val2.ToArray();
            }
            catch (IOException val3)
            {
                IOException exception = val3;
                throw new PgpException("exception encoding hashed data.", (global::System.Exception)(object) exception);
            }
            sig.BlockUpdate(array4, 0, array4.Length);
            dig.BlockUpdate(array4, 0, array4.Length);
            array4 = new byte[6]
            {
                (byte)num,
                255,
                (byte)(array4.Length >> 24),
                (byte)(array4.Length >> 16),
                (byte)(array4.Length >> 8),
                (byte)array4.Length
            };
            sig.BlockUpdate(array4, 0, array4.Length);
            dig.BlockUpdate(array4, 0, array4.Length);
            byte[] encoding    = sig.GenerateSignature();
            byte[] array5      = DigestUtilities.DoFinal(dig);
            byte[] fingerprint = new byte[2]
            {
                array5[0],
                array5[1]
            };
            MPInteger[] signature = ((keyAlgorithm == PublicKeyAlgorithmTag.RsaSign || keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral) ? PgpUtilities.RsaSigToMpi(encoding) : PgpUtilities.DsaSigToMpi(encoding));
            return(new PgpSignature(new SignaturePacket(signatureType, privKey.KeyId, keyAlgorithm, hashAlgorithm, array, array2, fingerprint, signature)));
        }
示例#23
0
 /// <summary>
 /// Generate the signature.
 /// </summary>
 /// <remarks>
 /// Generates the signature.
 /// </remarks>
 /// <returns>The signature.</returns>
 public byte[] GenerateSignature()
 {
     return(Signer.GenerateSignature());
 }
示例#24
0
        private void DoTestConsistency(Ed25519.Algorithm algorithm, byte[] context)
        {
            Ed25519KeyPairGenerator kpg = new Ed25519KeyPairGenerator();

            kpg.Init(new Ed25519KeyGenerationParameters(Random));

            AsymmetricCipherKeyPair     kp         = kpg.GenerateKeyPair();
            Ed25519PrivateKeyParameters privateKey = (Ed25519PrivateKeyParameters)kp.Private;
            Ed25519PublicKeyParameters  publicKey  = (Ed25519PublicKeyParameters)kp.Public;

            byte[] msg = new byte[Random.NextInt() & 255];
            Random.NextBytes(msg);

            ISigner signer = CreateSigner(algorithm, context);

            signer.Init(true, privateKey);
            signer.BlockUpdate(msg, 0, msg.Length);
            byte[] signature = signer.GenerateSignature();

            ISigner verifier = CreateSigner(algorithm, context);

            {
                verifier.Init(false, publicKey);
                verifier.BlockUpdate(msg, 0, msg.Length);
                bool shouldVerify = verifier.VerifySignature(signature);

                if (!shouldVerify)
                {
                    Fail("Ed25519(" + algorithm + ") signature failed to verify");
                }
            }

            {
                byte[] wrongLengthSignature = Arrays.Append(signature, 0x00);

                verifier.Init(false, publicKey);
                verifier.BlockUpdate(msg, 0, msg.Length);
                bool shouldNotVerify = verifier.VerifySignature(wrongLengthSignature);

                if (shouldNotVerify)
                {
                    Fail("Ed25519(" + algorithm + ") wrong length signature incorrectly verified");
                }
            }

            if (msg.Length > 0)
            {
                bool shouldNotVerify = verifier.VerifySignature(signature);

                if (shouldNotVerify)
                {
                    Fail("Ed25519(" + algorithm + ") wrong length failure did not reset verifier");
                }
            }

            {
                byte[] badSignature = Arrays.Clone(signature);
                badSignature[Random.Next() % badSignature.Length] ^= (byte)(1 << (Random.NextInt() & 7));

                verifier.Init(false, publicKey);
                verifier.BlockUpdate(msg, 0, msg.Length);
                bool shouldNotVerify = verifier.VerifySignature(badSignature);

                if (shouldNotVerify)
                {
                    Fail("Ed25519(" + algorithm + ") bad signature incorrectly verified");
                }
            }
        }
示例#25
0
        /// <summary>Return a signature object containing the current signature state.</summary>
        public PgpSignature Generate()
        {
            SignatureSubpacket[] hPkts = hashed, unhPkts = unhashed;

            if (!packetPresent(hashed, SignatureSubpacketTag.CreationTime))
            {
                hPkts = insertSubpacket(hPkts, new SignatureCreationTime(false, DateTime.UtcNow));
            }

            if (!packetPresent(hashed, SignatureSubpacketTag.IssuerKeyId) &&
                !packetPresent(unhashed, SignatureSubpacketTag.IssuerKeyId))
            {
                unhPkts = insertSubpacket(unhPkts, new IssuerKeyId(false, privKey.KeyId));
            }

            int version = 4;

            byte[] hData;

            try
            {
                MemoryStream hOut = new MemoryStream();

                for (int i = 0; i != hPkts.Length; i++)
                {
                    hPkts[i].Encode(hOut);
                }

                byte[] data = hOut.ToArray();

                MemoryStream sOut = new MemoryStream(data.Length + 6);
                sOut.WriteByte((byte)version);
                sOut.WriteByte((byte)signatureType);
                sOut.WriteByte((byte)keyAlgorithm);
                sOut.WriteByte((byte)hashAlgorithm);
                sOut.WriteByte((byte)(data.Length >> 8));
                sOut.WriteByte((byte)data.Length);
                sOut.Write(data, 0, data.Length);

                hData = sOut.ToArray();
            }
            catch (IOException e)
            {
                throw new PgpException("exception encoding hashed data.", e);
            }

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            hData = new byte[]
            {
                (byte)version,
                0xff,
                (byte)(hData.Length >> 24),
                (byte)(hData.Length >> 16),
                (byte)(hData.Length >> 8),
                (byte)hData.Length
            };

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            byte[] sigBytes    = sig.GenerateSignature();
            byte[] digest      = DigestUtilities.DoFinal(dig);
            byte[] fingerPrint = new byte[] { digest[0], digest[1] };

            // an RSA signature
            bool isRsa = keyAlgorithm == PublicKeyAlgorithmTag.RsaSign ||
                         keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral;

            MPInteger[] sigValues = isRsa
                                ?       PgpUtilities.RsaSigToMpi(sigBytes)
                                :       PgpUtilities.DsaSigToMpi(sigBytes);

            return(new PgpSignature(
                       new SignaturePacket(signatureType, privKey.KeyId, keyAlgorithm,
                                           hashAlgorithm, hPkts, unhPkts, fingerPrint, sigValues)));
        }
示例#26
0
 internal SignatureResult(ISigner sig)
 {
     this.sig = sig.GenerateSignature();
 }
示例#27
0
        public void TestECDsa239BitPrime()
        {
            BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176");
            BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783");

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

            SecureRandom k = FixedSecureRandom.From(kData);

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

            ECDomainParameters spec = new ECDomainParameters(
                curve,
//				ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"),      // n
                BigInteger.One);                                                                                 //1); // h

            ECPrivateKeyParameters sKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
                spec);

            ECPublicKeyParameters vKey = new ECPublicKeyParameters(
                "ECDSA",
//				ECPointUtil.DecodePoint(curve, Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                spec);

            ISigner sgr = SignerUtilities.GetSigner("ECDSA");

//			KeyFactory f = KeyFactory.getInstance("ECDSA");
//			AsymmetricKeyParameter sKey = f.generatePrivate(priKey);
//			AsymmetricKeyParameter vKey = f.generatePublic(pubKey);

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("239 Bit EC verification failed");
            }

            BigInteger[] sig = derDecode(sigBytes);

            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]);
            }
        }
示例#28
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);

            X9ECParameters     x9    = ECNamedCurveTable.GetByName("prime239v1");
            ECCurve            curve = x9.Curve;
            ECDomainParameters spec  = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

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

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                spec);

            ISigner sgr = SignerUtilities.GetSigner("ECDSA");

//			KeyFactory f = KeyFactory.GetInstance("ECDSA");
//			PrivateKey sKey = f.generatePrivate(priKey);
//			PublicKey vKey = f.generatePublic(pubKey);
            AsymmetricKeyParameter sKey = priKey;
            AsymmetricKeyParameter vKey = pubKey;

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            byte[] message = Encoding.ASCII.GetBytes("abc");

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("239 Bit EC verification failed");
            }

            BigInteger[] sig = DerDecode(sigBytes);

            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]);
            }
        }
示例#29
0
        private void ecGOST3410Test()
        {
            BigInteger r = new BigInteger("29700980915817952874371204983938256990422752107994319651632687982059210933395");
            BigInteger s = new BigInteger("46959264877825372965922731380059061821746083849389763294914877353246631700866");

            byte[] kData = new BigInteger("53854137677348463731403841147996619241504003434302020712960838528893196233395").ToByteArrayUnsigned();

            SecureRandom k = FixedSecureRandom.From(kData);

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

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

            ECDomainParameters spec = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")),
                new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q

            ECPrivateKeyParameters sKey = new ECPrivateKeyParameters(
                "ECGOST3410",
                new BigInteger("55441196065363246126355624130324183196576709222340016572108097750006097525544"), // d
                spec);

            ECPublicKeyParameters vKey = new ECPublicKeyParameters(
                "ECGOST3410",
                curve.CreatePoint(
                    new BigInteger("57520216126176808443631405023338071176630104906313632182896741342206604859403"),
                    new BigInteger("17614944419213781543809391949654080031942662045363639260709847859438286763994")),
                spec);

            ISigner sgr = SignerUtilities.GetSigner("ECGOST3410");

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("ECGOST3410 verification failed");
            }

            BigInteger[] sig = decode(sigBytes);

            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]);
            }
        }
示例#30
0
        public void TestGeneration()
        {
            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[]       data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            SecureRandom rand = new SecureRandom();

            // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            // test exception
            //

            doTestBadStrength(513);
            doTestBadStrength(510);
            doTestBadStrength(1025);

            //g.initialize(512, rand);
            {
                DsaParametersGenerator pGen = new DsaParametersGenerator();
                pGen.Init(512, 80, rand);

                g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters()));
            }

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }



            //
            // ECDSA Fp generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            X9ECParameters     x9     = ECNamedCurveTable.GetByName("prime239v1");
            ECCurve            curve  = x9.Curve;
            ECDomainParameters ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }

            //
            // ECDSA F2m generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            x9     = ECNamedCurveTable.GetByName("c2tnb239v1");
            curve  = x9.Curve;
            ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }
        }
示例#31
0
		private void checkSignature(
			int						size,
			ECPrivateKeyParameters	sKey,
			ECPublicKeyParameters	vKey,
			ISigner					sgr,
			SecureRandom			k,
			byte[]					message,
			BigInteger				r,
			BigInteger				s)
		{
			sgr.Init(true, new ParametersWithRandom(sKey, k));

			sgr.BlockUpdate(message, 0, message.Length);

			byte[] sigBytes = sgr.GenerateSignature();

			sgr.Init(false, vKey);

			sgr.BlockUpdate(message, 0, message.Length);

			if (!sgr.VerifySignature(sigBytes))
			{
				Fail(size + " bit EC verification failed");
			}

			BigInteger[] sig = derDecode(sigBytes);

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

			if (!s.Equals(sig[1]))
			{
				Fail(size + "bit"
					+ ": s component wrong." + SimpleTest.NewLine
					+ " expecting: " + s + SimpleTest.NewLine
					+ " got      : " + sig[1]);
			}
		}
示例#32
0
        protected override async Task OnOpenAsync(CancellationToken token)
        {
            this.Logger?.LogInformation($"Opening session channel with endpoint '{this.RemoteEndpoint.EndpointUrl}'.");
            this.Logger?.LogInformation($"SecurityPolicy: '{this.RemoteEndpoint.SecurityPolicyUri}'.");
            this.Logger?.LogInformation($"SecurityMode: '{this.RemoteEndpoint.SecurityMode}'.");
            this.Logger?.LogInformation($"UserIdentityToken: '{this.UserIdentity}'.");

            await base.OnOpenAsync(token).ConfigureAwait(false);

            token.ThrowIfCancellationRequested();

            // if SessionId is provided then we skip the CreateSessionRequest and go directly to (re)ActivateSession.
            // requires from previous Session: SessionId, AuthenticationToken, RemoteNonce
            if (this.SessionId == null)
            {
                var localNonce           = this.RemoteEndpoint.SecurityMode != MessageSecurityMode.None ? this.GetNextNonce(NonceLength) : null;
                var localCertificate     = this.RemoteEndpoint.SecurityMode != MessageSecurityMode.None ? this.LocalCertificate : null;
                var createSessionRequest = new CreateSessionRequest
                {
                    ClientDescription       = this.LocalDescription,
                    EndpointUrl             = this.RemoteEndpoint.EndpointUrl,
                    SessionName             = this.LocalDescription.ApplicationName,
                    ClientNonce             = localNonce,
                    ClientCertificate       = localCertificate,
                    RequestedSessionTimeout = this.SessionTimeout,
                    MaxResponseMessageSize  = this.RemoteMaxMessageSize
                };

                var createSessionResponse = await this.CreateSessionAsync(createSessionRequest).ConfigureAwait(false);

                this.SessionId           = createSessionResponse.SessionId;
                this.AuthenticationToken = createSessionResponse.AuthenticationToken;
                this.RemoteNonce         = createSessionResponse.ServerNonce;

                // verify the server's certificate is the same as the certificate from the selected endpoint.
                if (this.RemoteEndpoint.ServerCertificate != null && !this.RemoteEndpoint.ServerCertificate.SequenceEqual(createSessionResponse.ServerCertificate))
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Server did not return the same certificate used to create the channel.");
                }

                // verify the server's signature.
                ISigner verifier     = null;
                byte[]  dataToVerify = null;
                switch (this.RemoteEndpoint.SecurityPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                case SecurityPolicyUris.Basic256:
                    dataToVerify = Concat(localCertificate, localNonce);
                    verifier     = SignerUtilities.GetSigner("SHA-1withRSA");
                    verifier.Init(false, this.RemotePublicKey);
                    verifier.BlockUpdate(dataToVerify, 0, dataToVerify.Length);
                    if (!verifier.VerifySignature(createSessionResponse.ServerSignature.Signature))
                    {
                        throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid, "Server did not provide a correct signature for the nonce data provided by the client.");
                    }

                    break;

                case SecurityPolicyUris.Basic256Sha256:
                    dataToVerify = Concat(localCertificate, localNonce);
                    verifier     = SignerUtilities.GetSigner("SHA-256withRSA");
                    verifier.Init(false, this.RemotePublicKey);
                    verifier.BlockUpdate(dataToVerify, 0, dataToVerify.Length);
                    if (!verifier.VerifySignature(createSessionResponse.ServerSignature.Signature))
                    {
                        throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid, "Server did not provide a correct signature for the nonce data provided by the client.");
                    }

                    break;

                default:
                    break;
                }
            }

            // create client signature
            SignatureData clientSignature = null;
            ISigner       signer          = null;

            byte[] dataToSign = null;
            switch (this.RemoteEndpoint.SecurityPolicyUri)
            {
            case SecurityPolicyUris.Basic128Rsa15:
            case SecurityPolicyUris.Basic256:
                dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce);
                signer     = SignerUtilities.GetSigner("SHA-1withRSA");
                signer.Init(true, this.LocalPrivateKey);
                signer.BlockUpdate(dataToSign, 0, dataToSign.Length);
                clientSignature = new SignatureData
                {
                    Signature = signer.GenerateSignature(),
                    Algorithm = RsaSha1Signature,
                };

                break;

            case SecurityPolicyUris.Basic256Sha256:
                dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce);
                signer     = SignerUtilities.GetSigner("SHA-256withRSA");
                signer.Init(true, this.LocalPrivateKey);
                signer.BlockUpdate(dataToSign, 0, dataToSign.Length);
                clientSignature = new SignatureData
                {
                    Signature = signer.GenerateSignature(),
                    Algorithm = RsaSha256Signature,
                };

                break;

            default:
                clientSignature = new SignatureData();
                break;
            }

            // supported UserIdentityToken types are AnonymousIdentityToken, UserNameIdentityToken, IssuedIdentityToken, X509IdentityToken
            UserIdentityToken identityToken  = null;
            SignatureData     tokenSignature = null;

            // if UserIdentity type is IssuedIdentity
            if (this.UserIdentity is IssuedIdentity)
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.IssuedToken);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                var    issuedIdentity = (IssuedIdentity)this.UserIdentity;
                byte[] plainText      = Concat(issuedIdentity.TokenData, this.RemoteNonce);
                var    secPolicyUri   = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                switch (secPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = this.RemotePublicKey.EncryptTokenData(plainText, secPolicyUri),
                        EncryptionAlgorithm = RsaV15KeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                case SecurityPolicyUris.Basic256:
                case SecurityPolicyUris.Basic256Sha256:
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = this.RemotePublicKey.EncryptTokenData(plainText, secPolicyUri),
                        EncryptionAlgorithm = RsaOaepKeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                default:
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = issuedIdentity.TokenData,
                        EncryptionAlgorithm = null,
                        PolicyId            = tokenPolicy.PolicyId
                    };
                    break;
                }

                tokenSignature = new SignatureData();
            }

            // if UserIdentity type is X509Identity
            else if (this.UserIdentity is X509Identity)
            {
                throw new NotImplementedException("A user identity of X509Identity is not implemented.");

                /*
                 * var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.Certificate);
                 * if (tokenPolicy == null)
                 * {
                 *  throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                 * }
                 *
                 * var x509Identity = (X509Identity)this.UserIdentity;
                 * identityToken = new X509IdentityToken { CertificateData = x509Identity.Certificate?.RawData, PolicyId = tokenPolicy.PolicyId };
                 * var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                 * switch (secPolicyUri)
                 * {
                 *  case SecurityPolicyUris.Basic128Rsa15:
                 *  case SecurityPolicyUris.Basic256:
                 *      var asymSigningKey = x509Identity.Certificate?.GetRSAPrivateKey();
                 *      if (asymSigningKey != null)
                 *      {
                 *          dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce);
                 *          tokenSignature = new SignatureData
                 *          {
                 *              Signature = asymSigningKey.SignData(dataToSign, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1),
                 *              Algorithm = RsaSha1Signature,
                 *          };
                 *          break;
                 *      }
                 *
                 *      tokenSignature = new SignatureData();
                 *      break;
                 *
                 *  case SecurityPolicyUris.Basic256Sha256:
                 *      var asymSigningKey256 = x509Identity.Certificate?.GetRSAPrivateKey();
                 *      if (asymSigningKey256 != null)
                 *      {
                 *          dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce);
                 *          tokenSignature = new SignatureData
                 *          {
                 *              Signature = asymSigningKey256.SignData(dataToSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1),
                 *              Algorithm = RsaSha256Signature,
                 *          };
                 *          break;
                 *      }
                 *
                 *      tokenSignature = new SignatureData();
                 *      break;
                 *
                 *  default:
                 *      tokenSignature = new SignatureData();
                 *      break;
                 * }
                 */
            }

            // if UserIdentity type is UserNameIdentity
            else if (this.UserIdentity is UserNameIdentity)
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.UserName);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                var    userNameIdentity = (UserNameIdentity)this.UserIdentity;
                byte[] plainText        = Concat(System.Text.Encoding.UTF8.GetBytes(userNameIdentity.Password), this.RemoteNonce);
                var    secPolicyUri     = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                switch (secPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = this.RemotePublicKey.EncryptTokenData(plainText, secPolicyUri),
                        EncryptionAlgorithm = RsaV15KeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                case SecurityPolicyUris.Basic256:
                case SecurityPolicyUris.Basic256Sha256:
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = this.RemotePublicKey.EncryptTokenData(plainText, secPolicyUri),
                        EncryptionAlgorithm = RsaOaepKeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                default:
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = System.Text.Encoding.UTF8.GetBytes(userNameIdentity.Password),
                        EncryptionAlgorithm = null,
                        PolicyId            = tokenPolicy.PolicyId
                    };
                    break;
                }

                tokenSignature = new SignatureData();
            }

            // if UserIdentity type is AnonymousIdentity or null
            else
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.Anonymous);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                identityToken = new AnonymousIdentityToken {
                    PolicyId = tokenPolicy.PolicyId
                };
                tokenSignature = new SignatureData();
            }

            var activateSessionRequest = new ActivateSessionRequest
            {
                ClientSignature    = clientSignature,
                LocaleIds          = new[] { CultureInfo.CurrentUICulture.TwoLetterISOLanguageName },
                UserIdentityToken  = identityToken,
                UserTokenSignature = tokenSignature
            };
            var activateSessionResponse = await this.ActivateSessionAsync(activateSessionRequest).ConfigureAwait(false);

            this.RemoteNonce = activateSessionResponse.ServerNonce;

            // fetch namespace array, etc.
            var readValueIds = new ReadValueId[]
            {
                new ReadValueId
                {
                    NodeId      = NodeId.Parse(VariableIds.Server_NamespaceArray),
                    AttributeId = AttributeIds.Value
                },
                new ReadValueId
                {
                    NodeId      = NodeId.Parse(VariableIds.Server_ServerArray),
                    AttributeId = AttributeIds.Value
                }
            };
            var readRequest = new ReadRequest
            {
                NodesToRead = readValueIds
            };

            var readResponse = await this.ReadAsync(readRequest).ConfigureAwait(false);

            if (readResponse.Results.Length == 2)
            {
                if (StatusCode.IsGood(readResponse.Results[0].StatusCode))
                {
                    this.NamespaceUris.Clear();
                    this.NamespaceUris.AddRange(readResponse.Results[0].GetValueOrDefault <string[]>());
                }

                if (StatusCode.IsGood(readResponse.Results[1].StatusCode))
                {
                    this.ServerUris.Clear();
                    this.ServerUris.AddRange(readResponse.Results[1].GetValueOrDefault <string[]>());
                }
            }
        }