internal static unsafe string DerStringToManagedString( byte[] derString, Asn1StringTypeFlags flags = AnyTextStringType) { SafeAsn1StringHandle asn1String = OpenSslD2I( (zero, ppin, len) => d2i_ASN1_type_bytes(zero, ppin, len, flags), derString, checkHandle: false); if (asn1String.IsInvalid) { return(null); } byte[] utf8Bytes; using (asn1String) using (SafeBioHandle bio = BIO_new(BIO_s_mem())) { int len = ASN1_STRING_print_ex(bio, asn1String, Asn1StringPrintFlags.ASN1_STRFLGS_UTF8_CONVERT); if (len < 0) { throw CreateOpenSslCryptographicException(); } int bioSize = GetMemoryBioSize(bio); utf8Bytes = new byte[bioSize + 1]; int read = BIO_read(bio, utf8Bytes, utf8Bytes.Length); if (read < 0) { throw CreateOpenSslCryptographicException(); } } int nonNullCount = utf8Bytes.Length; if (utf8Bytes[utf8Bytes.Length - 1] == 0) { for (int i = utf8Bytes.Length - 1; i >= 0; i--) { if (utf8Bytes[i] != 0) { break; } nonNullCount = i; } } return(Encoding.UTF8.GetString(utf8Bytes, 0, nonNullCount)); }
internal static unsafe string DerStringToManagedString( byte[] derString, Asn1StringTypeFlags flags=AnyTextStringType) { SafeAsn1StringHandle asn1String = OpenSslD2I( (zero, ppin, len) => d2i_ASN1_type_bytes(zero, ppin, len, flags), derString, checkHandle: false); if (asn1String.IsInvalid) { return null; } byte[] utf8Bytes; using (asn1String) using (SafeBioHandle bio = BIO_new(BIO_s_mem())) { int len = ASN1_STRING_print_ex(bio, asn1String, Asn1StringPrintFlags.ASN1_STRFLGS_UTF8_CONVERT); if (len < 0) { throw CreateOpenSslCryptographicException(); } int bioSize = GetMemoryBioSize(bio); utf8Bytes = new byte[bioSize + 1]; int read = BIO_read(bio, utf8Bytes, utf8Bytes.Length); if (read < 0) { throw CreateOpenSslCryptographicException(); } } int nonNullCount = utf8Bytes.Length; if (utf8Bytes[utf8Bytes.Length - 1] == 0) { for (int i = utf8Bytes.Length - 1; i >= 0; i--) { if (utf8Bytes[i] != 0) { break; } nonNullCount = i; } } return Encoding.UTF8.GetString(utf8Bytes, 0, nonNullCount); }
private static extern SafeAsn1StringHandle DecodeAsn1TypeBytes(byte[] buf, int len, Asn1StringTypeFlags flags);
private static extern SafeAsn1StringHandle DecodeAsn1TypeBytes(byte[] buf, int len, Asn1StringTypeFlags flags);
private static unsafe extern SafeAsn1StringHandle d2i_ASN1_type_bytes(IntPtr zero, byte **ppin, int len, Asn1StringTypeFlags flags);
private static unsafe extern SafeAsn1StringHandle d2i_ASN1_type_bytes(IntPtr zero, byte** ppin, int len, Asn1StringTypeFlags flags);