public static void ConvertPemToDer(Stream source, Stream target) { using (var ts = new StreamReader(source)) { using (var xr = new X509Request(ts.ReadToEnd())) { using (var bio = BIO.MemoryBuffer()) { xr.Write_DER(bio); var arr = bio.ReadBytes((int)bio.BytesPending); target.Write(arr.Array, arr.Offset, arr.Count); } } } }
public void TestGenCSR() { var pem = File.ReadAllText("openssl-rsagen-privatekey.txt"); var rsa = CryptoKey.FromPrivateKey(pem, null); //pem = File.ReadAllText("openssl-rsagen-publickey.txt"); //rsa = CryptoKey.FromPublicKey(pem, null); var nam = new X509Name(); nam.Common = "FOOBAR"; nam.Country = "US"; var csr = new X509Request(); csr.PublicKey = rsa; csr.Subject = nam; csr.Sign(rsa, MessageDigest.SHA256); File.WriteAllText("openssl-requ-csr.txt", csr.PEM); using (var bioOut = BIO.MemoryBuffer()) { csr.Write_DER(bioOut); var arr = bioOut.ReadBytes((int)bioOut.BytesPending); File.WriteAllBytes("openssl-requ-csr.der", arr.Array); } //using (var bioIn = BIO.MemoryBuffer()) //{ // var pem2 = File.ReadAllText("openssl-requ-csr.txt"); // bioIn.Write(pem2); // var csr = new X509Request() // var x509 = new X509Certificate(bioIn); //} }
/// <summary> /// Support exporting CSR to <see cref="EncodingFormat.PEM">PEM</see> /// and <see cref="EncodingFormat.DER">DER</see> formats. /// </summary> public override void ExportCsr(Csr csr, EncodingFormat fmt, Stream target) { if (fmt == EncodingFormat.PEM) { var bytes = Encoding.UTF8.GetBytes(csr.Pem); target.Write(bytes, 0, bytes.Length); } else if (fmt == EncodingFormat.DER) { using (var xr = new X509Request(csr.Pem)) { using (var bio = BIO.MemoryBuffer()) { xr.Write_DER(bio); var arr = bio.ReadBytes((int)bio.BytesPending); target.Write(arr.Array, arr.Offset, arr.Count); } } } else { throw new NotSupportedException("encoding format has not been implemented"); } }