public static String generatePem() { // Create a new key BitCoinSharp.EcKey keys = new BitCoinSharp.EcKey(); StringWriter stringWriter = new StringWriter (); PemWriter pemWriter = new PemWriter (stringWriter); const string DER1 = "30740201010420"; string privKey = (privKeyFromKeyPair (keys)); // Make sure private key is in correct format privKey = checkHas64 (privKey); const string DER2 = "a0070605"; const string DER3 = "2b8104000a"; const string DER4 = "a144034200"; string pubKey = uncompressedPubKeyFromKeyPair (keys); string fullDER = DER1 + privKey + DER2 + DER3 + DER4 + pubKey; PemObject pemObj = new PemObject("EC PRIVATE KEY", hexToBytes(fullDER)); pemWriter.WriteObject(pemObj); string pem = stringWriter.ToString (); return pem; }
private string GeneratePkcs1PublicKeyFromRsaEncryptedOpenSshPublicKey(string content) { List <byte[]> data = this.GetOpenSshPublicKeyInBinary(content); if (data.Count != 3) { throw new InvalidOperationException("Given OpenSSH key body is invalid."); } //// RFC 3447 (PKCS #1) //// 3.1 RSA public key //// For the purposes of this document, an RSA public key consists of two //// components: //// n the RSA modulus, a positive integer //// e the RSA public exponent, a positive integer //// A recommended syntax for interchanging RSA public keys between //// implementations is given in Appendix A.1.1; an implementation's //// internal representation may differ. //// A.1.1 RSA public key syntax //// An RSA public key should be represented with the ASN.1 type //// RSAPublicKey: //// RSAPublicKey ::= SEQUENCE { //// modulus INTEGER, -- n //// publicExponent INTEGER -- e //// } //// The fields of type RSAPublicKey have the following meanings: //// * modulus is the RSA modulus n. //// * publicExponent is the RSA public exponent e. //// RFC 4251: Strings are also used to store text. In that case, US-ASCII is //// used for internal names, and ISO-10646 UTF-8 for text that might be displayed to the user. string algorithmName = Encoding.UTF8.GetString(data[0]); if (!"ssh-rsa".Equals(algorithmName, StringComparison.Ordinal)) { throw new InvalidOperationException("Invalid OpenSSH key body, expected 'ssh-rsa' encrypted."); } var publicExponent = new DerInteger(data[1]); var modulus = new DerInteger(data[2]); var sequence = new DerSequence(new Asn1Encodable[] { modulus, publicExponent }); // Generate DER-encoded public key StringBuilder sb = new StringBuilder(); using (var sw = new StringWriter(sb, CultureInfo.InvariantCulture)) { var pemWriter = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(sw); pemWriter.WriteObject(new PemObject("RSA PUBLIC KEY", sequence.GetEncoded())); } return(sb.ToString()); }
private static string ConvertPrivateKeyToPem(AsymmetricKeyParameter privateKey) { using (var stringWriter = new StringWriter()) { var pkcsgen = new Pkcs8Generator(privateKey); var pemwriter = new PemWriter(stringWriter); pemwriter.WriteObject(pkcsgen.Generate()); return stringWriter.ToString(); } }
private static string ConvertPrivateKeyToPem(AsymmetricKeyParameter privateKey) { using (var stringWriter = new StringWriter()) { var pkcsgen = new Pkcs8Generator(privateKey); var pemwriter = new PemWriter(stringWriter); pemwriter.WriteObject(pkcsgen.Generate()); return(stringWriter.ToString()); } }
private static string ConvertPublicKeyToPem(AsymmetricKeyParameter pubKey) { using (var stringWriter = new StringWriter()) { var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey); var pemWriter = new PemWriter(stringWriter); PemObjectGenerator pemObject = new PemObject("PUBLIC KEY", publicKeyInfo.GetEncoded()); pemWriter.WriteObject(pemObject); return stringWriter.ToString(); } }
private static string ConvertPublicKeyToPem(AsymmetricKeyParameter pubKey) { using (var stringWriter = new StringWriter()) { var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey); var pemWriter = new PemWriter(stringWriter); PemObjectGenerator pemObject = new PemObject("PUBLIC KEY", publicKeyInfo.GetEncoded()); pemWriter.WriteObject(pemObject); return(stringWriter.ToString()); } }
/// <summary> /// eth Sign /// </summary> /// <param name="macdata"></param> /// <param name="ecdsaPrivateKey"></param> /// <returns>r,s,v</returns> public static Tuple <byte[], byte[], byte[]> Sign(byte[] macdata, ECPrivateKeyParameters ecdsaPrivateKey) { MessageSigner signer = new MessageSigner(); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecdsaPrivateKey); PemObject pemObj = new PemObject("PRIVATE KEY", privateKeyInfo.ToAsn1Object().GetEncoded()); StringWriter strPri = new StringWriter(); Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemW = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(strPri); pemW.WriteObject(pemObj); var signData = signer.SignAndCalculateV(macdata, ConvertPrikToHexString(strPri.ToString())); return(new Tuple <byte[], byte[], byte[]>(signData.R, signData.S, signData.V)); }
/// <summary> /// save private key /// </summary> /// <param name="privateKey">private key</param> /// <param name="pkUrl">key file</param> public static void SavePriKey(AsymmetricKeyParameter privateKey, string pkUrl) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); PemObject pemObj = new PemObject("PRIVATE KEY", privateKeyInfo.ToAsn1Object().GetEncoded()); StringWriter strPri = new StringWriter(); Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemW = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(strPri); pemW.WriteObject(pemObj); byte[] priInfoByte = System.Text.Encoding.UTF8.GetBytes(strPri.ToString()); FileStream fs = new FileStream(pkUrl, FileMode.Create, FileAccess.Write); fs.Write(priInfoByte, 0, priInfoByte.Length); fs.Close(); }
/// <summary> /// save public key /// </summary> /// <param name="publicKey">public key</param> /// <param name="pkUrl">key file</param> /// <returns></returns> public static bool SavePubKey(ECPublicKeyParameters publicKey, string pkUrl) { try { //save public key SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); PemObject pemObj = new PemObject("PUBLIC KEY", publicKeyInfo.ToAsn1Object().GetEncoded()); StringWriter strPri = new StringWriter(); Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemW = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(strPri); pemW.WriteObject(pemObj); byte[] priInfoByte = System.Text.Encoding.UTF8.GetBytes(strPri.ToString()); FileStream fs = new FileStream(pkUrl, FileMode.Create, FileAccess.Write); fs.Write(priInfoByte, 0, priInfoByte.Length); fs.Close(); return(true); } catch (Exception ex) { return(false); } }
public override void PerformTest() { IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); dsaKpg.Init(new DsaKeyGenerationParameters(random, testDsaParams)); AsymmetricCipherKeyPair testDsaKp = dsaKpg.GenerateKeyPair(); AsymmetricKeyParameter testDsaKey = testDsaKp.Private; DoWriteReadTest(testDsaKey); DoWriteReadTests(testDsaKey, algorithms); DoWriteReadTest(testRsaKey); DoWriteReadTests(testRsaKey, algorithms); AsymmetricKeyParameter ecPriv = PrivateKeyFactory.CreateKey(testEcDsaKeyBytes); DoWriteReadTest(ecPriv); DoWriteReadTests(ecPriv, algorithms); IAsymmetricCipherKeyPairGenerator ecKpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); ecKpg.Init(new KeyGenerationParameters(random, 239)); ecPriv = ecKpg.GenerateKeyPair().Private; DoWriteReadTest(ecPriv); DoWriteReadTests(ecPriv, algorithms); // override test PemWriter pWrt = new PemWriter(new StringWriter()); object o = new PemObject("FRED", new byte[100]); pWrt.WriteObject(o); pWrt.Writer.Close(); }
private void DoWriteReadTest( AsymmetricKeyParameter akp, string algorithm) { StringWriter sw = new StringWriter(); PemWriter pw = new PemWriter(sw); pw.WriteObject(akp, algorithm, testPassword, random); pw.Writer.Close(); string data = sw.ToString(); PemReader pr = new PemReader(new StringReader(data), new Password(testPassword)); AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair; if (kp == null || !kp.Private.Equals(akp)) { Fail("Failed to read back test key encoded with: " + algorithm); } }
private void DoWriteReadTest( AsymmetricKeyParameter akp) { StringWriter sw = new StringWriter(); PemWriter pw = new PemWriter(sw); pw.WriteObject(akp); pw.Writer.Close(); string data = sw.ToString(); PemReader pr = new PemReader(new StringReader(data)); AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair; if (kp == null || !kp.Private.Equals(akp)) { Fail("Failed to read back test key"); } }
private string GenerateX509Cert(string publicKey, string x509Subject) { Asn1Sequence asn1Sequence = null; using (var reader = new StringReader(publicKey)) { // Read the RSA public key from the input string. var pemReader = new PemReader(reader); var pemObject = pemReader.ReadPemObject(); asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pemObject.Content); } // Generate a TBS certificate. We use placeholder-like values since // the consumer of this certificate should only use the subject // public key info. var tbsCertGen = new V3TbsCertificateGenerator(); tbsCertGen.SetSerialNumber(new DerInteger(1)); var signatureAlgId = new AlgorithmIdentifier(PkcsObjectIdentifiers.Sha1WithRsaEncryption, DerNull.Instance); tbsCertGen.SetSignature(signatureAlgId); tbsCertGen.SetIssuer(new X509Name("CN=Root Agency")); var dateTimeNow = DateTime.Now; tbsCertGen.SetStartDate(new Time(dateTimeNow.AddMinutes(-10))); tbsCertGen.SetEndDate(new Time(dateTimeNow.AddYears(1))); // Openssh key doesn`t have any start/end date, this is to satisfy RDFE tbsCertGen.SetSubject(new X509Name(x509Subject)); tbsCertGen.SetSubjectPublicKeyInfo(new SubjectPublicKeyInfo(new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), asn1Sequence)); var tbsCert = tbsCertGen.GenerateTbsCertificate(); // Per RFC 3280, the layout of an X.509 v3 certificate looks like: // Certificate ::= SEQUENCE { // tbsCertificate TBSCertificate, // signatureAlgorithm AlgorithmIdentifier, // signatureValue BIT STRING // } // Since we don't have access to the private key, we cannot create // a signature for the TBS. However, a valid certificate requires // a bit string for the signature value, so we use a 0-byte array // in its place. Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(tbsCert); v.Add(signatureAlgId); v.Add(new DerBitString(new byte[0])); var derSequence = new DerSequence(v); // Output the DER-encoded X509 certificate. var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { var pemWriter = new PemWriter(writer); pemWriter.WriteObject(new PemObject("CERTIFICATE", derSequence.GetEncoded())); } return sb.ToString(); }
private string GeneratePkcs1PublicKeyFromRsaEncryptedOpenSshPublicKey(string content) { List<byte[]> data = this.GetOpenSshPublicKeyInBinary(content); if (data.Count != 3) { throw new InvalidOperationException("Given OpenSSH key body is invalid."); } //// RFC 3447 (PKCS #1) //// 3.1 RSA public key //// For the purposes of this document, an RSA public key consists of two //// components: //// n the RSA modulus, a positive integer //// e the RSA public exponent, a positive integer //// A recommended syntax for interchanging RSA public keys between //// implementations is given in Appendix A.1.1; an implementation's //// internal representation may differ. //// A.1.1 RSA public key syntax //// An RSA public key should be represented with the ASN.1 type //// RSAPublicKey: //// RSAPublicKey ::= SEQUENCE { //// modulus INTEGER, -- n //// publicExponent INTEGER -- e //// } //// The fields of type RSAPublicKey have the following meanings: //// * modulus is the RSA modulus n. //// * publicExponent is the RSA public exponent e. //// RFC 4251: Strings are also used to store text. In that case, US-ASCII is //// used for internal names, and ISO-10646 UTF-8 for text that might be displayed to the user. string algorithmName = Encoding.UTF8.GetString(data[0]); if (!"ssh-rsa".Equals(algorithmName, StringComparison.Ordinal)) { throw new InvalidOperationException("Invalid OpenSSH key body, expected 'ssh-rsa' encrypted."); } var publicExponent = new DerInteger(data[1]); var modulus = new DerInteger(data[2]); var sequence = new DerSequence(new Asn1Encodable[] { modulus, publicExponent }); // Generate DER-encoded public key StringBuilder sb = new StringBuilder(); using (var sw = new StringWriter(sb, CultureInfo.InvariantCulture)) { var pemWriter = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(sw); pemWriter.WriteObject(new PemObject("RSA PUBLIC KEY", sequence.GetEncoded())); } return sb.ToString(); }