public static string ExportPublicKeyToPEMFormat(RSAParameters parms) { RsaKeyParameters publicParams = DotNetUtilities.GetRsaPublicKey(parms); SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicParams); return(Convert.ToBase64String(keyInfo.GetEncoded())); }
public void TestBasicMessageWithArchiveControlJVMGenerated() { AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey( Hex.Decode("305c300d06092a864886f70d0101010500034b003048024100a9a94b7b98dc3daf8cac032a14bd4510832b0e007edbdafc065e328645a35828b8185cdbf73ed495c88436b11a9322965595d2e4c1dd63c3c4d41812f876b3070203010001")); AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey( Hex.Decode("30820154020100300d06092a864886f70d01010105000482013e3082013a020100024100a9a94b7b98dc3daf8cac032a14bd4510832b0e007edbdafc065e328645a35828b8185cdbf73ed495c88436b11a9322965595d2e4c1dd63c3c4d41812f876b307020301000102400831deacfe21a9331902d7f648e1297c563196b00c70971fb439098cb5c1618925bdbac4c66b30f8956660220f326f51e5a1725ce690165154fb62fa14497265022100e54943be1b4951e127f6e79c5ab333cba4b0fff0b5e59328d6393ba98dc0e6c3022100bd6da58ce195146a1d3825ec2a622cf4962da653096bea87fbd9a94db266a66d0221008948bcceeef78f97089ec53ed0efcb6b7b489f7638f32491a6f2cdce4f99d89102204eb1b066d8883054ed12985e863506ec0d3fa5ab356cc99ff876b228ff0639f9022024049aaf39bf9a0ddfbd4caee277d0a9f07d075faae12571176a5c0ca40415c0")); CertificateRequestMessage msg = new CertificateRequestMessage( Hex.Decode("308202af308202ab0201013071a511300f310d300b0603550403130454657374a65c300d06092a864886f70d0101010500034b003048024100a9a94b7b98dc3daf8cac032a14bd4510832b0e007edbdafc065e328645a35828b8185cdbf73ed495c88436b11a9322965595d2e4c1dd63c3c4d41812f876b3070203010001308202313082022d06092b0601050507050104a082021ea082021a0201003171306f0201003019300f310d300b06035504030c04546573740206016859de5806300d06092a864886f70d0101010500044066f1a72f808908af784b83c07895276104d7c4caaee6090212ce5b27517aec510425b784352b5342c999f844b8796286f10a59807e290f06aa39f8cba86dd6bf308201a0060b2a864886f70d0109100115301d060960864801650304010204104aceaa277cc7974ea2a775ff9db6062580820170c648e70c25c4789d2ff4ed398e5536efb45d2dd8ba76a628ad30bf9596a18337afc0f596f0c18e05fb3fa9944ed9691dae1d9b327b5bbafaaa63efb0e22d675811c27bfb023b80184325fd4b67b3b9e41bf43c5583a86433b230e09a34b61397ddff0eadf10c883fc1f01860e2a56ab4002dcc4d4925c53e09dde0b99928fdf602bce544722155cebd8816e91a411a99feea07695774cd8883034022d57f64e9cd3383c3125c48db2936b7395a22b17910be1f2c0b8650bdb5bd752ffc40fcd30169e5ae3a4ac7ad9cc850e9c17bbcf8e1a1898d0d8be19145c484467b8f1124657a5e08c10fc67416274990cc16d55c9fb76c265dd436b7e803425892297f1a08e4fab8e178874b2b3bf9c749693d609db208e9a3ebbddd26cd6a1b33c0201532170dc6c303e7ac0c42ba0bc54dfb928b228842b6bb08d8dc411d262dabf140a8b5a5c67ea486c1877a2fc000981d54cf2decaf1cfeebcf83134992b09a2b1fe9e02da25b874604b5d8bbd609875ba8")); AsymmetricCipherKeyPair rsaKeyPair = new AsymmetricCipherKeyPair(publicKey, privateKey); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); Console.WriteLine(msg.GetCertTemplate().Subject.Equivalent(new X509Name("CN=Test"))); IsTrue(msg.GetCertTemplate().Subject.Equivalent(new X509Name("CN=Test"))); IsTrue(Arrays.AreEqual(msg.GetCertTemplate().PublicKey.GetEncoded(), publicKeyInfo.GetEncoded())); checkCertReqMsgWithArchiveControl(rsaKeyPair, msg); checkCertReqMsgWithArchiveControl(rsaKeyPair, new CertificateRequestMessage(msg.GetEncoded())); checkCertReqMsgWithArchiveControl(rsaKeyPair, msg); }
/// <summary> /// Returns the specified XML RSA key <c>string</c> converted to the PEM format. /// </summary> /// <param name="xml">The XML <c>string</c> containing the RSA key.</param> /// <returns>System.String.</returns> /// <exception cref="InvalidKeyException">Invalid XML RSA Key</exception> public static string XmlToPem(this string xml) { using (var rsa = RSA.Create()) { rsa.FromXmlStringNetCore(xml); // Try to get the private and public key pair first. AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa); if (keyPair != null) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); return(FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "RSA PRIVATE KEY")); } // At this point, the XML RSA key contains only the public key. RsaKeyParameters publicKey = DotNetUtilities.GetRsaPublicKey(rsa); if (publicKey != null) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY")); } } throw new InvalidKeyException("Invalid XML RSA Key"); }
public static string XmlStringToPem(this string xml) { try { using (RSA rsa = RSA.Create()) { rsa.FromXmlString(xml); var keyPair = DotNetUtilities.GetRsaKeyPair(rsa); if (keyPair != null) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); return(FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "RSA PRIVATE KEY")); } var publicKey = DotNetUtilities.GetRsaPublicKey(rsa); if (publicKey != null) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY")); } } } catch (Exception e) { throw new InvalidKeyException("Invalid RSA Xml Key", e); } throw new InvalidKeyException("Keys were not found"); }
public string Encode(bool Private, bool Public) { string derPublicKey; string derPrivateKey; string retval; derPrivateKey = ""; derPublicKey = ""; switch (this.Type) { case "RSA": if (this._containsprivatekey == true && Private == true) { PrivateKeyInfo infoPrivate = PrivateKeyInfoFactory.CreatePrivateKeyInfo(this.PrivateKey); derPrivateKey = Convert.ToBase64String(infoPrivate.GetEncoded()); } if (this._containspublickey = true && Public == true) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(this.PublicKey); derPublicKey = Convert.ToBase64String(publicKeyInfo.GetEncoded()); } retval = this.UUID.ToString() + "!RSA!" + this.Length.ToString() + "!" + derPublicKey + "!" + derPrivateKey; break; default: retval = this.UUID.ToString() + "!NONE!!!"; break; } return(retval); }
/// <summary> /// /// </summary> /// <param name="forPubKey"></param> /// <param name="forPrivKey"></param> /// <param name="keyStrength">1024, 2048,4096</param> /// <param name="exponent">Typically a fermat number 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617,</param> /// <param name="certaninty">Should be 80 or higher depending on Key strength number (exponent)</param> public static void GenerateKeys(out string forPubKey, out string forPrivKey, int keyStrength, int exponent, int certaninty) { // Create key RsaKeyPairGenerator generator = new RsaKeyPairGenerator(); /* * This value should be a Fermat number. 0x10001 (F4) is current recommended value. 3 (F1) is known to be safe also. * 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617, * * Practically speaking, Windows does not tolerate public exponents which do not fit in a 32-bit unsigned integer. Using e=3 or e=65537 works "everywhere". */ BigInteger exponentBigInt = new BigInteger(exponent.ToString()); var param = new RsaKeyGenerationParameters( exponentBigInt, // new BigInteger("10001", 16) publicExponent new SecureRandom(), // SecureRandom.getInstance("SHA1PRNG"),//prng keyStrength, //strength certaninty); //certainty generator.Init(param); AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair(); // Save to export format SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); byte[] ret = info.GetEncoded(); forPubKey = Convert.ToBase64String(ret); // EncryptedPrivateKeyInfo asdf = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( // DerObjectIdentifier.Ber,,,keyPair.Private); //TextWriter textWriter = new StringWriter(); //PemWriter pemWriter = new PemWriter(textWriter); //pemWriter.WriteObject(keyPair); //pemWriter.Writer.Flush(); //string ret2 = textWriter.ToString(); //// demonstration: how to serialise option 1 //TextReader tr = new StringReader(ret2); //PemReader read = new PemReader(tr); //AsymmetricCipherKeyPair something = (AsymmetricCipherKeyPair)read.ReadObject(); //// demonstration: how to serialise option 2 (don't know how to deserailize) //PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); //byte[] privRet = pKinfo.GetEncoded(); //string forPrivKey2Test = Convert.ToBase64String(privRet); PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); byte[] privRet = pKinfo.GetEncoded(); string forPrivKey2Test = Convert.ToBase64String(privRet); forPrivKey = forPrivKey2Test; }
public static string PublicXmlToPem(string xml) { using (RSA rsa = RSA.Create()) { rsa.FromXmlString(xml); RsaKeyParameters publicKey = Org.BouncyCastle.Security.DotNetUtilities.GetRsaPublicKey(rsa); // try get public key if (publicKey != null) // if XML RSA key contains public key { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY")); } } throw new InvalidKeyException("Invalid RSA Xml Key"); }
public static byte[] Init() { AsymmetricCipherKeyPair keyPair = null; string path = "proxy/session-key"; try { AsymmetricKeyParameter keyPub = PublicKeyFactory.CreateKey(File.ReadAllBytes(path + ".pub")); AsymmetricKeyParameter KeyPriv = PrivateKeyFactory.CreateKey(File.ReadAllBytes(path + ".priv")); keyPair = new AsymmetricCipherKeyPair(keyPub, KeyPriv); Debug.WriteLine("Loaded session.key"); } catch (Exception e) { Log.WriteServer(e); Debug.WriteLine("Generating session.key..."); var generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); keyPair = generator.GenerateKeyPair(); Debug.WriteLine("Generated, saving..."); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); byte[] bytePub = publicKeyInfo.ToAsn1Object().GetDerEncoded(); Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllBytes(path + ".pub", bytePub); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); byte[] bytePriv = privateKeyInfo.ToAsn1Object().GetDerEncoded(); File.WriteAllBytes(path + ".priv", bytePriv); Debug.WriteLine("Saved session.key"); } //Old method /*var generator = new RsaKeyPairGenerator(); * generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); * var keyPair = generator.GenerateKeyPair(); */ keyParameters = (RsaKeyParameters)keyPair.Private; SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); return(info.GetEncoded()); }
public void TestBasicMessageWithArchiveControl() { RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator(); rsaKeyPairGenerator.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(65537), new SecureRandom(), 2048, 100)); AsymmetricCipherKeyPair rsaKeyPair = rsaKeyPairGenerator.GenerateKeyPair(); TestCertBuilder tcb = new TestCertBuilder(); tcb.PublicKey = rsaKeyPair.Public; tcb.Subject = new X509Name("CN=Test"); tcb.Issuer = new X509Name("CN=Test"); tcb.NotBefore = DateTime.UtcNow.AddDays(-1); tcb.NotAfter = DateTime.UtcNow.AddDays(1); tcb.SignatureAlgorithm = "Sha1WithRSAEncryption"; X509Certificate cert = tcb.Build(rsaKeyPair.Private); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rsaKeyPair.Public); PrivateKeyInfo privateInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(rsaKeyPair.Private); CertificateRequestMessageBuilder certificateRequestMessageBuilder = new CertificateRequestMessageBuilder(BigInteger.One); certificateRequestMessageBuilder.SetSubject(new X509Name("CN=Test")); certificateRequestMessageBuilder.SetPublicKey(publicKeyInfo); certificateRequestMessageBuilder.AddControl( new PkiArchiveControlBuilder(privateInfo, new GeneralName(new X509Name("CN=Test"))) .AddRecipientGenerator(new CmsKeyTransRecipientInfoGenerator(cert, new Asn1KeyWrapper("RSA/None/OAEPwithSHA256andMGF1Padding", cert))) .Build(new CmsContentEncryptorBuilder(NistObjectIdentifiers.IdAes128Cbc).Build()) ); CertificateRequestMessage msg = certificateRequestMessageBuilder.Build(); IsTrue(Arrays.AreEqual(msg.GetCertTemplate().Subject.GetEncoded(), new X509Name("CN=Test").GetEncoded())); IsTrue(Arrays.AreEqual(msg.GetCertTemplate().PublicKey.GetEncoded(), publicKeyInfo.GetEncoded())); CheckCertReqMsgWithArchiveControl(rsaKeyPair, msg); CheckCertReqMsgWithArchiveControl(rsaKeyPair, new CertificateRequestMessage(msg.GetEncoded())); }
/// <summary> /// Create/Load RSA key pairs /// </summary> public void GenerateKeys() { AsymmetricCipherKeyPair keyPair; if (!FSCheck()) { RsaKeyPairGenerator generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); keyPair = generator.GenerateKeyPair(); SaveToDisk(keyPair); } else { keyPair = LoadFromDisk(); } privateKey = keyPair.Private; RsaKeyParameters keyParam = (RsaKeyParameters)keyPair.Public; SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyParam); derFormat = Convert.ToBase64String(info.GetEncoded()); }
public static string XmlToPem(string xml) { using (RSA rsa = RSA.Create()) { rsa.FromXmlString(xml); AsymmetricCipherKeyPair keyPair = Org.BouncyCastle.Security.DotNetUtilities.GetRsaKeyPair(rsa); // try get private and public key pair if (keyPair != null) // if XML RSA key contains private key { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); return(FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "PRIVATE KEY")); } RsaKeyParameters publicKey = Org.BouncyCastle.Security.DotNetUtilities.GetRsaPublicKey(rsa); // try get public key if (publicKey != null) // if XML RSA key contains public key { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY")); } } throw new InvalidKeyException("Invalid RSA Xml Key"); }
public static string XmlToPem(string xml) { using (RSA rsa = RSA.Create()) { rsa.FromXmlString(xml); AsymmetricCipherKeyPair keyPair = rsa.GetKeyPair(); // try get private and public key pair if (keyPair != null) // if XML RSA key contains private key { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); return(FormatPem(privateKeyInfo.GetEncoded().ToBase64(), "RSA PRIVATE KEY")); } RsaKeyParameters publicKey = rsa.GetPublicKey(); // try get public key if (publicKey != null) // if XML RSA key contains public key { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(publicKeyInfo.GetEncoded().ToBase64(), "PUBLIC KEY")); } } throw new InvalidKeyException("Invalid RSA Xml Key"); }
private void EncodePublicKey() { X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3); if (X9IntegerConverter.GetByteLength(ecP.Curve) != 30) { Fail("wrong byte length reported for curve"); } if (ecP.Curve.FieldSize != 239) { Fail("wrong field size reported for curve"); } // // named curve // X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1); ECPoint point = ecP.G.Multiply(BigInteger.ValueOf(100)); DerOctetString p = new DerOctetString(point.GetEncoded(true)); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets()); if (!Arrays.AreEqual(info.GetEncoded(), namedPub)) { Fail("failed public named generation"); } X9ECPoint x9P = new X9ECPoint(ecP.Curve, p); if (!Arrays.AreEqual(p.GetOctets(), x9P.Point.GetEncoded())) { Fail("point encoding not preserved"); } Asn1Object o = Asn1Object.FromByteArray(namedPub); if (!info.Equals(o)) { Fail("failed public named equality"); } // // explicit curve parameters // _params = new X962Parameters(ecP); info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets()); if (!Arrays.AreEqual(info.GetEncoded(), expPub)) { Fail("failed public explicit generation"); } o = Asn1Object.FromByteArray(expPub); if (!info.Equals(o)) { Fail("failed public explicit equality"); } }
private void EncodePublicKey() { X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3); if (X9IntegerConverter.GetByteLength(ecP.Curve) != 30) { Fail("wrong byte length reported for curve"); } if (ecP.Curve.FieldSize != 239) { Fail("wrong field size reported for curve"); } // // named curve // X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1); X9ECPoint pPoint = new X9ECPoint( new FPPoint(ecP.Curve, new FPFieldElement(BigInteger.Two, BigInteger.One), new FPFieldElement(BigInteger.ValueOf(4), BigInteger.ValueOf(3)), true)); Asn1OctetString p = (Asn1OctetString)pPoint.ToAsn1Object(); if (p == null) { Fail("failed to convert to ASN.1"); } SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets()); if (!Arrays.AreEqual(info.GetEncoded(), namedPub)) { Fail("failed public named generation"); } Asn1Object o = Asn1Object.FromByteArray(namedPub); if (!info.Equals(o)) { Fail("failed public named equality"); } // // explicit curve parameters // _params = new X962Parameters(ecP); info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets()); if (!Arrays.AreEqual(info.GetEncoded(), expPub)) { Fail("failed public explicit generation"); } o = Asn1Object.FromByteArray(expPub); if (!info.Equals(o)) { Fail("failed public explicit equality"); } }
public override void Encode(Stream output) { byte[] derEncoding = mSubjectPublicKeyInfo.GetEncoded(Asn1Encodable.Der); TlsUtilities.WriteOpaque24(derEncoding, output); }