public HttpResponseMessage Get(string smsNumber, string code) { RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 2048)); AsymmetricCipherKeyPair keys = r.GenerateKeyPair(); string publicKeyPath = Path.Combine(Path.GetTempPath(), "publicKey.key"); if (File.Exists(publicKeyPath)) { File.Delete(publicKeyPath); } using (TextWriter textWriter = new StreamWriter(publicKeyPath, false)) { PemWriter pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(keys.Public); pemWriter.Writer.Flush(); } string certSubjectName = "UShadow_RSA"; var certName = new X509Name("CN=" + certSubjectName); var serialNo = BigInteger.ProbablePrime(120, new Random()); X509V3CertificateGenerator gen2 = new X509V3CertificateGenerator(); gen2.SetSerialNumber(serialNo); gen2.SetSubjectDN(certName); gen2.SetIssuerDN(new X509Name(true, "CN=UShadow")); gen2.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(30, 0, 0, 0))); gen2.SetNotAfter(DateTime.Now.AddYears(2)); gen2.SetSignatureAlgorithm("sha512WithRSA"); gen2.SetPublicKey(keys.Public); Org.BouncyCastle.X509.X509Certificate newCert = gen2.Generate(keys.Private); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); X509CertificateEntry certEntry = new X509CertificateEntry(newCert); store.SetCertificateEntry(newCert.SubjectDN.ToString(), certEntry); AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private); store.SetKeyEntry(newCert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); using (MemoryStream ms = new MemoryStream()) { store.Save(ms, "Password".ToCharArray(), new SecureRandom()); var resp = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(ms.ToArray()) }; resp.Content.Headers.Add("Content-Type", "application/x-pkcs12"); return resp; } }
private void doTestParams( byte[] ecParameterEncoded, bool compress) { // string keyStorePass = "******"; Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(ecParameterEncoded); X9ECParameters x9 = new X9ECParameters(seq); AsymmetricCipherKeyPair kp = null; bool success = false; while (!success) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); // kpg.Init(new ECParameterSpec(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed())); ECDomainParameters ecParams = new ECDomainParameters( x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); kpg.Init(new ECKeyGenerationParameters(ecParams, new SecureRandom())); kp = kpg.GenerateKeyPair(); // The very old Problem... we need a certificate chain to // save a private key... ECPublicKeyParameters pubKey = (ECPublicKeyParameters) kp.Public; if (!compress) { //pubKey.setPointFormat("UNCOMPRESSED"); pubKey = SetPublicUncompressed(pubKey); } byte[] x = pubKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned(); byte[] y = pubKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned(); if (x.Length == y.Length) { success = true; } } // The very old Problem... we need a certificate chain to // save a private key... X509CertificateEntry[] chain = new X509CertificateEntry[] { new X509CertificateEntry(GenerateSelfSignedSoftECCert(kp, compress)) }; // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(null, keyStorePass.ToCharArray()); Pkcs12Store keyStore = new Pkcs12StoreBuilder().Build(); keyStore.SetCertificateEntry("ECCert", chain[0]); ECPrivateKeyParameters privateECKey = (ECPrivateKeyParameters) kp.Private; keyStore.SetKeyEntry("ECPrivKey", new AsymmetricKeyEntry(privateECKey), chain); // Test ec sign / verify ECPublicKeyParameters pub = (ECPublicKeyParameters) kp.Public; // string oldPrivateKey = new string(Hex.encode(privateECKey.getEncoded())); byte[] oldPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateECKey).GetDerEncoded(); string oldPrivateKey = Hex.ToHexString(oldPrivateKeyBytes); // string oldPublicKey = new string(Hex.encode(pub.getEncoded())); byte[] oldPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub).GetDerEncoded(); string oldPublicKey = Hex.ToHexString(oldPublicKeyBytes); ECPrivateKeyParameters newKey = (ECPrivateKeyParameters) keyStore.GetKey("ECPrivKey").Key; ECPublicKeyParameters newPubKey = (ECPublicKeyParameters) keyStore.GetCertificate("ECCert").Certificate.GetPublicKey(); if (!compress) { // TODO Private key compression? //newKey.setPointFormat("UNCOMPRESSED"); //newPubKey.setPointFormat("UNCOMPRESSED"); newPubKey = SetPublicUncompressed(newPubKey); } // string newPrivateKey = new string(Hex.encode(newKey.getEncoded())); byte[] newPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(newKey).GetDerEncoded(); string newPrivateKey = Hex.ToHexString(newPrivateKeyBytes); // string newPublicKey = new string(Hex.encode(newPubKey.getEncoded())); byte[] newPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(newPubKey).GetDerEncoded(); string newPublicKey = Hex.ToHexString(newPublicKeyBytes); if (!oldPrivateKey.Equals(newPrivateKey)) // if (!privateECKey.Equals(newKey)) { Fail("failed private key comparison"); } if (!oldPublicKey.Equals(newPublicKey)) // if (!pub.Equals(newPubKey)) { Fail("failed public key comparison"); } }
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()); }
private static byte[] GeneratePkcs12(AsymmetricCipherKeyPair keys, Org.BouncyCastle.X509.X509Certificate cert, string friendlyName, string password, Dictionary<string, Org.BouncyCastle.X509.X509Certificate> chain) { var chainCerts = new List<X509CertificateEntry>(); // Create the PKCS12 store Pkcs12Store store = new Pkcs12StoreBuilder().Build(); // Add a Certificate entry X509CertificateEntry certEntry = new X509CertificateEntry(cert); store.SetCertificateEntry(friendlyName, certEntry); // use DN as the Alias. //chainCerts.Add(certEntry); // Add chain entries var additionalCertsAsBytes = new List<byte[]>(); if (chain != null && chain.Count > 0) { foreach (var additionalCert in chain) { additionalCertsAsBytes.Add(additionalCert.Value.GetEncoded()); } } if (chain != null && chain.Count > 0) { var addicionalCertsAsX09Chain = BuildCertificateChainBC(cert.GetEncoded(), additionalCertsAsBytes); foreach (var addCertAsX09 in addicionalCertsAsX09Chain) { chainCerts.Add(new X509CertificateEntry(addCertAsX09)); } } // Add a key entry AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private); // no chain store.SetKeyEntry(friendlyName, keyEntry, new X509CertificateEntry[] { certEntry }); using (var memoryStream = new MemoryStream()) { store.Save(memoryStream, password.ToCharArray(), new SecureRandom()); return memoryStream.ToArray(); } }