public static string ExportPemEncodedPublicKey(this RSA rsa) { var keyBytes = rsa.ExportRSAPublicKey(); var pemChars = PemEncoding.Write(PemEncodingLabels.RsaPublicKey, keyBytes); return(new string(pemChars)); }
private static FileInfo CreateBundleFile(string directoryPath, X509Certificate2 certificate) { FileInfo file = new(Path.Combine(directoryPath, FallbackCertificateBundleX509ChainFactory.FileName)); char[] pem = PemEncoding.Write("CERTIFICATE", certificate.RawData); File.WriteAllText(file.FullName, new string(pem)); return(file); }
public static void Write_Simple() { string label = "HELLO"; byte[] content = new byte[] { 0x66, 0x6F, 0x6F }; char[] result = PemEncoding.Write(label, content); string pem = new string(result); Assert.Equal("-----BEGIN HELLO-----\nZm9v\n-----END HELLO-----", pem); }
public static V1Secret?AsSecret(this PairingRecord?pairingRecord) { if (pairingRecord == null) { return(null); } var secret = new V1Secret() { ApiVersion = V1Secret.KubeApiVersion, Kind = V1Secret.KubeKind, Type = TlsType, Metadata = new V1ObjectMeta(), Data = new Dictionary <string, byte[]>(), Immutable = true, }; secret.Data[TlsCertificateKey] = Encoding.UTF8.GetBytes( PemEncoding.Write( "CERTIFICATE", pairingRecord.HostCertificate.Export(X509ContentType.Cert))); secret.Data[TlsPrivateKey] = Encoding.UTF8.GetBytes( PemEncoding.Write( "PRIVATE KEY", pairingRecord.HostPrivateKey.ExportPkcs8PrivateKey())); secret.Data[CaCertificateKey] = Encoding.UTF8.GetBytes( PemEncoding.Write( "CERTIFICATE", pairingRecord.RootCertificate.Export(X509ContentType.Cert))); secret.Data[CaPrivateKey] = Encoding.UTF8.GetBytes( PemEncoding.Write( "PRIVATE KEY", pairingRecord.RootPrivateKey.ExportPkcs8PrivateKey())); secret.Data[DeviceCertificateKey] = Encoding.UTF8.GetBytes( PemEncoding.Write( "CERTIFICATE", pairingRecord.DeviceCertificate.Export(X509ContentType.Cert))); secret.Data[EscrowBagKey] = pairingRecord.EscrowBag; secret.Data[HostIdKey] = Encoding.UTF8.GetBytes(pairingRecord.HostId); secret.Data[SystemBuidKey] = Encoding.UTF8.GetBytes(pairingRecord.SystemBUID); secret.Data[WifiMacAddressKey] = pairingRecord.WiFiMacAddress == null ? null : Encoding.UTF8.GetBytes(pairingRecord.WiFiMacAddress); return(secret); }
/// <summary> /// Exports the private key of the specified certificate using the new .net 6 method /// </summary> /// <param name="certificate"></param> /// <returns></returns> private static string ExportPrivateKeyPkcs1Pem(X509Certificate2 certificate) { RSA rsa = certificate.GetRSAPrivateKey(); Assert.NotNull(rsa); byte[] privateKeyBytes = rsa.ExportRSAPrivateKey(); char[] privateKeyPem = PemEncoding.Write("RSA PRIVATE KEY", privateKeyBytes); return(new string(privateKeyPem)); }
public static string GeneratePEMWithPrivateKeyAsString(X509Certificate2 certificate) { var sb = new StringBuilder(); AsymmetricAlgorithm key = certificate.GetRSAPrivateKey(); byte[] privKeyBytes = key.ExportPkcs8PrivateKey(); char[] privKeyPem = PemEncoding.Write("PRIVATE KEY", privKeyBytes); char[] certificatePem = PemEncoding.Write("CERTIFICATE", certificate.GetRawCertData()); sb.AppendLine(new string(privKeyPem)); sb.AppendLine(); sb.AppendLine(new string(certificatePem)); return(sb.ToString()); }
private string ToPEMCertificateChain(byte[] orderCertificate) { var certificateCollection = new X509Certificate2Collection(); certificateCollection.Import(orderCertificate); var stringBuilder = new StringBuilder(); foreach (var certificate in certificateCollection) { var certPem = PemEncoding.Write("CERTIFICATE", certificate.Export(X509ContentType.Cert)); stringBuilder.AppendLine(new string(certPem)); } return(stringBuilder.ToString()); }
internal CertificateData(byte[] rawData) { #if DEBUG try { #endif RawData = rawData; certificate = CertificateAsn.Decode(rawData, AsnEncodingRules.DER); certificate.TbsCertificate.ValidateVersion(); Issuer = new X500DistinguishedName(certificate.TbsCertificate.Issuer.Span); Subject = new X500DistinguishedName(certificate.TbsCertificate.Subject.Span); IssuerName = Issuer.Name; SubjectName = Subject.Name; AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); certificate.TbsCertificate.SubjectPublicKeyInfo.Encode(writer); SubjectPublicKeyInfo = writer.Encode(); Extensions = new List <X509Extension>((certificate.TbsCertificate.Extensions?.Length).GetValueOrDefault()); if (certificate.TbsCertificate.Extensions != null) { foreach (X509ExtensionAsn rawExtension in certificate.TbsCertificate.Extensions) { X509Extension extension = new X509Extension( rawExtension.ExtnId, rawExtension.ExtnValue.Span, rawExtension.Critical); Extensions.Add(extension); } } #if DEBUG } catch (Exception e) { string pem = new string(PemEncoding.Write(PemLabels.X509Certificate, rawData)); throw new CryptographicException($"Error in reading certificate:{Environment.NewLine}{pem}", e); } #endif }
private static byte[] SerializePrivateKey(RSA privateKey) { if (privateKey == null) { return(null); } var pemEncoded = PemEncoding.Write( "RSA PRIVATE KEY", privateKey.ExportRSAPrivateKey()); // Append a \n character at the end var length = Encoding.UTF8.GetByteCount(pemEncoded) + 1; var bytes = new byte[length]; Encoding.UTF8.GetBytes(pemEncoded, bytes); bytes[length - 1] = 0xA; return(bytes); }
private static byte[] SerializeCertificate(X509Certificate certificate) { if (certificate == null) { return(null); } char[] pemEncoded = PemEncoding.Write( "CERTIFICATE", certificate.Export(X509ContentType.Cert)); // Append a \n character at the end var length = Encoding.UTF8.GetByteCount(pemEncoded) + 1; var bytes = new byte[length]; Encoding.UTF8.GetBytes(pemEncoded, bytes); bytes[length - 1] = 0xA; return(bytes); }
private static void WriteCertificateBundle(FileInfo certificateBundle, X509Certificate2Collection certificates) { FileInfo file = new(Path.GetTempFileName()); try { using (StreamWriter writer = new(file.FullName)) { foreach (X509Certificate2 certificate in certificates) { char[] pem = PemEncoding.Write("CERTIFICATE", certificate.RawData); writer.WriteLine(pem); writer.WriteLine(); } } File.Copy(file.FullName, certificateBundle.FullName, overwrite: true); } finally { file.Delete(); } }
/// <summary> /// Converts this <see cref="X509Certificate2"/> to a <see cref="V1Secret"/>. /// </summary> /// <param name="certificate"> /// A <see cref="X509Certificate2"/> which represents a TLS certificate. /// </param> /// <returns> /// The equivalent <see cref="V1Secret"/>. /// </returns> public static V1Secret AsSecret(this X509Certificate2 certificate) { var secret = new V1Secret() { ApiVersion = V1Secret.KubeApiVersion, Kind = V1Secret.KubeKind, Type = TlsType, Metadata = new V1ObjectMeta() { // Must conform to a DNS subdomain naming rules, so all lowercase ASCII. Name = certificate.Thumbprint.ToLowerInvariant(), Labels = new Dictionary <string, string>(), }, Data = new Dictionary <string, byte[]>(), Immutable = true, }; var certificateAsPem = PemEncoding.Write( "CERTIFICATE", certificate.Export(X509ContentType.Cert)); secret.Data[TlsCertificate] = Encoding.UTF8.GetBytes(certificateAsPem); if (certificate.PrivateKey != null) { var keyAsPem = PemEncoding.Write( "PRIVATE KEY", certificate.PrivateKey.ExportPkcs8PrivateKey()); secret.Data[TlsPrivateKey] = Encoding.UTF8.GetBytes(keyAsPem); } return(secret); }
internal void ExportCertificate(X509Certificate2 certificate, string path, bool includePrivateKey, string password, CertificateKeyExportFormat format) { Log.ExportCertificateStart(GetDescription(certificate), path, includePrivateKey); if (includePrivateKey && password == null) { Log.NoPasswordForCertificate(); } var targetDirectoryPath = Path.GetDirectoryName(path); if (targetDirectoryPath != "") { Log.CreateExportCertificateDirectory(targetDirectoryPath); Directory.CreateDirectory(targetDirectoryPath); } byte[] bytes; byte[] keyBytes; byte[] pemEnvelope = null; RSA key = null; try { if (includePrivateKey) { switch (format) { case CertificateKeyExportFormat.Pfx: bytes = certificate.Export(X509ContentType.Pkcs12, password); break; case CertificateKeyExportFormat.Pem: key = certificate.GetRSAPrivateKey(); char[] pem; if (password != null) { keyBytes = key.ExportEncryptedPkcs8PrivateKey(password, new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 100000)); pem = PemEncoding.Write("ENCRYPTED PRIVATE KEY", keyBytes); pemEnvelope = Encoding.ASCII.GetBytes(pem); } else { // Export the key first to an encrypted PEM to avoid issues with System.Security.Cryptography.Cng indicating that the operation is not supported. // This is likely by design to avoid exporting the key by mistake. // To bypass it, we export the certificate to pem temporarily and then we import it and export it as unprotected PEM. keyBytes = key.ExportEncryptedPkcs8PrivateKey("", new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 1)); pem = PemEncoding.Write("ENCRYPTED PRIVATE KEY", keyBytes); key.Dispose(); key = RSA.Create(); key.ImportFromEncryptedPem(pem, ""); Array.Clear(keyBytes, 0, keyBytes.Length); Array.Clear(pem, 0, pem.Length); keyBytes = key.ExportPkcs8PrivateKey(); pem = PemEncoding.Write("PRIVATE KEY", keyBytes); pemEnvelope = Encoding.ASCII.GetBytes(pem); } Array.Clear(keyBytes, 0, keyBytes.Length); Array.Clear(pem, 0, pem.Length); bytes = certificate.Export(X509ContentType.Cert); break; default: throw new InvalidOperationException("Unknown format."); } } else { bytes = certificate.Export(X509ContentType.Cert); } } catch (Exception e) { Log.ExportCertificateError(e.ToString()); throw; } finally { key?.Dispose(); } try { Log.WriteCertificateToDisk(path); File.WriteAllBytes(path, bytes); } catch (Exception ex) { Log.WriteCertificateToDiskError(ex.ToString()); throw; } finally { Array.Clear(bytes, 0, bytes.Length); } if (includePrivateKey && format == CertificateKeyExportFormat.Pem) { try { var keyPath = Path.ChangeExtension(path, ".key"); Log.WritePemKeyToDisk(keyPath); File.WriteAllBytes(keyPath, pemEnvelope); } catch (Exception ex) { Log.WritePemKeyToDiskError(ex.ToString()); throw; } finally { Array.Clear(pemEnvelope, 0, pemEnvelope.Length); } } }
private static void CreateBundleFile(FileInfo file, X509Certificate2 certificate) { char[] pem = PemEncoding.Write("CERTIFICATE", certificate.RawData); File.WriteAllText(file.FullName, new string(pem)); }
private Renci.SshNet.SftpClient _getSFtpClientWithCertificate() { #if NETSTANDARD2_0 || NET472 throw new NotSupportedException($"ClientCertificate does not support X509 Certificate in NETCORE2.0 nor NET472"); #else var connInfo = _getConnectionInfo(); var cert = FtpConfig.ClientCertificate; string keyExchangeAlgorithm = null; byte[] privateKeyBytes = null; string privateKeyPemString; bool isKeyNull = false; switch (cert.PublicKey.Oid.Value) { case _rsa: { using RSA rsaKey = cert.GetRSAPrivateKey(); keyExchangeAlgorithm = rsaKey.KeyExchangeAlgorithm; if (rsaKey != null) { privateKeyBytes = rsaKey.ExportRSAPrivateKey(); } else { isKeyNull = true; } break; } case _dsa: { using DSA dsaKey = cert.GetDSAPrivateKey(); keyExchangeAlgorithm = dsaKey.KeyExchangeAlgorithm; if (dsaKey != null) { privateKeyBytes = dsaKey.ExportPkcs8PrivateKey(); } else { isKeyNull = true; } break; } case _ecdsa: { using ECDsa ecdsaKey = cert.GetECDsaPrivateKey(); keyExchangeAlgorithm = ecdsaKey.KeyExchangeAlgorithm; if (ecdsaKey != null) { privateKeyBytes = ecdsaKey.ExportPkcs8PrivateKey(); } else { isKeyNull = true; } break; } default: throw new NotSupportedException($"ClientCertificate does not support the given algorithm {cert.PublicKey.Oid.FriendlyName}"); } if (isKeyNull) { throw new ArgumentNullException($"ClientCertificate has a null Key"); } #if NET5_0_OR_GREATER var privateKeyPem = PemEncoding.Write($"{keyExchangeAlgorithm} PRIVATE KEY", privateKeyBytes); privateKeyPemString = new string(privateKeyPem); #else var builder = new StringBuilder(); builder.AppendLine($"-----BEGIN {keyExchangeAlgorithm} PRIVATE KEY-----"); builder.AppendLine( Convert.ToBase64String(privateKeyBytes, Base64FormattingOptions.InsertLineBreaks)); builder.AppendLine($"-----END {keyExchangeAlgorithm} PRIVATE KEY-----"); privateKeyPemString = builder.ToString(); #endif var byteArray = Encoding.UTF8.GetBytes(privateKeyPemString); using var ms = new MemoryStream(byteArray); using var privateKeyFile = new PrivateKeyFile(ms); return(new Renci.SshNet.SftpClient(connInfo.Host, connInfo.Username, new PrivateKeyFile[] { privateKeyFile }) { KeepAliveInterval = _keepAliveInterval, OperationTimeout = _operationTimeout, }); #endif }