/// <summary>Initialise the signature object for verification.</summary> public void InitVerify( PgpPublicKey pubKey) { lastb = 0; try { sig = SignerUtilities.GetSigner( PgpUtilities.GetSignatureName(sigPack.KeyAlgorithm, sigPack.HashAlgorithm)); } catch (Exception e) { throw new PgpException("can't set up signature object.", e); } try { sig.Init(false, pubKey.GetKey()); } catch (InvalidKeyException e) { throw new PgpException("invalid key.", e); } }
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]); } }
public void TestAlgorithms() { // // RSA parameters // IBigInteger rsaMod = new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16); IBigInteger rsaPubExp = new BigInteger("10001", 16); IBigInteger rsaPrivExp = new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16); IBigInteger rsaPrivP = new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16); IBigInteger rsaPrivQ = new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16); IBigInteger rsaPrivDP = new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16); IBigInteger rsaPrivDQ = new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16); IBigInteger 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 // IBigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv")); IBigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R")); IBigInteger ECParraH = new BigInteger(Base64.Decode("AQ==")); IBigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L")); IBigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l")); IBigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx")); IBigInteger 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 // IBigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM=")); IBigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs=")); IBigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx")); IBigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw==")); IBigInteger 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())); IAsymmetricCipherKeyPair ecGostPair = ecGostKpg.GenerateKeyPair(); // // GOST3410 parameters // IAsymmetricCipherKeyPairGenerator gostKpg = GeneratorUtilities.GetKeyPairGenerator("GOST3410"); gostKpg.Init( new Gost3410KeyGenerationParameters( new SecureRandom(), CryptoProObjectIdentifiers.GostR3410x94CryptoProA)); IAsymmetricCipherKeyPair 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.ToUpper(CultureInfo.InvariantCulture); 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."); } }
private void processDHEKeyExchange( MemoryStream inStr, ISigner signer) { Stream sigIn = inStr; if (signer != null) { signer.Init(false, this.serverPublicKey); signer.BlockUpdate(this.clientRandom, 0, this.clientRandom.Length); signer.BlockUpdate(this.serverRandom, 0, this.serverRandom.Length); sigIn = new SignerStream(inStr, signer, null); } /* * Parse the Structure */ byte[] pByte = TlsUtilities.ReadOpaque16(sigIn); byte[] gByte = TlsUtilities.ReadOpaque16(sigIn); byte[] YsByte = TlsUtilities.ReadOpaque16(sigIn); if (signer != null) { byte[] sigByte = TlsUtilities.ReadOpaque16(sigIn); /* * Verify the Signature. */ if (!signer.VerifySignature(sigByte)) { this.FailWithError(AL_fatal, AP_bad_certificate); } } this.AssertEmpty(inStr); /* * Do the DH calculation. */ BigInteger p = new BigInteger(1, pByte); BigInteger g = new BigInteger(1, gByte); BigInteger Ys = new BigInteger(1, YsByte); /* * Check the DH parameter values */ if (!p.IsProbablePrime(10)) { this.FailWithError(AL_fatal, AP_illegal_parameter); } if (g.CompareTo(BigInteger.Two) < 0 || g.CompareTo(p.Subtract(BigInteger.Two)) > 0) { this.FailWithError(AL_fatal, AP_illegal_parameter); } // TODO For static DH public values, see additional checks in RFC 2631 2.1.5 if (Ys.CompareTo(BigInteger.Two) < 0 || Ys.CompareTo(p.Subtract(BigInteger.One)) > 0) { this.FailWithError(AL_fatal, AP_illegal_parameter); } /* * Diffie-Hellman basic key agreement */ DHParameters dhParams = new DHParameters(p, g); // Generate a keypair DHBasicKeyPairGenerator dhGen = new DHBasicKeyPairGenerator(); dhGen.Init(new DHKeyGenerationParameters(random, dhParams)); AsymmetricCipherKeyPair dhPair = dhGen.GenerateKeyPair(); // Store the public value to send to server this.Yc = ((DHPublicKeyParameters)dhPair.Public).Y; // Calculate the shared secret DHBasicAgreement dhAgree = new DHBasicAgreement(); dhAgree.Init(dhPair.Private); BigInteger agreement = dhAgree.CalculateAgreement(new DHPublicKeyParameters(Ys, dhParams)); this.pms = BigIntegers.AsUnsignedByteArray(agreement); }
public override void PerformTest() { ISigner s = SignerUtilities.GetSigner("SHA1withRSA/PSS"); s.Init(true, new ParametersWithRandom(privKey, new FixedRandom(slt1a))); s.BlockUpdate(msg1a, 0, msg1a.Length); byte[] sig = s.GenerateSignature(); if (!Arrays.AreEqual(sig1a, sig)) { Fail("PSS Sign test expected " + Hex.ToHexString(sig1a) + " got " + Hex.ToHexString(sig)); } s = SignerUtilities.GetSigner("SHA1withRSAandMGF1"); s.Init(false, pubKey); s.BlockUpdate(msg1a, 0, msg1a.Length); if (!s.VerifySignature(sig1a)) { Fail("SHA1 signature verification failed"); } s = SignerUtilities.GetSigner("SHA1withRSAandMGF1"); s.Init(false, pubKey); s.BlockUpdate(msg1a, 0, msg1a.Length); if (!s.VerifySignature(sig1a)) { Fail("SHA1 signature verification with default parameters failed"); } // AlgorithmParameters pss = s.getParameters(); // TODO Can we do some equivalent check? // if (!Arrays.AreEqual(pss.getEncoded(), new byte[] { 0x30, 0x00 })) // { // Fail("failed default encoding test."); // } s = SignerUtilities.GetSigner("SHA256withRSA/PSS"); s.Init(true, new ParametersWithRandom(privKey, new FixedRandom(slt1a))); s.BlockUpdate(msg1a, 0, msg1a.Length); sig = s.GenerateSignature(); if (!Arrays.AreEqual(sig1b, sig)) { Fail("PSS Sign test expected " + Hex.ToHexString(sig1b) + " got " + Hex.ToHexString(sig)); } s = SignerUtilities.GetSigner("SHA256withRSAandMGF1"); s.Init(false, pubKey); s.BlockUpdate(msg1a, 0, msg1a.Length); if (!s.VerifySignature(sig1b)) { Fail("SHA256 signature verification failed"); } // // 512 test -with zero salt length // //s = SignerUtilities.GetSigner("SHA512withRSAandMGF1"); // s.setParameter( // new PSSParameterSpec("SHA-512", "MGF1", new MGF1ParameterSpec("SHA-512"), 0, 1)); // TODO How to do this via SignerUtilities/Init // trailerField=1 above means use default/implicit trailer?) s = new PssSigner(new RsaEngine(), new Sha512Digest(), 0, PssSigner.TrailerImplicit); s.Init(true, privKey); s.BlockUpdate(msg1a, 0, msg1a.Length); sig = s.GenerateSignature(); // pss = s.getParameters(); if (!Arrays.AreEqual(sig1c, sig)) { Fail("PSS Sign test expected " + Hex.ToHexString(sig1c) + " got " + Hex.ToHexString(sig)); } // s = SignerUtilities.GetSigner("SHA512withRSAandMGF1"); // TODO How to do this via SignerUtilities/Init // trailerField=1 above means use default/implicit trailer?) s = new PssSigner(new RsaEngine(), new Sha512Digest(), 0, PssSigner.TrailerImplicit); s.Init(false, pubKey); s.BlockUpdate(msg1a, 0, msg1a.Length); if (!s.VerifySignature(sig1c)) { Fail("SHA512 signature verification failed"); } SecureRandom random = new SecureRandom(); // Note: PSS minimum key size determined by hash/salt lengths // PrivateKey priv2048Key = fact.generatePrivate(RSATest.priv2048KeySpec); // PublicKey pub2048Key = fact.generatePublic(RSATest.pub2048KeySpec); AsymmetricKeyParameter priv2048Key = RsaTest.priv2048KeySpec; AsymmetricKeyParameter pub2048Key = RsaTest.pub2048KeySpec; rawModeTest("SHA1withRSA/PSS", X509ObjectIdentifiers.IdSha1, priv2048Key, pub2048Key, random); // FIXME // rawModeTest("SHA224withRSA/PSS", NistObjectIdentifiers.IdSha224, priv2048Key, pub2048Key, random); // rawModeTest("SHA256withRSA/PSS", NistObjectIdentifiers.IdSha256, priv2048Key, pub2048Key, random); // rawModeTest("SHA384withRSA/PSS", NistObjectIdentifiers.IdSha384, priv2048Key, pub2048Key, random); // rawModeTest("SHA512withRSA/PSS", NistObjectIdentifiers.IdSha512, priv2048Key, pub2048Key, random); }
/** * Verifies a signature using the sub-filter adbe.pkcs7.detached or * adbe.pkcs7.sha1. * @param contentsKey the /Contents key * @param provider the provider or <code>null</code> for the default provider * @throws SecurityException on error * @throws CRLException on error * @throws InvalidKeyException on error * @throws CertificateException on error * @throws NoSuchProviderException on error * @throws NoSuchAlgorithmException on error */ public PdfPKCS7(byte[] contentsKey) { Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // Asn1Object pkcs; try { pkcs = din.ReadObject(); } catch { throw new ArgumentException("can't decode PKCS7SignedData object"); } if (!(pkcs is Asn1Sequence)) { throw new ArgumentException("Not a valid PKCS#7 object - not a sequence"); } Asn1Sequence signedData = (Asn1Sequence)pkcs; DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0]; if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA)) throw new ArgumentException("Not a valid PKCS#7 object - not signed data"); Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((DerInteger)content[0]).Value.IntValue; // the digestAlgorithms digestalgos = new Hashtable(); IEnumerator e = ((Asn1Set)content[1]).GetEnumerator(); while (e.MoveNext()) { Asn1Sequence s = (Asn1Sequence)e.Current; DerObjectIdentifier o = (DerObjectIdentifier)s[0]; digestalgos[o.Id] = null; } // the certificates and crls X509CertificateParser cf = new X509CertificateParser(); certs = new ArrayList(); foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) { certs.Add(cc); } crls = new ArrayList(); // the possible ID_PKCS7_DATA Asn1Sequence rsaData = (Asn1Sequence)content[2]; if (rsaData.Count > 1) { DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject(); RSAdata = rsaDataContent.GetOctets(); } // the signerInfos int next = 3; while (content[next] is DerTaggedObject) ++next; Asn1Set signerInfos = (Asn1Set)content[next]; if (signerInfos.Count != 1) throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0]; // the positions that we care are // 0 - version // 1 - the signing certificate serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((DerInteger)signerInfo[0]).Value.IntValue; // Get the signing certificate Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1]; BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value; foreach (X509Certificate cert in certs) { if (serialNumber.Equals(cert.SerialNumber)) { signCert = cert; break; } } if (signCert == null) { throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16)); } CalcSignCertificateChain(); digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id; next = 3; if (signerInfo[next] is Asn1TaggedObject) { Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next]; Asn1Set sseq = Asn1Set.GetInstance(tagsig, false); sigAttr = sseq.GetEncoded(Asn1Encodable.Der); for (int k = 0; k < sseq.Count; ++k) { Asn1Sequence seq2 = (Asn1Sequence)sseq[k]; if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) { Asn1Set sset = (Asn1Set)seq2[1]; digestAttr = ((DerOctetString)sset[0]).GetOctets(); } else if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_ADBE_REVOCATION)) { Asn1Set setout = (Asn1Set)seq2[1]; Asn1Sequence seqout = (Asn1Sequence)setout[0]; for (int j = 0; j < seqout.Count; ++j) { Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j]; if (tg.TagNo != 1) continue; Asn1Sequence seqin = (Asn1Sequence)tg.GetObject(); FindOcsp(seqin); } } } if (digestAttr == null) throw new ArgumentException("Authenticated attribute is missing the digest."); ++next; } digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id; digest = ((DerOctetString)signerInfo[next++]).GetOctets(); if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) { DerTaggedObject taggedObject = (DerTaggedObject) signerInfo[next]; Asn1Set unat = Asn1Set.GetInstance(taggedObject, false); Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat); Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]; if (ts != null) { Asn1Set attributeValues = ts.AttrValues; Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]); Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence); this.timeStampToken = new TimeStampToken(contentInfo); } } if (RSAdata != null || digestAttr != null) { messageDigest = GetHashClass(); } sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); sig.Init(false, signCert.GetPublicKey()); }
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]); } }
/** * Generates a signature. * @param privKey the private key * @param certChain the certificate chain * @param crlList the certificate revocation list * @param hashAlgorithm the hash algorithm * @param provider the provider or <code>null</code> for the default provider * @param hasRSAdata <CODE>true</CODE> if the sub-filter is adbe.pkcs7.sha1 * @throws SecurityException on error * @throws InvalidKeyException on error * @throws NoSuchProviderException on error * @throws NoSuchAlgorithmException on error */ public PdfPKCS7(ICipherParameters privKey, X509Certificate[] certChain, object[] crlList, String hashAlgorithm, bool hasRSAdata) { this.privKey = privKey; digestAlgorithm = GetAllowedDigests(hashAlgorithm); if (digestAlgorithm == null) throw new ArgumentException(MessageLocalization.GetComposedMessage("unknown.hash.algorithm.1", hashAlgorithm)); version = signerversion = 1; certs = new List<X509Certificate>(); crls = new List<X509Crl>(); digestalgos = new Dictionary<string,object>(); digestalgos[digestAlgorithm] = null; // // Copy in the certificates and crls used to sign the private key. // signCert = certChain[0]; for (int i = 0;i < certChain.Length;i++) { certs.Add(certChain[i]); } // if (crlList != null) { // for (int i = 0;i < crlList.length;i++) { // crls.Add(crlList[i]); // } // } if (privKey != null) { // // Now we have private key, find out what the digestEncryptionAlgorithm is. // if (privKey is RsaKeyParameters) digestEncryptionAlgorithm = ID_RSA; else if (privKey is DsaKeyParameters) digestEncryptionAlgorithm = ID_DSA; else throw new ArgumentException(MessageLocalization.GetComposedMessage("unknown.key.algorithm.1", privKey.ToString())); } if (hasRSAdata) { RSAdata = new byte[0]; messageDigest = GetHashClass(); } if (privKey != null) { sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); sig.Init(true, privKey); } }
public override void Execute(string[] commandline) { if (commandline.Length < 2) { _console.Out.WriteLine("Error: [local_session_alias] not specified"); return; } else if (commandline.Length < 3) { _console.Out.WriteLine("Error: [command] not specified"); return; } ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null); if (ctx == null) { _console.Out.WriteLine("No active connection was found"); return; } string localAlias = commandline[1]; IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null); if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false) { _console.Out.WriteLine("Error: Specified local alias was not found"); return; } if (tpmSessions[localAlias].Keystore == null) { _console.Out.WriteLine("Error: No keystore was opened"); return; } string subCommand = commandline[2]; IDictionary <string, string> arguments = _console.SplitArguments(commandline[3], 0); if (arguments.ContainsKey("name") == false) { _console.Out.WriteLine("Error: no key name was specified"); return; } // if(arguments.ContainsKey("pcr") == false) // { // _console.Out.WriteLine("Error: no pcr values where specified"); // return; // } if (arguments.ContainsKey("data_input") == false) { _console.Out.WriteLine("Error: no data input source specified"); return; } DataInputMode dataInputMode; try { dataInputMode = (DataInputMode)Enum.Parse(typeof(DataInputMode), arguments["data_input"], true); } catch (Exception) { _console.Out.WriteLine("Error: Invalid data input source"); return; } DataFormat inputDataFormat = DataFormat.Raw; if (arguments.ContainsKey("input_data_format")) { try { inputDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), arguments["input_data_format"], true); } catch (Exception) { _console.Out.WriteLine("Error: Invalid input data format"); return; } } if (dataInputMode == DataInputMode.File && arguments.ContainsKey("file") == false) { _console.Out.WriteLine("Error: data_input=file requires file argument!"); return; } ClientKeyHandle keyHandle = tpmSessions[localAlias].KeyClient.GetKeyHandleByFriendlyName(arguments["name"]); Stream inputStream = null; if (dataInputMode == DataInputMode.Console) { inputStream = new TextReaderStream(_console.In); } else if (dataInputMode == DataInputMode.Embedded) { if (commandline.Length <= 3) { _console.Out.WriteLine("Error: no embedded data"); return; } StringBuilder embeddedData = new StringBuilder(); for (int i = 3; i < commandline.Length; i++) { embeddedData.Append(commandline[i]); if (i + 1 < commandline.Length) { embeddedData.Append(" "); } } inputStream = new TextReaderStream(new StringReader(embeddedData.ToString())); } else if (dataInputMode == DataInputMode.File) { inputStream = new FileStream(arguments["file"], FileMode.Open, FileAccess.Read); } if (inputDataFormat == DataFormat.Hex) { inputStream = new HexFilterStream(inputStream); } ISigner signatureGenerator = null; if (subCommand == "verify") { signatureGenerator = keyHandle.CreateSigner(); signatureGenerator.Init(false, null); } else if (subCommand == "generate") { signatureGenerator = keyHandle.CreateSigner(); signatureGenerator.Init(true, null); } else if (subCommand == "generate_quote" || subCommand == "verify_quote") { if (arguments.ContainsKey("pcr") == false) { _console.Out.WriteLine("Error: No pcrs specified!"); return; } TPMPCRSelection pcrSelection = tpmSessions[localAlias].CreateEmptyPCRSelection(); foreach (string pcr in arguments["pcr"].Split('|')) { int pcrValue = int.Parse(pcr); pcrSelection.PcrSelection.SetBit(pcrValue - 1, true); } signatureGenerator = keyHandle.CreateQuoter(pcrSelection); signatureGenerator.Init(subCommand == "generate_quote", null); } byte[] buffer = new byte[1024]; int read = 0; do { read = inputStream.Read(buffer, 0, buffer.Length); signatureGenerator.BlockUpdate(buffer, 0, read); }while(read > 0); _console.Out.WriteLine(ByteHelper.ByteArrayToHexString(signatureGenerator.GenerateSignature())); _console.Out.WriteLine(); inputStream.Dispose(); }
private void DoTestConsistency(Ed448.Algorithm algorithm, byte[] context) { Ed448KeyPairGenerator kpg = new Ed448KeyPairGenerator(); kpg.Init(new Ed448KeyGenerationParameters(Random)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); Ed448PrivateKeyParameters privateKey = (Ed448PrivateKeyParameters)kp.Private; Ed448PublicKeyParameters publicKey = (Ed448PublicKeyParameters)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("Ed448(" + 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("Ed448(" + algorithm + ") wrong length signature incorrectly verified"); } } if (msg.Length > 0) { bool shouldNotVerify = verifier.VerifySignature(signature); if (shouldNotVerify) { Fail("Ed448(" + 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("Ed448(" + algorithm + ") bad signature incorrectly verified"); } } }
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"); } }
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]); } }
/** * Verifies a signature using the sub-filter adbe.pkcs7.detached or * adbe.pkcs7.sha1. * @param contentsKey the /Contents key * @param provider the provider or <code>null</code> for the default provider * @throws SecurityException on error * @throws CRLException on error * @throws InvalidKeyException on error * @throws CertificateException on error * @throws NoSuchProviderException on error * @throws NoSuchAlgorithmException on error */ public PdfPKCS7(byte[] contentsKey) { Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // Asn1Object pkcs; try { pkcs = din.ReadObject(); } catch { throw new ArgumentException("can't decode PKCS7SignedData object"); } if (!(pkcs is Asn1Sequence)) { throw new ArgumentException("Not a valid PKCS#7 object - not a sequence"); } Asn1Sequence signedData = (Asn1Sequence)pkcs; DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0]; if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA)) throw new ArgumentException("Not a valid PKCS#7 object - not signed data"); Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((DerInteger)content[0]).Value.IntValue; // the digestAlgorithms digestalgos = new Hashtable(); IEnumerator e = ((Asn1Set)content[1]).GetEnumerator(); while (e.MoveNext()) { Asn1Sequence s = (Asn1Sequence)e.Current; DerObjectIdentifier o = (DerObjectIdentifier)s[0]; digestalgos[o.Id] = null; } // the certificates and crls X509CertificateParser cf = new X509CertificateParser(); certs = new ArrayList(); foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) { certs.Add(cc); } crls = new ArrayList(); // the possible ID_PKCS7_DATA Asn1Sequence rsaData = (Asn1Sequence)content[2]; if (rsaData.Count > 1) { DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject(); RSAdata = rsaDataContent.GetOctets(); } // the signerInfos int next = 3; while (content[next] is DerTaggedObject) ++next; Asn1Set signerInfos = (Asn1Set)content[next]; if (signerInfos.Count != 1) throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0]; // the positions that we care are // 0 - version // 1 - the signing certificate serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((DerInteger)signerInfo[0]).Value.IntValue; // Get the signing certificate Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1]; BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value; foreach (X509Certificate cert in certs) { if (serialNumber.Equals(cert.SerialNumber)) { signCert = cert; break; } } if (signCert == null) { throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16)); } digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id; next = 3; if (signerInfo[next] is Asn1TaggedObject) { Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next]; Asn1Sequence sseq = (Asn1Sequence)tagsig.GetObject(); MemoryStream bOut = new MemoryStream(); Asn1OutputStream dout = new Asn1OutputStream(bOut); try { Asn1EncodableVector attribute = new Asn1EncodableVector(); for (int k = 0; k < sseq.Count; ++k) { attribute.Add(sseq[k]); } dout.WriteObject(new DerSet(attribute)); dout.Close(); } catch (IOException){} sigAttr = bOut.ToArray(); for (int k = 0; k < sseq.Count; ++k) { Asn1Sequence seq2 = (Asn1Sequence)sseq[k]; if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) { Asn1Set sset = (Asn1Set)seq2[1]; digestAttr = ((DerOctetString)sset[0]).GetOctets(); break; } } if (digestAttr == null) throw new ArgumentException("Authenticated attribute is missing the digest."); ++next; } digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id; digest = ((DerOctetString)signerInfo[next]).GetOctets(); if (RSAdata != null || digestAttr != null) { messageDigest = GetHashClass(); } sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); sig.Init(false, signCert.GetPublicKey()); }
public Asn1SignatureVerifier (AlgorithmIdentifier algorithm, AsymmetricKeyParameter publicKey) { DerObjectIdentifier sigOid = algorithm.Algorithm; this.sig = SignerUtilities.GetSigner(sigOid); sig.Init(false, publicKey); this.algID = algorithm; }
public static void Main(String[] args) { // we make a connection to a PreSign servlet HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PRE); request.Method = "POST"; // we upload our self-signed certificate Stream os = request.GetRequestStream(); FileStream fis = new FileStream(CERT, FileMode.Open); int read; byte[] data = new byte[0x100]; while ((read = fis.Read(data, 0, data.Length)) != 0) { os.Write(data, 0, read); } os.Flush(); os.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // we use cookies to maintain a session String cookies = response.Headers["Set-Cookie"]; // we receive a hash that needs to be signed Stream istream = response.GetResponseStream(); MemoryStream baos = new MemoryStream(); data = new byte[0x100]; while ((read = istream.Read(data, 0, data.Length)) != 0) { baos.Write(data, 0, read); } istream.Close(); byte[] hash = baos.ToArray(); // we load our private key from the key store Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD); String alias = ""; // searching for private key foreach (string al in store.Aliases) { if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyEntry pk = store.GetKey(alias); // we sign the hash received from the server ISigner sig = SignerUtilities.GetSigner("SHA256withRSA"); sig.Init(true, pk.Key); sig.BlockUpdate(hash, 0, hash.Length); data = sig.GenerateSignature(); // we make a connection to the PostSign Servlet request = (HttpWebRequest)WebRequest.Create(POST); request.Headers.Add(HttpRequestHeader.Cookie, cookies.Split(";".ToCharArray(), 2)[0]); request.Method = "POST"; // we upload the signed bytes os = request.GetRequestStream(); os.Write(data, 0, data.Length); os.Flush(); os.Close(); // we receive the signed document response = (HttpWebResponse)request.GetResponse(); istream = response.GetResponseStream(); FileStream fos = new FileStream(DEST, FileMode.Create); data = new byte[0x100]; while ((read = istream.Read(data, 0, data.Length)) != 0) { fos.Write(data, 0, read); } istream.Close(); fos.Flush(); fos.Close(); }
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()); // } }
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"); 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 spec = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("2"), new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")), mod_q, BigInteger.One); 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]); } }
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))); }
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"); } }
/** * Use this constructor if you want to verify a signature using * the sub-filter adbe.pkcs7.detached or adbe.pkcs7.sha1. * @param contentsKey the /Contents key * @param tsp set to true if there's a PAdES LTV time stamp. * @param provider the provider or <code>null</code> for the default provider */ public PdfPKCS7(byte[] contentsKey, bool tsp) { isTsp = tsp; Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // Asn1Object pkcs; try { pkcs = din.ReadObject(); } catch { throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object")); } if (!(pkcs is Asn1Sequence)) { throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence")); } Asn1Sequence signedData = (Asn1Sequence)pkcs; DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0]; if (!objId.Id.Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA)) throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data")); Asn1Sequence content = (Asn1Sequence)((Asn1TaggedObject)signedData[1]).GetObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((DerInteger)content[0]).Value.IntValue; // the digestAlgorithms digestalgos = new Dictionary<string,object>(); IEnumerator e = ((Asn1Set)content[1]).GetEnumerator(); while (e.MoveNext()) { Asn1Sequence s = (Asn1Sequence)e.Current; DerObjectIdentifier o = (DerObjectIdentifier)s[0]; digestalgos[o.Id] = null; } // the certificates and crls X509CertificateParser cf = new X509CertificateParser(); certs = new List<X509Certificate>(); foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) { certs.Add(cc); } crls = new List<X509Crl>(); // the possible ID_PKCS7_DATA Asn1Sequence rsaData = (Asn1Sequence)content[2]; if (rsaData.Count > 1) { Asn1OctetString rsaDataContent = (Asn1OctetString)((Asn1TaggedObject)rsaData[1]).GetObject(); RSAdata = rsaDataContent.GetOctets(); } // the signerInfos int next = 3; while (content[next] is Asn1TaggedObject) ++next; Asn1Set signerInfos = (Asn1Set)content[next]; if (signerInfos.Count != 1) throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time")); Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0]; // the positions that we care are // 0 - version // 1 - the signing certificate issuer and serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((DerInteger)signerInfo[0]).Value.IntValue; // Get the signing certificate Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1]; Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]); BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value; foreach (X509Certificate cert in certs) { if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber)) { signCert = cert; break; } } if (signCert == null) { throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1", issuer.ToString() + " / " + serialNumber.ToString(16))); } CalcSignCertificateChain(); digestAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id; next = 3; if (signerInfo[next] is Asn1TaggedObject) { Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next]; Asn1Set sseq = Asn1Set.GetInstance(tagsig, false); sigAttr = sseq.GetEncoded(Asn1Encodable.Der); for (int k = 0; k < sseq.Count; ++k) { Asn1Sequence seq2 = (Asn1Sequence)sseq[k]; if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_MESSAGE_DIGEST)) { Asn1Set sset = (Asn1Set)seq2[1]; digestAttr = ((DerOctetString)sset[0]).GetOctets(); } else if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_ADBE_REVOCATION)) { Asn1Set setout = (Asn1Set)seq2[1]; Asn1Sequence seqout = (Asn1Sequence)setout[0]; for (int j = 0; j < seqout.Count; ++j) { Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j]; if (tg.TagNo == 1) { Asn1Sequence seqin = (Asn1Sequence)tg.GetObject(); FindOcsp(seqin); } if (tg.TagNo == 0) { Asn1Sequence seqin = (Asn1Sequence)tg.GetObject(); FindCRL(seqin); } } } } if (digestAttr == null) throw new ArgumentException(MessageLocalization.GetComposedMessage("authenticated.attribute.is.missing.the.digest")); ++next; } digestEncryptionAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id; digest = ((Asn1OctetString)signerInfo[next++]).GetOctets(); if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) { Asn1TaggedObject taggedObject = (Asn1TaggedObject) signerInfo[next]; Asn1Set unat = Asn1Set.GetInstance(taggedObject, false); Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat); Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]; if (ts != null && ts.AttrValues.Count > 0) { Asn1Set attributeValues = ts.AttrValues; Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]); Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence); this.timeStampToken = new TimeStampToken(contentInfo); } } if (isTsp) { Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfoTsp = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(signedData); this.timeStampToken = new TimeStampToken(contentInfoTsp); TimeStampTokenInfo info = timeStampToken.TimeStampInfo; String algOID = info.MessageImprintAlgOid; messageDigest = DigestUtilities.GetDigest(algOID); } else { if (RSAdata != null || digestAttr != null) { messageDigest = GetHashClass(); encContDigest = GetHashClass(); } sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); sig.Init(false, signCert.GetPublicKey()); } }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { 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)); #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || NETFX_CORE Stream sigStr = new SigOutputStream(sig); #else Stream sigStr = new BufferedStream(new SigOutputStream(sig)); #endif 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 (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); } } // 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.Dispose(); 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)); }
/// <summary> /// Base constructor. /// </summary> /// <param name="algorithm">The name of the signature algorithm to use.</param> /// <param name="publicKey">The public key to be used in the verification operation.</param> public Asn1SignatureVerifier (String algorithm, AsymmetricKeyParameter publicKey) { DerObjectIdentifier sigOid = X509Utilities.GetAlgorithmOid (algorithm); this.sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, publicKey); this.algID = X509Utilities.GetSigAlgID (sigOid, algorithm); }
private static bool SignFile(ref string filename) { Signing s = new Signing(); if (!s.LoadFile(filename)) { Console.WriteLine("error loading xml file:" + filename); Environment.Exit(-1); return(false); } AsymmetricKeyEntry key = null; Org.BouncyCastle.X509.X509Certificate cert = null; try { string signercert = ConfigurationManager.AppSettings["signercert"].ToString(); string signerpwd = ConfigurationManager.AppSettings["signerpwd"].ToString(); FileStream fs = new FileStream(signercert, FileMode.Open, FileAccess.Read); Pkcs12Store store = new Pkcs12Store(fs, signerpwd.ToCharArray()); string pName = null; foreach (string n in store.Aliases) { if (store.IsKeyEntry(n)) { pName = n; break; } } key = store.GetKey(pName); cert = store.GetCertificate(pName).Certificate; } catch (Exception) { Console.WriteLine("error loading signer (config)"); Environment.Exit(-1); return(false); } if ((null == key) || (null == cert)) { Console.WriteLine("error loading signer (config) (2)"); Environment.Exit(-1); return(false); } string signedxml = ""; try { byte[] tobesigned = s.AddSignature(cert); // sha256WithRSAEncryption DerObjectIdentifier signingAlgo = new DerObjectIdentifier("1.2.840.113549.1.1.11"); ISigner signer = SignerUtilities.GetSigner(signingAlgo); signer.Init(true, key.Key); signer.BlockUpdate(tobesigned, 0, tobesigned.Length); byte[] signed = signer.GenerateSignature(); s.SetSignature(signed); signedxml = s.GetXml(); } catch (Exception) { Console.WriteLine("error signing xml"); Environment.Exit(-1); return(false); } filename += ".sig"; File.WriteAllText(filename, signedxml); return(true); }
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))); }
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"); 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"); } }
private void processSRPKeyExchange( MemoryStream inStr, ISigner signer) { Stream sigIn = inStr; if (signer != null) { signer.Init(false, this.serverPublicKey); signer.BlockUpdate(this.clientRandom, 0, this.clientRandom.Length); signer.BlockUpdate(this.serverRandom, 0, this.serverRandom.Length); sigIn = new SignerStream(inStr, signer, null); } /* * Parse the Structure */ byte[] NByte = TlsUtilities.ReadOpaque16(sigIn); byte[] gByte = TlsUtilities.ReadOpaque16(sigIn); byte[] sByte = TlsUtilities.ReadOpaque8(sigIn); byte[] BByte = TlsUtilities.ReadOpaque16(sigIn); if (signer != null) { byte[] sigByte = TlsUtilities.ReadOpaque16(sigIn); /* * Verify the Signature. */ if (!signer.VerifySignature(sigByte)) { this.FailWithError(AL_fatal, AP_bad_certificate); } } this.AssertEmpty(inStr); BigInteger N = new BigInteger(1, NByte); BigInteger g = new BigInteger(1, gByte); byte[] s = sByte; BigInteger B = new BigInteger(1, BByte); Srp6Client srpClient = new Srp6Client(); srpClient.Init(N, g, new Sha1Digest(), random); this.SRP_A = srpClient.GenerateClientCredentials(s, this.SRP_identity, this.SRP_password); try { BigInteger S = srpClient.CalculateSecret(B); this.pms = BigIntegers.AsUnsignedByteArray(S); } catch (CryptoException) { this.FailWithError(AL_fatal, AP_illegal_parameter); } }
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"); } }
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]); } }
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"); } }
private bool VerifyDigest( byte[] digest, IAsymmetricKeyParameter key, byte[] signature) { string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid); try { if (algorithm.Equals("RSA")) { IBufferedCipher c = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding"); c.Init(false, key); byte[] decrypt = c.DoFinal(signature); DigestInfo digInfo = DerDecode(decrypt); if (!digInfo.AlgorithmID.ObjectID.Equals(digestAlgorithm.ObjectID)) { return(false); } if (!IsNull(digInfo.AlgorithmID.Parameters)) { return(false); } byte[] sigHash = digInfo.GetDigest(); return(Arrays.ConstantTimeAreEqual(digest, sigHash)); } else if (algorithm.Equals("DSA")) { ISigner sig = SignerUtilities.GetSigner("NONEwithDSA"); sig.Init(false, key); sig.BlockUpdate(digest, 0, digest.Length); return(sig.VerifySignature(signature)); } else { throw new CmsException("algorithm: " + algorithm + " not supported in base signatures."); } } catch (SecurityUtilityException e) { throw e; } catch (GeneralSecurityException e) { throw new CmsException("Exception processing signature: " + e, e); } catch (IOException e) { throw new CmsException("Exception decoding signature: " + e, e); } }
/* * we generate a self signed certificate for the sake of testing - SHA224withECDSA */ private void createECRequest( string algorithm, DerObjectIdentifier algOid) { X9ECParameters x9 = ECNamedCurveTable.GetByName("secp521r1"); ECCurve curve = x9.Curve; ECDomainParameters spec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d spec); ECPublicKeyParameters pubKey = new ECPublicKeyParameters( // curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q spec); // // // // set up the keys // // // AsymmetricKeyParameter privKey; // AsymmetricKeyParameter pubKey; // // KeyFactory fact = KeyFactory.getInstance("ECDSA"); // // privKey = fact.generatePrivate(privKeySpec); // pubKey = fact.generatePublic(pubKeySpec); Pkcs10CertificationRequest req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC encoded."); } // // try with point compression turned off // // ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); ECPoint q = pubKey.Q.Normalize(); pubKey = new ECPublicKeyParameters( pubKey.AlgorithmName, q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()), pubKey.Parameters); req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC uncompressed."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC uncompressed encoded."); } if (!req.SignatureAlgorithm.Algorithm.Equals(algOid)) { Fail("ECDSA oid incorrect."); } if (req.SignatureAlgorithm.Parameters != null) { Fail("ECDSA parameters incorrect."); } ISigner sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, pubKey); byte[] b = req.GetCertificationRequestInfo().GetEncoded(); sig.BlockUpdate(b, 0, b.Length); if (!sig.VerifySignature(req.GetSignatureOctets())) { Fail("signature not mapped correctly."); } }
public void InitPrivateKey(RsaKeyParameters privatKey) { _signer.Reset(); _signer.Init(true, privatKey); }
private OcspReq GenerateRequest(DerObjectIdentifier signingAlgorithm, AsymmetricKeyParameter privateKey, X509Certificate[] chain, SecureRandom random) { Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (OcspReqGenerator.RequestObject requestObject in this.list) { try { asn1EncodableVector.Add(new Asn1Encodable[] { requestObject.ToRequest() }); } catch (Exception e) { throw new OcspException("exception creating Request", e); } } TbsRequest tbsRequest = new TbsRequest(this.requestorName, new DerSequence(asn1EncodableVector), this.requestExtensions); ISigner signer = null; Signature optionalSignature = null; if (signingAlgorithm != null) { if (this.requestorName == null) { throw new OcspException("requestorName must be specified if request is signed."); } try { signer = SignerUtilities.GetSigner(signingAlgorithm.Id); if (random != null) { signer.Init(true, new ParametersWithRandom(privateKey, random)); } else { signer.Init(true, privateKey); } } catch (Exception ex) { throw new OcspException("exception creating signature: " + ex, ex); } DerBitString signatureValue = null; try { byte[] encoded = tbsRequest.GetEncoded(); signer.BlockUpdate(encoded, 0, encoded.Length); signatureValue = 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(new Asn1Encodable[0]); try { for (int num = 0; num != chain.Length; num++) { asn1EncodableVector2.Add(new Asn1Encodable[] { X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(chain[num].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, signatureValue, new DerSequence(asn1EncodableVector2)); } else { optionalSignature = new Signature(signatureAlgorithm, signatureValue); } } return(new OcspReq(new OcspRequest(tbsRequest, optionalSignature))); }
/// <inheritdoc/> protected override async Task OnOpenAsync(CancellationToken token = default(CancellationToken)) { 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($"UserIdentity: '{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.options.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; bool verified = false; switch (this.RemoteEndpoint.SecurityPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: case SecurityPolicyUris.Basic256: verifier = SignerUtilities.GetSigner("SHA-1withRSA"); verifier.Init(false, this.RemotePublicKey); verifier.BlockUpdate(localCertificate, 0, localCertificate.Length); verifier.BlockUpdate(localNonce, 0, localNonce.Length); verified = verifier.VerifySignature(createSessionResponse.ServerSignature.Signature); break; case SecurityPolicyUris.Basic256Sha256: verifier = SignerUtilities.GetSigner("SHA-256withRSA"); verifier.Init(false, this.RemotePublicKey); verifier.BlockUpdate(localCertificate, 0, localCertificate.Length); verifier.BlockUpdate(localNonce, 0, localNonce.Length); verified = verifier.VerifySignature(createSessionResponse.ServerSignature.Signature); break; default: verified = true; break; } verifier = null; if (!verified) { throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid, "Server did not provide a correct signature for the nonce data provided by the client."); } } // create client signature SignatureData clientSignature = null; ISigner signer = null; switch (this.RemoteEndpoint.SecurityPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: case SecurityPolicyUris.Basic256: signer = SignerUtilities.GetSigner("SHA-1withRSA"); signer.Init(true, this.LocalPrivateKey); signer.BlockUpdate(this.RemoteEndpoint.ServerCertificate, 0, this.RemoteEndpoint.ServerCertificate.Length); signer.BlockUpdate(this.RemoteNonce, 0, this.RemoteNonce.Length); clientSignature = new SignatureData { Signature = signer.GenerateSignature(), Algorithm = RsaSha1Signature, }; break; case SecurityPolicyUris.Basic256Sha256: signer = SignerUtilities.GetSigner("SHA-256withRSA"); signer.Init(true, this.LocalPrivateKey); signer.BlockUpdate(this.RemoteEndpoint.ServerCertificate, 0, this.RemoteEndpoint.ServerCertificate.Length); signer.BlockUpdate(this.RemoteNonce, 0, this.RemoteNonce.Length); clientSignature = new SignatureData { Signature = signer.GenerateSignature(), Algorithm = RsaSha256Signature, }; break; default: clientSignature = new SignatureData(); break; } signer = null; // 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); IBufferedCipher encryptor; byte[] cipherText; int pos; var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri; switch (secPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: encryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding"); encryptor.Init(true, this.RemotePublicKey); cipherText = new byte[encryptor.GetOutputSize(4 + plainText.Length)]; pos = encryptor.ProcessBytes(BitConverter.GetBytes(plainText.Length), cipherText, 0); pos = encryptor.DoFinal(plainText, cipherText, pos); identityToken = new IssuedIdentityToken { TokenData = cipherText, EncryptionAlgorithm = RsaV15KeyWrap, PolicyId = tokenPolicy.PolicyId }; break; case SecurityPolicyUris.Basic256: case SecurityPolicyUris.Basic256Sha256: encryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding"); encryptor.Init(true, this.RemotePublicKey); cipherText = new byte[encryptor.GetOutputSize(4 + plainText.Length)]; pos = encryptor.ProcessBytes(BitConverter.GetBytes(plainText.Length), cipherText, 0); pos = encryptor.DoFinal(plainText, cipherText, pos); identityToken = new IssuedIdentityToken { TokenData = cipherText, EncryptionAlgorithm = RsaOaepKeyWrap, PolicyId = tokenPolicy.PolicyId }; break; default: identityToken = new IssuedIdentityToken { TokenData = issuedIdentity.TokenData, EncryptionAlgorithm = null, PolicyId = tokenPolicy.PolicyId }; break; } tokenSignature = new SignatureData(); plainText = null; encryptor = null; cipherText = null; } // 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; * } * * dataToSign = null; */ } // 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[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(userNameIdentity.Password); int plainTextLength = passwordBytes.Length + this.RemoteNonce.Length; IBufferedCipher encryptor; byte[] cipherText; int pos; var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri; switch (secPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: encryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding"); encryptor.Init(true, this.RemotePublicKey); cipherText = new byte[encryptor.GetOutputSize(4 + plainTextLength)]; pos = encryptor.ProcessBytes(BitConverter.GetBytes(plainTextLength), cipherText, 0); pos = encryptor.ProcessBytes(passwordBytes, cipherText, pos); pos = encryptor.DoFinal(this.RemoteNonce, cipherText, pos); identityToken = new UserNameIdentityToken { UserName = userNameIdentity.UserName, Password = cipherText, EncryptionAlgorithm = RsaV15KeyWrap, PolicyId = tokenPolicy.PolicyId }; break; case SecurityPolicyUris.Basic256: case SecurityPolicyUris.Basic256Sha256: encryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING"); encryptor.Init(true, this.RemotePublicKey); cipherText = new byte[encryptor.GetOutputSize(4 + plainTextLength)]; pos = encryptor.ProcessBytes(BitConverter.GetBytes(plainTextLength), cipherText, 0); pos = encryptor.ProcessBytes(passwordBytes, cipherText, pos); pos = encryptor.DoFinal(this.RemoteNonce, cipherText, pos); identityToken = new UserNameIdentityToken { UserName = userNameIdentity.UserName, Password = cipherText, EncryptionAlgorithm = RsaOaepKeyWrap, PolicyId = tokenPolicy.PolicyId }; break; default: identityToken = new UserNameIdentityToken { UserName = userNameIdentity.UserName, Password = passwordBytes, EncryptionAlgorithm = null, PolicyId = tokenPolicy.PolicyId }; break; } tokenSignature = new SignatureData(); passwordBytes = null; encryptor = null; cipherText = null; } // 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[]>()); } } // create the keep alive subscription. var subscriptionRequest = new CreateSubscriptionRequest { RequestedPublishingInterval = DefaultPublishingInterval, RequestedMaxKeepAliveCount = DefaultKeepaliveCount, RequestedLifetimeCount = DefaultKeepaliveCount * 3, PublishingEnabled = true, }; var subscriptionResponse = await this.CreateSubscriptionAsync(subscriptionRequest).ConfigureAwait(true); // link up the dataflow blocks var id = subscriptionResponse.SubscriptionId; var linkToken = this.LinkTo(this.actionBlock, pr => pr.SubscriptionId == id); // start publishing. this.stateMachineTask = Task.Run(() => this.StateMachineAsync(this.stateMachineCts.Token)); }
public static void InitSign(this ISigner signer, ICipherParameters pk) { signer.Init(true, pk); }
public static void InitVerify(this ISigner signer, AsymmetricKeyParameter publicKey) { signer.Init(false, publicKey); }
/// <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, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter 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.ToUpperInvariant(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()); }
protected virtual void CheckSignature( IAsymmetricKeyParameter publicKey, ISigner signature) { if (!IsAlgIDEqual(c.SignatureAlgorithm, c.TbsCertificate.Signature)) throw new CertificateException("signature algorithm in TBS cert not same as outer cert"); Asn1Encodable parameters = c.SignatureAlgorithm.Parameters; X509SignatureUtilities.SetSignatureParameters(signature, parameters); signature.Init(false, publicKey); byte[] b = this.GetTbsCertificate(); signature.BlockUpdate(b, 0, b.Length); byte[] sig = this.GetSignature(); if (!signature.VerifySignature(sig)) { throw new InvalidKeyException("Public key presented not for certificate signature"); } }
/* * we generate a self signed certificate for the sake of testing - SHA224withECDSA */ private void createECRequest( string algorithm, DerObjectIdentifier algOid) { FpCurve curve = new FpCurve( new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p) new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b ECDomainParameters spec = new ECDomainParameters( curve, // curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d spec); ECPublicKeyParameters pubKey = new ECPublicKeyParameters( // curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q spec); // // // // set up the keys // // // AsymmetricKeyParameter privKey; // AsymmetricKeyParameter pubKey; // // KeyFactory fact = KeyFactory.getInstance("ECDSA"); // // privKey = fact.generatePrivate(privKeySpec); // pubKey = fact.generatePublic(pubKeySpec); Pkcs10CertificationRequest req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC encoded."); } // // try with point compression turned off // // ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); ECPoint q = pubKey.Q.Normalize(); pubKey = new ECPublicKeyParameters( pubKey.AlgorithmName, q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()), pubKey.Parameters); req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC uncompressed."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC uncompressed encoded."); } if (!req.SignatureAlgorithm.ObjectID.Equals(algOid)) { Fail("ECDSA oid incorrect."); } if (req.SignatureAlgorithm.Parameters != null) { Fail("ECDSA parameters incorrect."); } ISigner sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, pubKey); byte[] b = req.GetCertificationRequestInfo().GetEncoded(); sig.BlockUpdate(b, 0, b.Length); if (!sig.VerifySignature(req.Signature.GetBytes())) { Fail("signature not mapped correctly."); } }
// Constructors for creating new signatures /** * Assembles all the elements needed to create a signature, except for the data. * @param privKey the private key * @param certChain the certificate chain * @param crlList the certificate revocation list * @param hashAlgorithm the hash algorithm * @param provider the provider or <code>null</code> for the default provider * @param hasRSAdata <CODE>true</CODE> if the sub-filter is adbe.pkcs7.sha1 * @throws InvalidKeyException on error * @throws NoSuchProviderException on error * @throws NoSuchAlgorithmException on error */ public PdfPKCS7(ICipherParameters privKey, ICollection<X509Certificate> certChain, String hashAlgorithm, bool hasRSAdata) { digestAlgorithmOid = DigestAlgorithms.GetAllowedDigests(hashAlgorithm); if (digestAlgorithmOid == null) throw new ArgumentException(MessageLocalization.GetComposedMessage("unknown.hash.algorithm.1", hashAlgorithm)); version = signerversion = 1; certs = new List<X509Certificate>(certChain); crls = new List<X509Crl>(); digestalgos = new Dictionary<string,object>(); digestalgos[digestAlgorithmOid] = null; // // Copy in the certificates and crls used to sign the private key. // signCert = certs[0]; if (privKey != null) { // // Now we have private key, find out what the digestEncryptionAlgorithm is. // if (privKey is RsaKeyParameters) digestEncryptionAlgorithmOid = SecurityIDs.ID_RSA; else if (privKey is DsaKeyParameters) digestEncryptionAlgorithmOid = SecurityIDs.ID_DSA; else throw new ArgumentException(MessageLocalization.GetComposedMessage("unknown.key.algorithm.1", privKey.ToString())); } if (hasRSAdata) { RSAdata = new byte[0]; messageDigest = GetHashClass(); } if (privKey != null) { sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); sig.Init(true, privKey); } }
/// <summary> /// verify signature /// </summary> /// <param name="signer">signature interface</param> /// <param name="key">EC public key</param> /// <param name="src">source data</param> /// <param name="signature">signature data</param> /// <returns></returns> public static bool Verify(this ISigner signer, ECPublicKeyParameters key, byte[] src, byte[] signature) { signer.Init(false, key); signer.BlockUpdate(src, 0, src.Length); return(signer.VerifySignature(signature)); }
/** * Verifies a signature using the sub-filter adbe.x509.rsa_sha1. * @param contentsKey the /Contents key * @param certsKey the /Cert key * @param provider the provider or <code>null</code> for the default provider */ public PdfPKCS7(byte[] contentsKey, byte[] certsKey) { X509CertificateParser cf = new X509CertificateParser(); certs = new ArrayList(); foreach (X509Certificate cc in cf.ReadCertificates(certsKey)) { certs.Add(cc); } signCerts = certs; signCert = (X509Certificate)certs[0]; crls = new ArrayList(); Asn1InputStream inp = new Asn1InputStream(new MemoryStream(contentsKey)); digest = ((DerOctetString)inp.ReadObject()).GetOctets(); sig = SignerUtilities.GetSigner("SHA1withRSA"); sig.Init(false, signCert.GetPublicKey()); }
// TODO Move this when other JCE tests are ported from Java /** * signature with a "forged signature" (sig block not at end of plain text) */ private void doTestBadSig()//PrivateKey priv, PublicKey pub) { // Signature sig = Signature.getInstance("SHA1WithRSAEncryption", "BC"); ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption"); // KeyPairGenerator fact; // KeyPair keyPair; // byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // fact = KeyPairGenerator.getInstance("RSA", "BC"); RsaKeyPairGenerator fact = new RsaKeyPairGenerator(); // fact.initialize(768, new SecureRandom()); RsaKeyGenerationParameters factParams = new RsaKeyGenerationParameters( // BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25); BigInteger.ValueOf(3), new SecureRandom(), 768, 25); fact.Init(factParams); // keyPair = fact.generateKeyPair(); // // PrivateKey signingKey = keyPair.getPrivate(); // PublicKey verifyKey = keyPair.getPublic(); AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair(); AsymmetricKeyParameter priv = keyPair.Private; AsymmetricKeyParameter pub = keyPair.Public; // testBadSig(signingKey, verifyKey); // MessageDigest sha1 = MessageDigest.getInstance("SHA1", "BC"); IDigest sha1 = DigestUtilities.GetDigest("SHA1"); // Cipher signer = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); // IBufferedCipher signer = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine()); // signer.init(Cipher.ENCRYPT_MODE, priv); signer.Init(true, priv); // byte[] block = new byte[signer.getBlockSize()]; // byte[] block = new byte[signer.GetBlockSize()]; byte[] block = new byte[signer.GetInputBlockSize()]; // sha1.update((byte)0); sha1.Update(0); // byte[] sigHeader = Hex.decode("3021300906052b0e03021a05000414"); byte[] sigHeader = Hex.Decode("3021300906052b0e03021a05000414"); // System.arraycopy(sigHeader, 0, block, 0, sigHeader.length); Array.Copy(sigHeader, 0, block, 0, sigHeader.Length); // sha1.digest(block, sigHeader.length, sha1.getDigestLength()); sha1.DoFinal(block, sigHeader.Length); // System.arraycopy(sigHeader, 0, block, // sigHeader.length + sha1.getDigestLength(), sigHeader.length); Array.Copy(sigHeader, 0, block, sigHeader.Length + sha1.GetDigestSize(), sigHeader.Length); // byte[] sigBytes = signer.doFinal(block); byte[] sigBytes = signer.ProcessBlock(block, 0, block.Length); // Signature verifier = Signature.getInstance("SHA1WithRSA", "BC"); ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA"); // verifier.initVerify(pub); verifier.Init(false, pub); // verifier.update((byte)0); verifier.Update(0); // if (verifier.verify(sig)) if (verifier.VerifySignature(sigBytes)) { // fail("bad signature passed"); Fail("bad signature passed"); } }
/** * Generates a signature. * @param privKey the private key * @param certChain the certificate chain * @param crlList the certificate revocation list * @param hashAlgorithm the hash algorithm * @param provider the provider or <code>null</code> for the default provider * @param hasRSAdata <CODE>true</CODE> if the sub-filter is adbe.pkcs7.sha1 * @throws SecurityException on error * @throws InvalidKeyException on error * @throws NoSuchProviderException on error * @throws NoSuchAlgorithmException on error */ public PdfPKCS7(ICipherParameters privKey, X509Certificate[] certChain, object[] crlList, String hashAlgorithm, bool hasRSAdata) { this.privKey = privKey; digestAlgorithm = (String)allowedDigests[hashAlgorithm.ToUpper(CultureInfo.InvariantCulture)]; if (digestAlgorithm == null) throw new ArgumentException("Unknown Hash Algorithm "+hashAlgorithm); version = signerversion = 1; certs = new ArrayList(); crls = new ArrayList(); digestalgos = new Hashtable(); digestalgos[digestAlgorithm] = null; // // Copy in the certificates and crls used to sign the private key. // signCert = certChain[0]; for (int i = 0;i < certChain.Length;i++) { certs.Add(certChain[i]); } // if (crlList != null) { // for (int i = 0;i < crlList.length;i++) { // crls.Add(crlList[i]); // } // } if (privKey != null) { // // Now we have private key, find out what the digestEncryptionAlgorithm is. // if (privKey is RsaKeyParameters) digestEncryptionAlgorithm = ID_RSA; else if (privKey is DsaKeyParameters) digestEncryptionAlgorithm = ID_DSA; else throw new ArgumentException("Unknown Key Algorithm "+privKey.ToString()); } if (hasRSAdata) { RSAdata = new byte[0]; messageDigest = GetHashClass(); } if (privKey != null) { sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); sig.Init(true, privKey); } }
/// <summary> /// Constructor which also specifies a source of randomness to be used if one is required. /// </summary> /// <param name="algorithm">The name of the signature algorithm to use.</param> /// <param name="privateKey">The private key to be used in the signing operation.</param> /// <param name="random">The source of randomness to be used in signature calculation.</param> public Asn1SignatureCalculator (String algorithm, AsymmetricKeyParameter privateKey, SecureRandom random) { DerObjectIdentifier sigOid = X509Utilities.GetAlgorithmOid (algorithm); this.sig = SignerUtilities.GetSigner(algorithm); if (random != null) { sig.Init(true, new ParametersWithRandom(privateKey, random)); } else { sig.Init(true, privateKey); } this.algID = X509Utilities.GetSigAlgID (sigOid, algorithm); }