public void TestRsaDigestSigner() { BigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ==")); BigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ==")); BigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ==")); BigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E=")); BigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE=")); BigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0=")); BigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg==")); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); byte[] msg = new byte[] { 1, 6, 3, 32, 7, 43, 2, 5, 7, 78, 4, 23 }; RsaDigestSigner signer = new RsaDigestSigner(new Sha1Digest()); signer.Init(true, rsaPrivate); signer.BlockUpdate(msg, 0, msg.Length); byte[] sig = signer.GenerateSignature(); signer.Init(false,rsaPublic); signer.BlockUpdate(msg, 0, msg.Length); Assert.IsTrue(signer.VerifySignature(sig), "RSA IDigest Signer failed."); }
//---------------------------------------私钥转换 public static void getPriKeyPem() { var rsa = new RSACryptoServiceProvider(); using (var sr = new StreamReader("E:\\PriKey.xml")) { rsa.FromXmlString(sr.ReadToEnd()); } var p = rsa.ExportParameters(true); var key = new RsaPrivateCrtKeyParameters( new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent), new BigInteger(1, p.D), new BigInteger(1, p.P), new BigInteger(1, p.Q), new BigInteger(1, p.DP), new BigInteger(1, p.DQ), new BigInteger(1, p.InverseQ)); using (var sw = new StreamWriter("e:\\PriKey.pem")) { var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw); pemWriter.WriteObject(key); } }
public AsymmetricCipherKeyPair GetRsaKeyPair( RSACryptoServiceProvider rsaCsp) { RSAParameters rp = rsaCsp.ExportParameters(true); BigInteger modulus = new BigInteger(1, rp.Modulus); BigInteger pubExp = new BigInteger(1, rp.Exponent); RsaKeyParameters pubKey = new RsaKeyParameters( false, modulus, pubExp); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( modulus, pubExp, new BigInteger(1, rp.D), new BigInteger(1, rp.P), new BigInteger(1, rp.Q), new BigInteger(1, rp.DP), new BigInteger(1, rp.DQ), new BigInteger(1, rp.InverseQ)); return new AsymmetricCipherKeyPair(pubKey, privKey); }
public static void WritePkcs12(RsaPrivateCrtKeyParameters privKey, Org.BouncyCastle.X509.X509Certificate certificate, string password, Stream stream) { Pkcs12Store store = new Pkcs12Store(); X509CertificateEntry[] chain = new X509CertificateEntry[1]; chain[0] = new X509CertificateEntry(certificate); store.SetKeyEntry("privateKey", new AsymmetricKeyEntry(privKey), chain); store.Save(stream, password.ToCharArray(), new SecureRandom()); }
public Key(int strength) { var generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), strength)); _keyPair = generator.GenerateKeyPair(); _rsaKey = _keyPair.Private as RsaPrivateCrtKeyParameters; PublicKey = new PublicKey(_keyPair.Public as RsaKeyParameters); }
public Key(string pem) { var k = new CertificateLoader().LoadFirst<AsymmetricCipherKeyPair>("key", pem); _rsaKey = k.Private as RsaPrivateCrtKeyParameters; if (_rsaKey == null) throw new SecularException("Cannot find key in PEM string."); var rsaKeyParameters = new RsaKeyParameters(false, _rsaKey.Modulus, _rsaKey.PublicExponent); PublicKey = new PublicKey(rsaKeyParameters); }
static Rsa() { var openTibiaDecryptKey = new RsaPrivateCrtKeyParameters(new BigInteger(Constants.RSAKey.OpenTibiaM), new BigInteger(Constants.RSAKey.OpenTibiaE), new BigInteger(Constants.RSAKey.OpenTibiaE), new BigInteger(Constants.RSAKey.OpenTibiaP), new BigInteger(Constants.RSAKey.OpenTibiaQ), new BigInteger(Constants.RSAKey.OpenTibiaDP), new BigInteger(Constants.RSAKey.OpenTibiaDQ), new BigInteger(Constants.RSAKey.OpenTibiaInverseQ)); openTibiaDecryptEngine = new RsaEngine(); openTibiaDecryptEngine.Init(false, openTibiaDecryptKey); var realTibiaEncryptKey = new RsaKeyParameters(false, new BigInteger(Constants.RSAKey.RealTibiaM), new BigInteger(Constants.RSAKey.RealTibiaE)); realTibiaEncryptEngine = new RsaEngine(); realTibiaEncryptEngine.Init(true, realTibiaEncryptKey); var openTibiaEncryptKey = new RsaKeyParameters(false, new BigInteger(Constants.RSAKey.OpenTibiaM), new BigInteger(Constants.RSAKey.OpenTibiaE)); openTibiaEncryptEngine = new RsaEngine(); openTibiaEncryptEngine.Init(true, openTibiaEncryptKey); }
public static RSA ToRSA(RsaPrivateCrtKeyParameters rsaKey) { var parameters = new RSAParameters { Modulus = rsaKey.Modulus.ToByteArrayUnsigned(), Exponent = rsaKey.PublicExponent.ToByteArrayUnsigned(), P = rsaKey.P.ToByteArrayUnsigned(), Q = rsaKey.Q.ToByteArrayUnsigned() }; parameters.D = ConvertRsaParametersField(rsaKey.Exponent, parameters.Modulus.Length); parameters.DP = ConvertRsaParametersField(rsaKey.DP, parameters.P.Length); parameters.DQ = ConvertRsaParametersField(rsaKey.DQ, parameters.Q.Length); parameters.InverseQ = ConvertRsaParametersField(rsaKey.QInv, parameters.Q.Length); var cryptoServiceProvider = RSA.Create(); cryptoServiceProvider.ImportParameters(parameters); return cryptoServiceProvider; }
public override bool Equals( object obj) { if (obj == this) { return(true); } RsaPrivateCrtKeyParameters kp = obj as RsaPrivateCrtKeyParameters; if (kp == null) { return(false); } return(kp.DP.Equals(dP) && kp.DQ.Equals(dQ) && kp.Exponent.Equals(this.Exponent) && kp.Modulus.Equals(this.Modulus) && kp.P.Equals(p) && kp.Q.Equals(q) && kp.PublicExponent.Equals(e) && kp.QInv.Equals(qInv)); }
public static AsymmetricCipherKeyPair GetRsaKeyPair( RSAParameters rp) { BigInteger modulus = new BigInteger(1, rp.Modulus); BigInteger pubExp = new BigInteger(1, rp.Exponent); RsaKeyParameters pubKey = new RsaKeyParameters( false, modulus, pubExp); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( modulus, pubExp, new BigInteger(1, rp.D), new BigInteger(1, rp.P), new BigInteger(1, rp.Q), new BigInteger(1, rp.DP), new BigInteger(1, rp.DQ), new BigInteger(1, rp.InverseQ)); return new AsymmetricCipherKeyPair(pubKey, privKey); }
/// <summary> /// Extract a <c>PgpPrivateKey</c> from this secret key's encrypted contents. /// </summary> /// <param name="passPhrase"></param> /// <returns></returns> /// <exception cref="PgpException"> /// unknown public key algorithm encountered /// or /// Exception constructing key /// </exception> public IPgpPrivateKey ExtractPrivateKey(char[] passPhrase) { var secKeyData = _secret.GetSecretKeyData(); if (secKeyData == null || secKeyData.Length < 1) return null; var pubPk = _secret.PublicKeyPacket; try { var data = ExtractKeyData(passPhrase); using (var memory = new MemoryStream(data, false)) { using (var bcpgIn = BcpgInputStream.Wrap(memory)) { IAsymmetricKeyParameter privateKey; switch (pubPk.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaSign: var rsaPub = (RsaPublicBcpgKey)pubPk.Key; var rsaPriv = new RsaSecretBcpgKey(bcpgIn); var rsaPrivSpec = new RsaPrivateCrtKeyParameters( rsaPriv.Modulus, rsaPub.PublicExponent, rsaPriv.PrivateExponent, rsaPriv.PrimeP, rsaPriv.PrimeQ, rsaPriv.PrimeExponentP, rsaPriv.PrimeExponentQ, rsaPriv.CrtCoefficient); privateKey = rsaPrivSpec; break; case PublicKeyAlgorithmTag.Dsa: var dsaPub = (DsaPublicBcpgKey)pubPk.Key; var dsaPriv = new DsaSecretBcpgKey(bcpgIn); var dsaParams = new DsaParameters(dsaPub.P, dsaPub.Q, dsaPub.G); privateKey = new DsaPrivateKeyParameters(dsaPriv.X, dsaParams); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: var elPub = (ElGamalPublicBcpgKey)pubPk.Key; var elPriv = new ElGamalSecretBcpgKey(bcpgIn); var elParams = new ElGamalParameters(elPub.P, elPub.G); privateKey = new ElGamalPrivateKeyParameters(elPriv.X, elParams); break; case PublicKeyAlgorithmTag.Ecdh: var ecdhPub = (ECDHPublicBcpgKey)pubPk.Key; var ecdhPriv = new ECSecretBcpgKey(bcpgIn); privateKey = new ECDHPrivateKeyParameters(ecdhPriv.X, new ECDHPublicKeyParameters(ecdhPub.Point, ecdhPub.Oid, ecdhPub.HashAlgorithm, ecdhPub.SymmetricKeyAlgorithm), PgpPublicKey.BuildFingerprint(pubPk)); break; case PublicKeyAlgorithmTag.Ecdsa: var ecdsaPub = (ECPublicBcpgKey)pubPk.Key; var ecdsaPriv = new ECSecretBcpgKey(bcpgIn); privateKey = new ECPrivateKeyParameters(pubPk.Algorithm.ToString(), ecdsaPriv.X, ecdsaPub.Oid); break; default: throw new PgpException("unknown public key algorithm encountered"); } return new PgpPrivateKey(privateKey, KeyId); } } } catch (PgpException) { throw; } catch (Exception e) { throw new PgpException("Exception constructing key", e); } }
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 static void GenerateSigningCertificate(ICertificatePolicy certificatePolicy, out string thumbprint, out string pemPublicCert, out byte[] pkcs12Data, out System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2) { // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); X509Name certName; if (certificatePolicy.X509NameDictionary == null || !certificatePolicy.X509NameDictionary.Any()) { certName = new X509Name("CN=" + certificatePolicy.CommonName); } else { var list = new Dictionary<string, string>(); AddSubjectNameItem(list, "CN", certificatePolicy.CommonName); foreach (var item in certificatePolicy.X509NameDictionary) { AddSubjectNameItem(list, item.Key, item.Value); } certName = new X509Name(GetSubjectNameItemString(list)); } BigInteger serialNo; serialNo = BigInteger.ProbablePrime(120, random); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(certName); gen.SetNotBefore(DateTime.UtcNow.AddHours(-2)); // go back 2 hours just to be safe gen.SetNotAfter(DateTime.UtcNow.AddDays(certificatePolicy.ValidForDays)); gen.SetSignatureAlgorithm("SHA256WithRSA"); gen.SetPublicKey(subjectKeyPair.Public); gen.AddExtension( X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); gen.AddExtension(X509Extensions.KeyUsage.Id, true, new KeyUsage(KeyUsage.DigitalSignature)); // handle our key purposes if (!certificatePolicy.AllPurposes) { var purposes = new List<KeyPurposeID>(); if (certificatePolicy.ServerAuthentication) { purposes.Add(KeyPurposeID.IdKPServerAuth); } if (certificatePolicy.ClientAuthentication) { purposes.Add(KeyPurposeID.IdKPClientAuth); } if (certificatePolicy.CodeSigning) { purposes.Add(KeyPurposeID.IdKPCodeSigning); } if (purposes.Any()) { gen.AddExtension( X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(purposes.ToArray())); } } var certificate = gen.Generate(subjectKeyPair.Private, random); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); // this is exportable to get the bytes of the key to our file system in an encrypted manner RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.PersistKeyInCsp = false; // do not persist rsaKey.ImportParameters(rsaParameters); var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); x509.PrivateKey = rsaKey; // this is non-exportable CspParameters cspParametersNoExport = new CspParameters(); cspParametersNoExport.KeyContainerName = Guid.NewGuid().ToString(); cspParametersNoExport.Flags = CspProviderFlags.UseNonExportableKey; RSACryptoServiceProvider rsaKey2 = new RSACryptoServiceProvider(2048, cspParametersNoExport); rsaKey2.PersistKeyInCsp = false; // do not persist rsaKey2.ImportParameters(rsaParameters); x509Certificate2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); x509Certificate2.PrivateKey = rsaKey2; //// Generating Random Numbers //var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; //var rnd = new Random(); //password = new string( // Enumerable.Repeat(chars, 15) // .Select(s => s[rnd.Next(s.Length)]) // .ToArray()); thumbprint = x509.Thumbprint.ToLower(); var publicKeyPem = new StringBuilder(); var utf8WithoutBom = new System.Text.UTF8Encoding(false); var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom)); publicKeyPemWriter.WriteObject(certificate); publicKeyPemWriter.Writer.Flush(); pemPublicCert = publicKeyPem.ToString(); pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx); }
public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey) { RSAParameters rp = new RSAParameters(); rp.Modulus = privKey.Modulus.ToByteArrayUnsigned(); rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned(); rp.P = privKey.P.ToByteArrayUnsigned(); rp.Q = privKey.Q.ToByteArrayUnsigned(); rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length); rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length); rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length); rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length); return rp; }
public override void PerformTest() { // // personal keys // RsaPublicKeyStructure pubKeySpec = new RsaPublicKeyStructure( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters privKeySpec = new RsaPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // // intermediate keys. // RsaPublicKeyStructure intPubKeySpec = new RsaPublicKeyStructure( new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), new BigInteger("ffff", 16)); RsaPrivateCrtKeyParameters intPrivKeySpec = new RsaPrivateCrtKeyParameters( new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), new BigInteger("ffff", 16), new BigInteger("7deb1b194a85bcfd29cf871411468adbc987650903e3bacc8338c449ca7b32efd39ffc33bc84412fcd7df18d23ce9d7c25ea910b1ae9985373e0273b4dca7f2e0db3b7314056ac67fd277f8f89cf2fd73c34c6ca69f9ba477143d2b0e2445548aa0b4a8473095182631da46844c356f5e5c7522eb54b5a33f11d730ead9c0cff", 16), new BigInteger("ef4cede573cea47f83699b814de4302edb60eefe426c52e17bd7870ec7c6b7a24fe55282ebb73775f369157726fcfb988def2b40350bdca9e5b418340288f649", 16), new BigInteger("97c7737d1b9a0088c3c7b528539247fd2a1593e7e01cef18848755be82f4a45aa093276cb0cbf118cb41117540a78f3fc471ba5d69f0042274defc9161265721", 16), new BigInteger("6c641094e24d172728b8da3c2777e69adfd0839085be7e38c7c4a2dd00b1ae969f2ec9d23e7e37090fcd449a40af0ed463fe1c612d6810d6b4f58b7bfa31eb5f", 16), new BigInteger("70b7123e8e69dfa76feb1236d0a686144b00e9232ed52b73847e74ef3af71fb45ccb24261f40d27f98101e230cf27b977a5d5f1f15f6cf48d5cb1da2a3a3b87f", 16), new BigInteger("e38f5750d97e270996a286df2e653fd26c242106436f5bab0f4c7a9e654ce02665d5a281f2c412456f2d1fa26586ef04a9adac9004ca7f913162cb28e13bf40d", 16)); // // ca keys // RsaPublicKeyStructure caPubKeySpec = new RsaPublicKeyStructure( new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters caPrivKeySpec = new RsaPrivateCrtKeyParameters( new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), new BigInteger("11", 16), new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16), new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16), new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16), new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16), new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16), new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16)); // // set up the keys // AsymmetricKeyParameter caPrivKey = caPrivKeySpec; RsaKeyParameters caPubKey = new RsaKeyParameters(false, caPubKeySpec.Modulus, caPubKeySpec.PublicExponent); AsymmetricKeyParameter intPrivKey = intPrivKeySpec; RsaKeyParameters intPubKey = new RsaKeyParameters(false, intPubKeySpec.Modulus, intPubKeySpec.PublicExponent); AsymmetricKeyParameter privKey = privKeySpec; RsaKeyParameters pubKey = new RsaKeyParameters(false, pubKeySpec.Modulus, intPubKeySpec.PublicExponent); X509Certificate trustCert = CreateTrustCert(caPubKey, caPrivKeySpec); Asn1EncodableVector intPolicies = null; Hashtable map = null; Asn1EncodableVector policies = null; ISet requirePolicies = null; X509Certificate intCert = null; X509Certificate endCert = null; // valid test_00 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = null; string msg = TestPolicies(0, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(0, msg, ""); // test_01 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.1"); msg = TestPolicies(1, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(1, msg, ""); // test_02 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.5.29.32.0"); msg = TestPolicies(2, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(2, msg, ""); // test_03 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.3"))); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.1"); msg = TestPolicies(3, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(3, msg, ""); // test_04 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.3"))); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.3"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.3"); msg = TestPolicies(4, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(4, msg, ""); // test_05 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.2"); msg = TestPolicies(5, trustCert, intCert, endCert, requirePolicies, false); CheckMessage(5, msg, "Path processing failed on policy."); // test_06 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.1"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.1"); msg = TestPolicies(6, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(6, msg, ""); // test_07 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.3"); msg = TestPolicies(7, trustCert, intCert, endCert, requirePolicies, false); CheckMessage(7, msg, "Path processing failed on policy."); // test_08 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.3"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.1"); msg = TestPolicies(8, trustCert, intCert, endCert, requirePolicies, false); CheckMessage(8, msg, "Path processing failed on policy."); }
public void TestRsa() { BigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ==")); BigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ==")); BigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ==")); BigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E=")); BigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE=")); BigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0=")); BigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg==")); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); SubjectPublicKeyInfo subInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rsaPublic); RsaKeyParameters testResult = (RsaKeyParameters)PublicKeyFactory.CreateKey(subInfo); // check RSA public key. Assert.IsFalse(!testResult.Equals(rsaPublic), "RSA: test failed on public key to info and back to public key."); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(rsaPrivate); testResult = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privInfo); Assert.IsFalse(!testResult.Equals(rsaPrivate), "RSA: private key to info back to private key."); Assert.IsTrue(true, "RSATest worked."); }
public void TestCreationRSA() { IBigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); IBigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ==")); IBigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); IBigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ==")); IBigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ==")); IBigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E=")); IBigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE=")); IBigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0=")); IBigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg==")); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); IDictionary attrs = new Hashtable(); attrs[X509Name.C] = "AU"; attrs[X509Name.O] = "The Legion of the Bouncy Castle"; attrs[X509Name.L] = "Melbourne"; attrs[X509Name.ST] = "Victoria"; attrs[X509Name.E] = "*****@*****.**"; IList ord = new ArrayList(); ord.Add(X509Name.C); ord.Add(X509Name.O); ord.Add(X509Name.L); ord.Add(X509Name.ST); ord.Add(X509Name.E); IList values = new ArrayList(); values.Add("AU"); values.Add("The Legion of the Bouncy Castle"); values.Add("Melbourne"); values.Add("Victoria"); values.Add("*****@*****.**"); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1)); certGen.SetNotAfter(DateTime.UtcNow.AddDays(1)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(rsaPublic); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate cert = certGen.Generate(rsaPrivate); // Assert.IsTrue((cert.IsValidNow && cert.Verify(rsaPublic)),"Certificate failed to be valid (RSA)"); cert.CheckValidity(); cert.Verify(rsaPublic); //Console.WriteLine(ASN1Dump.DumpAsString(cert.ToAsn1Object())); ISet dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { foreach (string key in dummySet) { Console.WriteLine("\t{0}:\t{1}", key); } } Console.WriteLine(); dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { foreach (string key in dummySet) { Console.WriteLine("\t{0}:\t{1}", key); } } Console.WriteLine(); }
internal static string RsaPrivateKeyToString(RsaPrivateCrtKeyParameters privateKey) { return privateKey.Modulus + "|" + privateKey.PublicExponent + "|" + privateKey.Exponent + "|" + privateKey.P + "|" + privateKey.Q + "|" + privateKey.DP + "|" + privateKey.DQ + "|" + privateKey.QInv; }
/// <summary> /// Taken directly from Bouncy Castle's ToRSA function in DotNetUtilities I had to modify it based on /// http://stackoverflow.com/questions/16419911/cannot-export-generated-certificate-with-private-key-to-byte-array-in-net-4-0-4 /// and more cleanly http://msdn.microsoft.com/en-us/library/system.security.cryptography.cspparameters.keycontainername%28v=vs.110%29.aspx /// which both say that if you don't put in some kind of key store then the private key will be marked as ephemeral and so won't /// be persisted on an export. /// </summary> /// <param name="privKey"></param> /// <param name="keyContainerName"></param> /// <returns></returns> public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey, string keyContainerName) { Debug.Assert(privKey != null && string.IsNullOrWhiteSpace(keyContainerName) == false); RSAParameters parameters = DotNetUtilities.ToRSAParameters(privKey); var cspParameters = new CspParameters { KeyContainerName = keyContainerName }; RSACryptoServiceProvider cryptoServiceProvider = new RSACryptoServiceProvider(cspParameters); cryptoServiceProvider.ImportParameters(parameters); return cryptoServiceProvider; }
public override void PerformTest() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef); byte[] data = Hex.Decode(edgeInput); // // RAW // IAsymmetricBlockCipher eng = new RsaBlindedEngine(); eng.Init(true, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("RSA: failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!edgeInput.Equals(Hex.ToHexString(data))) { Fail("failed RAW edge Test"); } data = Hex.Decode(input); eng.Init(true, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed RAW Test"); } // // PKCS1 - public encrypt, private decrypt // eng = new Pkcs1Encoding(eng); eng.Init(true, pubParameters); if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize()) { Fail("PKCS1 output block size incorrect"); } try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed PKCS1 public/private Test"); } // // PKCS1 - private encrypt, public decrypt // eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher()); eng.Init(true, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed PKCS1 private/public Test"); } // // key generation test // RsaKeyPairGenerator pGen = new RsaKeyPairGenerator(); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25); pGen.Init(genParam); AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair(); eng = new RsaBlindedEngine(); if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768) { Fail("failed key generation (768) length test"); } eng.Init(true, pair.Public); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pair.Private); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed key generation (768) Test"); } genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25); pGen.Init(genParam); pair = pGen.GenerateKeyPair(); eng.Init(true, pair.Public); if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024) { Fail("failed key generation (1024) length test"); } try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pair.Private); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed key generation (1024) test"); } doTestOaep(pubParameters, privParameters); doTestStrictPkcs1Length(pubParameters, privParameters); doTestDudPkcs1Block(pubParameters, privParameters); doTestMissingDataPkcs1Block(pubParameters, privParameters); doTestTruncatedPkcs1Block(pubParameters, privParameters); doTestWrongPaddingPkcs1Block(pubParameters, privParameters); try { new RsaBlindedEngine().ProcessBlock(new byte[]{ 1 }, 0, 1); Fail("failed initialisation check"); } catch (InvalidOperationException) { // expected } }
private void BaseOaepTest( int id, byte[] pubKeyEnc, byte[] privKeyEnc, byte[] output) { // // extract the public key info. // Asn1Object pubKeyObj = Asn1Object.FromByteArray(pubKeyEnc); RsaPublicKeyStructure pubStruct = RsaPublicKeyStructure.GetInstance( SubjectPublicKeyInfo.GetInstance(pubKeyObj).GetPublicKey()); // // extract the private key info. // Asn1Object privKeyObj = Asn1Object.FromByteArray(privKeyEnc); RsaPrivateKeyStructure privStruct = RsaPrivateKeyStructure.GetInstance( PrivateKeyInfo.GetInstance(privKeyObj).ParsePrivateKey()); RsaKeyParameters pubParameters = new RsaKeyParameters( false, pubStruct.Modulus, pubStruct.PublicExponent); RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters( privStruct.Modulus, privStruct.PublicExponent, privStruct.PrivateExponent, privStruct.Prime1, privStruct.Prime2, privStruct.Exponent1, privStruct.Exponent2, privStruct.Coefficient); byte[] input = new byte[] { (byte)0x54, (byte)0x85, (byte)0x9b, (byte)0x34, (byte)0x2c, (byte)0x49, (byte)0xea, (byte)0x2a }; EncDec("id(" + id + ")", pubParameters, privParameters, seed, input, output); }
internal void checkCreation5() { // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // // set up the keys // SecureRandom rand = new SecureRandom(); // AsymmetricKeyParameter privKey; // AsymmetricKeyParameter pubKey; // // KeyFactory fact = KeyFactory.GetInstance("RSA"); // // privKey = fact.generatePrivate(privKeySpec); // pubKey = fact.generatePublic(pubKeySpec); // // distinguished name table. // IList ord = new ArrayList(); ord.Add(X509Name.C); ord.Add(X509Name.O); ord.Add(X509Name.L); ord.Add(X509Name.ST); ord.Add(X509Name.E); IList values = new ArrayList(); values.Add("AU"); values.Add("The Legion of the Bouncy Castle"); values.Add("Melbourne"); values.Add("Victoria"); values.Add("*****@*****.**"); // // create base certificate - version 3 // X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, values)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name(ord, values)); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); certGen.AddExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.EncipherOnly)); certGen.AddExtension("2.5.29.37", true, new DerSequence(KeyPurposeID.AnyExtendedKeyUsage)); certGen.AddExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.Rfc822Name, "*****@*****.**"))); X509Certificate baseCert = certGen.Generate(privKey); // // copy certificate // certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, values)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name(ord, values)); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); certGen.CopyAndAddExtension(new DerObjectIdentifier("2.5.29.15"), true, baseCert); certGen.CopyAndAddExtension("2.5.29.37", false, baseCert); X509Certificate cert = certGen.Generate(privKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(pubKey); DerObjectIdentifier oid1 = new DerObjectIdentifier("2.5.29.15"); if (!baseCert.GetExtensionValue(oid1).Equals(cert.GetExtensionValue(oid1))) { Fail("2.5.29.15 differs"); } DerObjectIdentifier oid2 = new DerObjectIdentifier("2.5.29.37"); if (!baseCert.GetExtensionValue(oid2).Equals(cert.GetExtensionValue(oid2))) { Fail("2.5.29.37 differs"); } // // exception test // try { certGen.CopyAndAddExtension("2.5.99.99", true, baseCert); Fail("exception not thrown on dud extension copy"); } catch (CertificateParsingException) { // expected } try { certGen.SetPublicKey(dudPublicKey); certGen.Generate(privKey); Fail("key without encoding not detected in v3"); } catch (ArgumentException) { // expected } }
public override void PerformTest() { BaseOaepTest(1, pubKeyEnc1, privKeyEnc1, output1); BaseOaepTest(2, pubKeyEnc2, privKeyEnc2, output2); BaseOaepTest(3, pubKeyEnc3, privKeyEnc3, output3); RsaKeyParameters pubParam = new RsaKeyParameters( false, new BigInteger(1, modulus_1024), new BigInteger(1, pubExp_1024)); RsaKeyParameters privParam = new RsaPrivateCrtKeyParameters( pubParam.Modulus, pubParam.Exponent, new BigInteger(1, privExp_1024), new BigInteger(1, prime1_1024), new BigInteger(1, prime2_1024), new BigInteger(1, primeExp1_1024), new BigInteger(1, primeExp2_1024), new BigInteger(1, crtCoef_1024)); OaepVecTest(1024, 1, pubParam, privParam, seed_1024_1, input_1024_1, output_1024_1); OaepVecTest(1024, 2, pubParam, privParam, seed_1024_2, input_1024_2, output_1024_2); OaepVecTest(1024, 3, pubParam, privParam, seed_1024_3, input_1024_3, output_1024_3); OaepVecTest(1024, 4, pubParam, privParam, seed_1024_4, input_1024_4, output_1024_4); OaepVecTest(1024, 5, pubParam, privParam, seed_1024_5, input_1024_5, output_1024_5); OaepVecTest(1024, 6, pubParam, privParam, seed_1024_6, input_1024_6, output_1024_6); pubParam = new RsaKeyParameters( false, new BigInteger(1, modulus_1027), new BigInteger(1, pubExp_1027)); privParam = new RsaPrivateCrtKeyParameters( pubParam.Modulus, pubParam.Exponent, new BigInteger(1, privExp_1027), new BigInteger(1, prime1_1027), new BigInteger(1, prime2_1027), new BigInteger(1, primeExp1_1027), new BigInteger(1, primeExp2_1027), new BigInteger(1, crtCoef_1027)); OaepVecTest(1027, 1, pubParam, privParam, seed_1027_1, input_1027_1, output_1027_1); OaepVecTest(1027, 2, pubParam, privParam, seed_1027_2, input_1027_2, output_1027_2); OaepVecTest(1027, 3, pubParam, privParam, seed_1027_3, input_1027_3, output_1027_3); OaepVecTest(1027, 4, pubParam, privParam, seed_1027_4, input_1027_4, output_1027_4); OaepVecTest(1027, 5, pubParam, privParam, seed_1027_5, input_1027_5, output_1027_5); OaepVecTest(1027, 6, pubParam, privParam, seed_1027_6, input_1027_6, output_1027_6); }
public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey) { return CreateRSAProvider(ToRSAParameters(privKey)); }
/* * converts a bouncy castle private key to a windows private key */ private static sys2.AsymmetricAlgorithm ConvertToSystemKey(RsaPrivateCrtKeyParameters privateKey) { sys2.CspParameters cspPars = new sys2.CspParameters { KeyContainerName = Guid.NewGuid().ToString(), KeyNumber = (int)sys2.KeyNumber.Exchange }; sys2.RSACryptoServiceProvider rsaCryptoProvider = new sys2.RSACryptoServiceProvider(cspPars); sys2.RSAParameters rsaParameters = new sys2.RSAParameters { Modulus = privateKey.Modulus.ToByteArrayUnsigned(), P = privateKey.P.ToByteArrayUnsigned(), Q = privateKey.Q.ToByteArrayUnsigned(), DP = privateKey.DP.ToByteArrayUnsigned(), DQ = privateKey.DQ.ToByteArrayUnsigned(), InverseQ = privateKey.QInv.ToByteArrayUnsigned(), D = privateKey.Exponent.ToByteArrayUnsigned(), Exponent = privateKey.PublicExponent.ToByteArrayUnsigned() }; rsaCryptoProvider.ImportParameters(rsaParameters); return rsaCryptoProvider; }
public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey) { RSAParameters rp = new RSAParameters(); rp.Modulus = privKey.Modulus.ToByteArrayUnsigned(); rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned(); rp.D = privKey.Exponent.ToByteArrayUnsigned(); rp.P = privKey.P.ToByteArrayUnsigned(); rp.Q = privKey.Q.ToByteArrayUnsigned(); rp.DP = privKey.DP.ToByteArrayUnsigned(); rp.DQ = privKey.DQ.ToByteArrayUnsigned(); rp.InverseQ = privKey.QInv.ToByteArrayUnsigned(); return rp; }
public void doTestPkcs12Store() { BigInteger mod = new BigInteger("bb1be8074e4787a8d77967f1575ef72dd7582f9b3347724413c021beafad8f32dba5168e280cbf284df722283dad2fd4abc750e3d6487c2942064e2d8d80641aa5866d1f6f1f83eec26b9b46fecb3b1c9856a303148a5cc899c642fb16f3d9d72f52526c751dc81622c420c82e2cfda70fe8d13f16cc7d6a613a5b2a2b5894d1", 16); MemoryStream stream = new MemoryStream(pkcs12, false); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.Load(stream, passwd); string pName = null; foreach (string n in store.Aliases) { if (store.IsKeyEntry(n)) { pName = n; //break; } } AsymmetricKeyEntry key = store.GetKey(pName); if (!((RsaKeyParameters) key.Key).Modulus.Equals(mod)) { Fail("Modulus doesn't match."); } X509CertificateEntry[] ch = store.GetCertificateChain(pName); if (ch.Length != 3) { Fail("chain was wrong length"); } if (!ch[0].Certificate.SerialNumber.Equals(new BigInteger("96153094170511488342715101755496684211"))) { Fail("chain[0] wrong certificate."); } if (!ch[1].Certificate.SerialNumber.Equals(new BigInteger("279751514312356623147411505294772931957"))) { Fail("chain[1] wrong certificate."); } if (!ch[2].Certificate.SerialNumber.Equals(new BigInteger("11341398017"))) { Fail("chain[2] wrong certificate."); } // // save test // MemoryStream bOut = new MemoryStream(); store.Save(bOut, passwd, new SecureRandom()); stream = new MemoryStream(bOut.ToArray(), false); store.Load(stream, passwd); key = store.GetKey(pName); if (!((RsaKeyParameters)key.Key).Modulus.Equals(mod)) { Fail("Modulus doesn't match."); } store.DeleteEntry(pName); if (store.GetKey(pName) != null) { Fail("Failed deletion test."); } // // cert chain test // store.SetCertificateEntry("testCert", ch[2]); if (store.GetCertificateChain("testCert") != null) { Fail("Failed null chain test."); } // // UTF 8 single cert test // stream = new MemoryStream(certUTF, false); store.Load(stream, "user".ToCharArray()); if (store.GetCertificate("37") == null) { Fail("Failed to find UTF cert."); } // // try for a self generated certificate // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); X509CertificateEntry[] chain = new X509CertificateEntry[] { CreateCert(pubKey, privKey, "*****@*****.**", "*****@*****.**") }; store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry("privateKey", new AsymmetricKeyEntry(privKey), chain); if (!store.ContainsAlias("privateKey") || !store.ContainsAlias("PRIVATEKEY")) { Fail("couldn't find alias privateKey"); } if (store.IsCertificateEntry("privateKey")) { Fail("key identified as certificate entry"); } if (!store.IsKeyEntry("privateKey") || !store.IsKeyEntry("PRIVATEKEY")) { Fail("key not identified as key entry"); } if (!"privateKey".Equals(store.GetCertificateAlias(chain[0].Certificate))) { Fail("Did not return alias for key certificate privateKey"); } MemoryStream store1Stream = new MemoryStream(); store.Save(store1Stream, passwd, new SecureRandom()); testNoExtraLocalKeyID(store1Stream.ToArray()); // // no friendly name test // stream = new MemoryStream(pkcs12noFriendly, false); store.Load(stream, noFriendlyPassword); pName = null; foreach (string n in store.Aliases) { if (store.IsKeyEntry(n)) { pName = n; //break; } } ch = store.GetCertificateChain(pName); //for (int i = 0; i != ch.Length; i++) //{ // Console.WriteLine(ch[i]); //} if (ch.Length != 1) { Fail("no cert found in pkcs12noFriendly"); } // // failure tests // ch = store.GetCertificateChain("dummy"); store.GetCertificateChain("DUMMY"); store.GetCertificate("dummy"); store.GetCertificate("DUMMY"); // // storage test // stream = new MemoryStream(pkcs12StorageIssue, false); store.Load(stream, storagePassword); pName = null; foreach (string n in store.Aliases) { if (store.IsKeyEntry(n)) { pName = n; //break; } } ch = store.GetCertificateChain(pName); if (ch.Length != 2) { Fail("Certificate chain wrong length"); } store.Save(new MemoryStream(), storagePassword, new SecureRandom()); // // basic certificate check // store.SetCertificateEntry("cert", ch[1]); if (!store.ContainsAlias("cert") || !store.ContainsAlias("CERT")) { Fail("couldn't find alias cert"); } if (!store.IsCertificateEntry("cert") || !store.IsCertificateEntry("CERT")) { Fail("cert not identified as certificate entry"); } if (store.IsKeyEntry("cert") || store.IsKeyEntry("CERT")) { Fail("cert identified as key entry"); } if (!store.IsEntryOfType("cert", typeof(X509CertificateEntry))) { Fail("cert not identified as X509CertificateEntry"); } if (!store.IsEntryOfType("CERT", typeof(X509CertificateEntry))) { Fail("CERT not identified as X509CertificateEntry"); } if (store.IsEntryOfType("cert", typeof(AsymmetricKeyEntry))) { Fail("cert identified as key entry via AsymmetricKeyEntry"); } if (!"cert".Equals(store.GetCertificateAlias(ch[1].Certificate))) { Fail("Did not return alias for certificate entry"); } // // test restoring of a certificate with private key originally as a ca certificate // store = new Pkcs12StoreBuilder().Build(); store.SetCertificateEntry("cert", ch[0]); if (!store.ContainsAlias("cert") || !store.ContainsAlias("CERT")) { Fail("restore: couldn't find alias cert"); } if (!store.IsCertificateEntry("cert") || !store.IsCertificateEntry("CERT")) { Fail("restore: cert not identified as certificate entry"); } if (store.IsKeyEntry("cert") || store.IsKeyEntry("CERT")) { Fail("restore: cert identified as key entry"); } if (store.IsEntryOfType("cert", typeof(AsymmetricKeyEntry))) { Fail("restore: cert identified as key entry via AsymmetricKeyEntry"); } if (store.IsEntryOfType("CERT", typeof(AsymmetricKeyEntry))) { Fail("restore: cert identified as key entry via AsymmetricKeyEntry"); } if (!store.IsEntryOfType("cert", typeof(X509CertificateEntry))) { Fail("restore: cert not identified as X509CertificateEntry"); } // // test of reading incorrect zero-length encoding // stream = new MemoryStream(pkcs12nopass, false); store.Load(stream, "".ToCharArray()); }
internal PgpPrivateKey DoExtractPrivateKey(byte[] rawPassPhrase, bool clearPassPhrase) { if (IsPrivateKeyEmpty) return null; PublicKeyPacket pubPk = secret.PublicKeyPacket; try { byte[] data = ExtractKeyData(rawPassPhrase, clearPassPhrase); BcpgInputStream bcpgIn = BcpgInputStream.Wrap(new MemoryStream(data, false)); AsymmetricKeyParameter privateKey; switch (pubPk.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaSign: RsaPublicBcpgKey rsaPub = (RsaPublicBcpgKey)pubPk.Key; RsaSecretBcpgKey rsaPriv = new RsaSecretBcpgKey(bcpgIn); RsaPrivateCrtKeyParameters rsaPrivSpec = new RsaPrivateCrtKeyParameters( rsaPriv.Modulus, rsaPub.PublicExponent, rsaPriv.PrivateExponent, rsaPriv.PrimeP, rsaPriv.PrimeQ, rsaPriv.PrimeExponentP, rsaPriv.PrimeExponentQ, rsaPriv.CrtCoefficient); privateKey = rsaPrivSpec; break; case PublicKeyAlgorithmTag.Dsa: DsaPublicBcpgKey dsaPub = (DsaPublicBcpgKey)pubPk.Key; DsaSecretBcpgKey dsaPriv = new DsaSecretBcpgKey(bcpgIn); DsaParameters dsaParams = new DsaParameters(dsaPub.P, dsaPub.Q, dsaPub.G); privateKey = new DsaPrivateKeyParameters(dsaPriv.X, dsaParams); break; case PublicKeyAlgorithmTag.ECDH: privateKey = GetECKey("ECDH", bcpgIn); break; case PublicKeyAlgorithmTag.ECDsa: privateKey = GetECKey("ECDSA", bcpgIn); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: ElGamalPublicBcpgKey elPub = (ElGamalPublicBcpgKey)pubPk.Key; ElGamalSecretBcpgKey elPriv = new ElGamalSecretBcpgKey(bcpgIn); ElGamalParameters elParams = new ElGamalParameters(elPub.P, elPub.G); privateKey = new ElGamalPrivateKeyParameters(elPriv.X, elParams); break; default: throw new PgpException("unknown public key algorithm encountered"); } return new PgpPrivateKey(KeyId, pubPk, privateKey); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception constructing key", e); } }
/** * we Generate a self signed certificate for the sake of testing - RSA */ internal void checkCreation1() { // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // // set up the keys // // AsymmetricKeyParameter privKey; // AsymmetricKeyParameter pubKey; // KeyFactory fact = KeyFactory.GetInstance("RSA"); // // privKey = fact.generatePrivate(privKeySpec); // pubKey = fact.generatePublic(pubKeySpec); // // distinguished name table. // IList ord = new ArrayList(); ord.Add(X509Name.C); ord.Add(X509Name.O); ord.Add(X509Name.L); ord.Add(X509Name.ST); ord.Add(X509Name.E); IList values = new ArrayList(); values.Add("AU"); values.Add("The Legion of the Bouncy Castle"); values.Add("Melbourne"); values.Add("Victoria"); values.Add("*****@*****.**"); // // extensions // // // create the certificate - version 3 - without extensions // X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, values)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name(ord, values)); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); X509Certificate cert = certGen.Generate(privKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(pubKey); ISet dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { Fail("non-critical oid set should be null"); } dummySet = cert.GetCriticalExtensionOids(); if (dummySet != null) { Fail("critical oid set should be null"); } // // create the certificate - version 3 - with extensions // certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, values)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name(ord, values)); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); certGen.AddExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.EncipherOnly)); certGen.AddExtension("2.5.29.37", true, new DerSequence(KeyPurposeID.AnyExtendedKeyUsage)); certGen.AddExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.Rfc822Name, "*****@*****.**"))); cert = certGen.Generate(privKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(pubKey); cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded()); if (!cert.GetKeyUsage()[7]) { Fail("error generating cert - key usage wrong."); } IList l = cert.GetExtendedKeyUsage(); if (!l[0].Equals(KeyPurposeID.AnyExtendedKeyUsage.Id)) { Fail("failed extended key usage test"); } foreach (IList gn in cert.GetSubjectAlternativeNames()) { if (!gn[1].Equals("*****@*****.**")) { Fail("failed subject alternative names test"); } } // Console.WriteLine(cert); // // create the certificate - version 1 // X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator(); certGen1.SetSerialNumber(BigInteger.One); certGen1.SetIssuerDN(new X509Name(ord, values)); certGen1.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen1.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen1.SetSubjectDN(new X509Name(ord, values)); certGen1.SetPublicKey(pubKey); certGen1.SetSignatureAlgorithm("MD5WithRSAEncryption"); cert = certGen1.Generate(privKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(pubKey); cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded()); // Console.WriteLine(cert); if (!cert.IssuerDN.Equivalent(cert.SubjectDN)) { Fail("name comparison fails"); } }
public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey) { RSAParameters rp = ToRSAParameters(privKey); RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(); rsaCsp.ImportParameters(rp); return rsaCsp; }
private static AsymmetricCipherKeyPair GenerateLongFixedKeys() { // RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( RsaKeyParameters pubKey = new RsaKeyParameters(false, new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); // RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16), new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16), new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16), new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16), new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16), new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16), new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16)); // KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); // // PrivateKey privKey = fact.generatePrivate(privKeySpec); // PublicKey pubKey = fact.generatePublic(pubKeySpec); return new AsymmetricCipherKeyPair(pubKey, privKey); }
protected void Page_Load(object sender, EventArgs e) { //AuthCode(); //ModeWappay(); //return; _log.Info("测试"); //X509Certificate2 pc = new X509Certificate2(@"D:/182000899000001_01.pfx", "123456", X509KeyStorageFlags.MachineKeySet); ////return BigNum.ToDecimalStr(BigNum.ConvertFromHex(pc.SerialNumber)); 低于4.0版本的.NET请使用此方法 ////return BigInteger.Parse(pc.SerialNumber, System.Globalization.NumberStyles.HexNumber).ToString(); //Org.BouncyCastle.Math.BigInteger mod = new Org.BouncyCastle.Math.BigInteger(pc.GetSerialNumberString(), 16); //string m = "123333333333333333333333333333333333333333333333333333333333333333333333333333333333333333344444444444444444444444444FFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGG"; //string sign = Cmn.GetSign(m); //bool f = Cmn.ValitedSign(sign, m); //int a = 0; //Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)privateKey //RSA密钥对的构造器 RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); //RSA密钥构造器的参数 RsaKeyGenerationParameters param = new RsaKeyGenerationParameters( Org.BouncyCastle.Math.BigInteger.ValueOf(3), new Org.BouncyCastle.Security.SecureRandom(), 1024, //密钥长度 25); //用参数初始化密钥构造器 keyGenerator.Init(param); //产生密钥对 string input = "popozh RSA test"; AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); //获取公钥和密钥 AsymmetricKeyParameter publicKey = keyPair.Public; AsymmetricKeyParameter privateKey = keyPair.Private; if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024) { Console.WriteLine("failed key generation (1024) length test"); } Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters pu = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)publicKey; Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters pr = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)privateKey; //加密 string mSign = GetSign(input, pr); //解密 bool isPass = ValitedSign(mSign, input, pu); return; //一个测试…………………… //输入,十六进制的字符串,解码为byte[] //string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; //byte[] testData = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(input); byte[] testData = Encoding.UTF8.GetBytes(input); Console.WriteLine("明文:" + input + Environment.NewLine); //非对称加密算法,加解密用 IAsymmetricBlockCipher engine = new RsaEngine(); //公钥加密 engine.Init(true, publicKey); try { testData = engine.ProcessBlock(testData, 0, testData.Length); Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine); } catch (Exception ex) { Console.WriteLine("failed - exception " + Environment.NewLine + ex.ToString()); } //string K = Convert.ToBase64String(testData);//System.Text.Encoding.Default.GetString(testData); //string sign = Cmn.GetSign(K); //int m = 1; //私钥解密 engine.Init(false, privateKey); try { testData = engine.ProcessBlock(testData, 0, testData.Length); } catch (Exception ef) { Console.WriteLine("failed - exception " + ef.ToString()); } if (input.Equals(Encoding.UTF8.GetString(testData))) { Console.WriteLine("解密成功"); } Console.Read(); }