public byte[] Export(X509ContentType contentType, string password) { // Export is for X509Certificate2Collections in their IStorePal guise, // if someone wanted to export whole stores they'd need to do // store.Certificates.Export(...), which would end up in the // CollectionBackedStoreProvider. Debug.Fail("Export was unexpected on a DirectoryBasedStore"); throw new InvalidOperationException(); }
public byte[] Export(X509ContentType contentType, string password) { switch (contentType) { case X509ContentType.Cert: return ExportX509Der(); case X509ContentType.Pfx: return ExportPfx(password); default: throw new NotImplementedException(); } }
public byte[] Export(X509ContentType contentType, string password) { switch (contentType) { case X509ContentType.Cert: return ExportX509Der(); case X509ContentType.Pfx: return ExportPfx(password); case X509ContentType.Pkcs7: return ExportPkcs7(); case X509ContentType.SerializedCert: case X509ContentType.SerializedStore: throw new PlatformNotSupportedException(SR.Cryptography_Unix_X509_SerializedExport); default: throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); } }
internal static SafeSecCertificateHandle X509ImportCertificate( byte[] bytes, X509ContentType contentType, SafePasswordHandle importPassword, SafeKeychainHandle keychain, bool exportable, out SafeSecIdentityHandle identityHandle) { SafeSecCertificateHandle certHandle; int osStatus; int ret; SafeCreateHandle cfPassphrase = s_nullExportString; bool releasePassword = false; try { if (!importPassword.IsInvalid) { importPassword.DangerousAddRef(ref releasePassword); IntPtr passwordHandle = importPassword.DangerousGetHandle(); if (passwordHandle != IntPtr.Zero) { cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle); } } ret = AppleCryptoNative_X509ImportCertificate( bytes, bytes.Length, contentType, cfPassphrase, keychain, exportable ? 1 : 0, out certHandle, out identityHandle, out osStatus); SafeTemporaryKeychainHandle.TrackItem(certHandle); SafeTemporaryKeychainHandle.TrackItem(identityHandle); } finally { if (releasePassword) { importPassword.DangerousRelease(); } if (cfPassphrase != s_nullExportString) { cfPassphrase.Dispose(); } } if (ret == 1) { return(certHandle); } certHandle.Dispose(); identityHandle.Dispose(); const int SeeOSStatus = 0; const int ImportReturnedEmpty = -2; const int ImportReturnedNull = -3; switch (ret) { case SeeOSStatus: throw CreateExceptionForOSStatus(osStatus); case ImportReturnedNull: case ImportReturnedEmpty: throw new CryptographicException(); default: Debug.Fail($"Unexpected return value {ret}"); throw new CryptographicException(); } }
public byte[] Export(X509ContentType contentType, string password) { throw new NotImplementedException(); }
public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password) { ThrowIfContextInvalid (impl); return impl.Export (contentType, password); }
public byte[] Export(X509ContentType contentType, string password) { switch (contentType) { case X509ContentType.Cert: { SafeCertContextHandle pCertContext = null; if (!Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext)) return null; try { unsafe { byte[] rawData = new byte[pCertContext.CertContext->cbCertEncoded]; Marshal.Copy((IntPtr)(pCertContext.CertContext->pbCertEncoded), rawData, 0, rawData.Length); GC.KeepAlive(pCertContext); return rawData; } } finally { pCertContext.Dispose(); } } case X509ContentType.SerializedCert: { SafeCertContextHandle pCertContext = null; if (!Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext)) return null; try { int cbEncoded = 0; if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, null, ref cbEncoded)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; byte[] pbEncoded = new byte[cbEncoded]; if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, pbEncoded, ref cbEncoded)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; return pbEncoded; } finally { pCertContext.Dispose(); } } case X509ContentType.Pkcs12: { unsafe { CRYPTOAPI_BLOB dataBlob = new CRYPTOAPI_BLOB(0, (byte*)null); if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; byte[] pbEncoded = new byte[dataBlob.cbData]; fixed (byte* ppbEncoded = pbEncoded) { dataBlob.pbData = ppbEncoded; if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; } return pbEncoded; } } case X509ContentType.SerializedStore: return SaveToMemoryStore(CertStoreSaveAs.CERT_STORE_SAVE_AS_STORE); case X509ContentType.Pkcs7: return SaveToMemoryStore(CertStoreSaveAs.CERT_STORE_SAVE_AS_PKCS7); default: throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); } }
public virtual byte[] Export (X509ContentType contentType) { return Export (contentType, (byte[])null); }
public bool PosTest(int id, string msg, X509ContentType x509ConType, TestDelegate d) { bool retVal = true; X509Certificate cer; byte[] bytes; TestLibrary.TestFramework.BeginScenario("PosTest"+id+": " + msg + " = " + x509ConType); try { cer = new X509Certificate(c_CERTFILE); bytes = d(cer, x509ConType); if (null == bytes) { TestLibrary.TestFramework.LogError("000", "Export return null!"); TestLibrary.TestFramework.LogInformation(""); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(""); retVal = false; } return retVal; }
public byte[] Export(X509ContentType contentType) { return(Export(contentType, null)); }
public static byte[] ConvertToBytes(this X509Certificate2 @this, string password, X509ContentType certificateType = X509ContentType.Pfx) { return(@this.Export(certificateType, password)); }
public static ICertificatePal FromBlob( ReadOnlySpan <byte> rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(password != null); X509ContentType contentType = X509Certificate2.GetCertContentType(rawData); if (contentType == X509ContentType.Pkcs7) { // In single mode for a PKCS#7 signed or signed-and-enveloped file we're supposed to return // the certificate which signed the PKCS#7 file. // // X509Certificate2Collection::Export(X509ContentType.Pkcs7) claims to be a signed PKCS#7, // but doesn't emit a signature block. So this is hard to test. // // TODO(2910): Figure out how to extract the signing certificate, when it's present. throw new CryptographicException(SR.Cryptography_X509_PKCS7_NoSigner); } if (contentType == X509ContentType.Pkcs12) { if ((keyStorageFlags & X509KeyStorageFlags.EphemeralKeySet) == X509KeyStorageFlags.EphemeralKeySet) { throw new PlatformNotSupportedException(SR.Cryptography_X509_NoEphemeralPfx); } bool exportable = (keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable; bool persist = (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet; SafeKeychainHandle keychain = persist ? Interop.AppleCrypto.SecKeychainCopyDefault() : Interop.AppleCrypto.CreateTemporaryKeychain(); using (keychain) { AppleCertificatePal ret = ImportPkcs12(rawData, password, exportable, keychain); if (!persist) { // If we used temporary keychain we need to prevent deletion. // on 10.15+ if keychain is unlinked, certain certificate operations may fail. bool success = false; keychain.DangerousAddRef(ref success); if (success) { ret._tempKeychain = keychain; } } return(ret); } } SafeSecIdentityHandle identityHandle; SafeSecCertificateHandle certHandle = Interop.AppleCrypto.X509ImportCertificate( rawData, contentType, SafePasswordHandle.InvalidHandle, SafeTemporaryKeychainHandle.InvalidHandle, exportable: true, out identityHandle); if (identityHandle.IsInvalid) { identityHandle.Dispose(); return(new AppleCertificatePal(certHandle)); } Debug.Fail("Non-PKCS12 import produced an identity handle"); identityHandle.Dispose(); certHandle.Dispose(); throw new CryptographicException(); }
internal static extern byte[] _ExportCertificatesToBlob(SafeCertStoreHandle safeCertStoreHandle, X509ContentType contentType, IntPtr password);
private static extern int AppleCryptoNative_X509ExportData( SafeCreateHandle data, X509ContentType type, SafeCreateHandle cfExportPassphrase, out SafeCFDataHandle pExportOut, out int pOSStatus);
internal static SafeCFArrayHandle X509ImportCollection( ReadOnlySpan <byte> bytes, X509ContentType contentType, SafePasswordHandle importPassword, SafeKeychainHandle keychain, bool exportable) { SafeCreateHandle cfPassphrase = s_nullExportString; bool releasePassword = false; int ret; SafeCFArrayHandle collectionHandle; int osStatus; try { if (!importPassword.IsInvalid) { importPassword.DangerousAddRef(ref releasePassword); IntPtr passwordHandle = importPassword.DangerousGetHandle(); if (passwordHandle != IntPtr.Zero) { cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle); } } ret = AppleCryptoNative_X509ImportCollection( ref MemoryMarshal.GetReference(bytes), bytes.Length, contentType, cfPassphrase, keychain, exportable ? 1 : 0, out collectionHandle, out osStatus); if (ret == 1) { return(collectionHandle); } } finally { if (releasePassword) { importPassword.DangerousRelease(); } if (cfPassphrase != s_nullExportString) { cfPassphrase.Dispose(); } } collectionHandle.Dispose(); const int SeeOSStatus = 0; const int ImportReturnedEmpty = -2; const int ImportReturnedNull = -3; switch (ret) { case SeeOSStatus: throw CreateExceptionForOSStatus(osStatus); case ImportReturnedNull: case ImportReturnedEmpty: throw new CryptographicException(); default: Debug.Fail($"Unexpected return value {ret}"); throw new CryptographicException(); } }
/// <summary> /// 从本机当前用户证书存储区域导出证书 /// </summary> /// <param name="subjectName"></param> /// <param name="fileName"></param> /// <param name="password"></param> /// <param name="isDeleteFromStore"></param> /// <param name="x509type"></param> /// <returns></returns> private static bool ExportFile(string subjectName, string fileName, string password, bool isDeleteFromStore, X509ContentType x509type) { subjectName = "CN=" + subjectName; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates; foreach (X509Certificate2 x509 in storecollection) { if (x509.Subject == subjectName) { Debug.Print(string.Format("certificate name: {0}", x509.Subject)); byte[] certificateBytes = null; if (x509type == X509ContentType.Pfx) { certificateBytes = x509.Export(x509type, password); } else { certificateBytes = x509.Export(x509type); } using (FileStream fileStream = new FileStream(fileName, FileMode.Create)) { for (int i = 0; i < certificateBytes.Length; i++) { fileStream.WriteByte(certificateBytes[i]); } fileStream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < fileStream.Length; i++) { if (certificateBytes[i] != fileStream.ReadByte()) { fileStream.Close(); return(false); } } fileStream.Close(); } if (isDeleteFromStore == true) { store.Remove(x509); } } } store.Close(); return(true); }
public byte[] Export(X509ContentType contentType);
public virtual byte[] Export(X509ContentType contentType) { return(ExportHelper(contentType, null)); }
public virtual byte[] Export(X509ContentType contentType, string password);
[System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] Export(X509ContentType contentType, SecureString password) { return(ExportHelper(contentType, password)); }
private static void TestExportSingleCert(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(blob); int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { Assert.NotSame(msCer, c); Assert.NotSame(pfxCer, c); Assert.True(msCer.Equals(c) || pfxCer.Equals(c)); } } }
private static partial int AppleCryptoNative_X509ImportCollection( ref byte pbKeyBlob, int cbKeyBlob, X509ContentType contentType, SafeCreateHandle cfPfxPassphrase, out SafeCFArrayHandle pCollectionOut);
public virtual byte[] Export (X509ContentType contentType, SecureString password) { byte[] pwd = (password == null) ? null : password.GetBuffer (); return Export (contentType, pwd); }
public byte[] Export(X509ContentType contentType, SafePasswordHandle password) => _realPal.Export(contentType, password);
public byte[] Export(X509ContentType contentType, String password) { using (IStorePal storePal = StorePal.LinkFromCertificateCollection(this)) { return storePal.Export(contentType, password); } }
public byte[]? Export(X509ContentType contentType, SafePasswordHandle password) { Debug.Assert(password != null); switch (contentType) { case X509ContentType.Cert: { SafeCertContextHandle?pCertContext = null; if (!Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext)) { return(null); } try { unsafe { byte[] rawData = new byte[pCertContext.CertContext->cbCertEncoded]; Marshal.Copy((IntPtr)(pCertContext.CertContext->pbCertEncoded), rawData, 0, rawData.Length); GC.KeepAlive(pCertContext); return(rawData); } } finally { pCertContext.Dispose(); } } case X509ContentType.SerializedCert: { SafeCertContextHandle?pCertContext = null; if (!Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext)) { return(null); } try { int cbEncoded = 0; if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, null, ref cbEncoded)) { throw Marshal.GetHRForLastWin32Error().ToCryptographicException(); } byte[] pbEncoded = new byte[cbEncoded]; if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, pbEncoded, ref cbEncoded)) { throw Marshal.GetHRForLastWin32Error().ToCryptographicException(); } return(pbEncoded); } finally { pCertContext.Dispose(); } } case X509ContentType.Pkcs12: { unsafe { CRYPTOAPI_BLOB dataBlob = new CRYPTOAPI_BLOB(0, (byte *)null); if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) { throw Marshal.GetHRForLastWin32Error().ToCryptographicException(); } byte[] pbEncoded = new byte[dataBlob.cbData]; fixed(byte *ppbEncoded = pbEncoded) { dataBlob.pbData = ppbEncoded; if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) { throw Marshal.GetHRForLastWin32Error().ToCryptographicException(); } } return(pbEncoded); } } case X509ContentType.SerializedStore: return(SaveToMemoryStore(CertStoreSaveAs.CERT_STORE_SAVE_AS_STORE)); case X509ContentType.Pkcs7: return(SaveToMemoryStore(CertStoreSaveAs.CERT_STORE_SAVE_AS_PKCS7)); default: throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); } }
public byte[] Export(X509ContentType contentType, string password) { #if !FEATURE_CORESYSTEM // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to export certificates to a memory store. // StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); #endif Cryptography.SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportToMemoryStore(this); byte[] result = ExportCertificatesToBlob(safeCertStoreHandle, contentType, password); safeCertStoreHandle.Dispose(); return result; }
public static void TestFileContentType(string fileName, X509ContentType contentType) { string fullPath = Path.Combine("TestData", fileName); X509ContentType fileType = X509Certificate2.GetCertContentType(fullPath); Assert.Equal(contentType, fileType); }
[System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] Export(X509ContentType contentType, SecureString password) { return ExportHelper(contentType, password); }
public override byte[] Export (X509ContentType contentType, string password) { ThrowIfContextInvalid (); switch (contentType) { case X509ContentType.Cert: return GetRawCertData (); case X509ContentType.Pfx: // this includes Pkcs12 return ExportPkcs12 (password); case X509ContentType.SerializedCert: // TODO throw new NotSupportedException (); default: string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType); throw new CryptographicException (msg); } }
public abstract byte[] Export(X509ContentType contentType, SafePasswordHandle password);
public static bool CheckCertificateIsExportable(X509Certificate2 certForCheck, X509ContentType certType) { try { certForCheck.Export(certType); return(true); } catch { return(false); } }
public static void TestBlobContentType(byte[] blob, X509ContentType contentType) { X509ContentType blobType = X509Certificate2.GetCertContentType(blob); Assert.Equal(contentType, blobType); }
public virtual byte[] Export(X509ContentType contentType, string password) { byte[] pwd = (password == null) ? null : Encoding.UTF8.GetBytes(password); return(Export(contentType, pwd)); }
internal byte[] Export (X509ContentType contentType, byte[] password) { try { X509Helper.ThrowIfContextInvalid (impl); return impl.Export (contentType, password); } finally { // protect password if (password != null) Array.Clear (password, 0, password.Length); } }
public virtual byte[] Export(X509ContentType contentType, SecureString password) { byte[] pwd = (password == null) ? null : password.GetBuffer(); return(Export(contentType, pwd)); }
public virtual byte[] Export(X509ContentType contentType);
/// <summary> /// Returns serialized certificate - Base64 encoded based on the content type /// </summary> /// <param name="cert">The certificate provided</param> /// <param name="contentType">Cert content type</param> /// <returns>The serialized cert value in string</returns> public static string SerializeCert(X509Certificate2 cert, X509ContentType contentType) { return(Convert.ToBase64String(cert.Export(contentType))); }
public virtual byte[] Export(X509ContentType contentType, string password) { if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12)) throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (IStorePal storePal = StorePal.FromCertificate(Pal)) { return storePal.Export(contentType, password); } }
public virtual byte[] Export(X509ContentType contentType) { }
public virtual byte[] Export(X509ContentType contentType, string password) { }
private static void TestExportStore(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(blob); int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); using (X509Certificate2 first = cs[0]) { Assert.NotSame(msCer, first); Assert.Equal(msCer, first); } using (X509Certificate2 second = cs[1]) { Assert.NotSame(pfxCer, second); Assert.Equal(pfxCer, second); } } }
public virtual byte[] Export(X509ContentType contentType, System.Security.SecureString password) { }
public virtual byte[] Export (X509ContentType contentType, string password) { byte[] pwd = (password == null) ? null : Encoding.UTF8.GetBytes (password); return Export (contentType, pwd); }
public static void TestContentType() { X509ContentType ct = X509Certificate2.GetCertContentType(TestData.MsCertificate); Assert.Equal(X509ContentType.Cert, ct); }
internal byte[] Export (X509ContentType contentType, byte[] password) { if (x509 == null) throw new CryptographicException (Locale.GetText ("Certificate instance is empty.")); try { switch (contentType) { case X509ContentType.Cert: return x509.RawData; case X509ContentType.Pfx: // this includes Pkcs12 // TODO throw new NotSupportedException (); case X509ContentType.SerializedCert: // TODO throw new NotSupportedException (); default: string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType); throw new CryptographicException (msg); } } finally { // protect password if (password != null) Array.Clear (password, 0, password.Length); } }
public static byte[] Export(X509CertificateImpl impl, X509ContentType contentType, byte[] password) { ThrowIfContextInvalid(impl); return(impl.Export(contentType, password)); }
public bool NegTest(int id, string msg, X509ContentType x509ConType, TestDelegate d) { bool retVal = true; X509Certificate cer; byte[] bytes; TestLibrary.TestFramework.BeginScenario("NegTest"+id+": "+msg+" = " + x509ConType); try { cer = new X509Certificate(c_CERTFILE); bytes = d(cer, x509ConType); TestLibrary.TestFramework.LogError("002", "Exception should have been thrown."); TestLibrary.TestFramework.LogInformation(""); retVal = false; } catch (CryptographicException e) { // expected // ensure that the message does NOT contain "Unknown error" if (e.Message.ToLower().Contains("unknown error")) { TestLibrary.TestFramework.LogError("003", "Unexpected exception message (should not be unkown): " + e); TestLibrary.TestFramework.LogInformation(""); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(""); retVal = false; } return retVal; }
public byte[]? Export(X509ContentType contentType) { return(Export(contentType, password: null)); }
public static X509ContentType GetCertContentType(byte[] rawData) { if ((rawData == null) || (rawData.Length == 0)) { throw new ArgumentException("rawData"); } X509ContentType type = X509ContentType.Unknown; try { ASN1 data = new ASN1(rawData); if (data.Tag != 0x30) { string msg = Locale.GetText("Unable to decode certificate."); throw new CryptographicException(msg); } if (data.Count == 0) { return(type); } if (data.Count == 3) { switch (data [0].Tag) { case 0x30: // SEQUENCE / SEQUENCE / BITSTRING if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03)) { type = X509ContentType.Cert; } break; #if !MOONLIGHT case 0x02: // INTEGER / SEQUENCE / SEQUENCE if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30)) { type = X509ContentType.Pkcs12; } // note: Pfx == Pkcs12 break; #endif } } #if !MOONLIGHT // check for PKCS#7 (count unknown but greater than 0) // SEQUENCE / OID (signedData) if ((data [0].Tag == 0x06) && data [0].CompareValue(signedData)) { type = X509ContentType.Pkcs7; } #endif } catch (Exception e) { string msg = Locale.GetText("Unable to decode certificate."); throw new CryptographicException(msg, e); } return(type); }
public override byte[] Export(X509ContentType contentType, string password) { return(Impl.Export(contentType, password)); }
public byte[] Export(X509ContentType contentType) { return Export(contentType, null); }
public FileCertificateSaver(string fileName, X509ContentType format, string password) { _fileName = fileName.ArgNotNull(nameof(fileName)); _format = format; _password = password.ArgNotNull(nameof(password)); }
private unsafe static byte[] ExportCertificatesToBlob(Cryptography.SafeCertStoreHandle safeCertStoreHandle, X509ContentType contentType, string password) { Cryptography.SafeCertContextHandle safeCertContextHandle = Cryptography.SafeCertContextHandle.InvalidHandle; uint dwSaveAs = CAPI.CERT_STORE_SAVE_AS_PKCS7; byte[] pbBlob = null; CAPI.CRYPTOAPI_BLOB DataBlob = new CAPI.CRYPTOAPI_BLOB(); SafeLocalAllocHandle pbEncoded = SafeLocalAllocHandle.InvalidHandle; switch(contentType) { case X509ContentType.Cert: safeCertContextHandle = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, safeCertContextHandle); if (safeCertContextHandle != null && !safeCertContextHandle.IsInvalid) { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); pbBlob = new byte[pCertContext.cbCertEncoded]; Marshal.Copy(pCertContext.pbCertEncoded, pbBlob, 0, pbBlob.Length); } break; case X509ContentType.SerializedCert: safeCertContextHandle = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, safeCertContextHandle); uint cbEncoded = 0; if (safeCertContextHandle != null && !safeCertContextHandle.IsInvalid) { if (!CAPI.CertSerializeCertificateStoreElement(safeCertContextHandle, 0, pbEncoded, new IntPtr(&cbEncoded))) throw new CryptographicException(Marshal.GetLastWin32Error()); pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbEncoded)); if (!CAPI.CertSerializeCertificateStoreElement(safeCertContextHandle, 0, pbEncoded, new IntPtr(&cbEncoded))) throw new CryptographicException(Marshal.GetLastWin32Error()); pbBlob = new byte[cbEncoded]; Marshal.Copy(pbEncoded.DangerousGetHandle(), pbBlob, 0, pbBlob.Length); } break; case X509ContentType.Pkcs12: if (!CAPI.PFXExportCertStore(safeCertStoreHandle, new IntPtr(&DataBlob), password, CAPI.EXPORT_PRIVATE_KEYS | CAPI.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(DataBlob.cbData)); DataBlob.pbData = pbEncoded.DangerousGetHandle(); if (!CAPI.PFXExportCertStore(safeCertStoreHandle, new IntPtr(&DataBlob), password, CAPI.EXPORT_PRIVATE_KEYS | CAPI.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbBlob = new byte[DataBlob.cbData]; Marshal.Copy(DataBlob.pbData, pbBlob, 0, pbBlob.Length); break; case X509ContentType.SerializedStore: // falling through case X509ContentType.Pkcs7: if (contentType == X509ContentType.SerializedStore) dwSaveAs = CAPI.CERT_STORE_SAVE_AS_STORE; // determine the required length if (!CAPI.CertSaveStore(safeCertStoreHandle, CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, dwSaveAs, CAPI.CERT_STORE_SAVE_TO_MEMORY, new IntPtr(&DataBlob), 0)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(DataBlob.cbData)); DataBlob.pbData = pbEncoded.DangerousGetHandle(); // now save the store to a memory blob if (!CAPI.CertSaveStore(safeCertStoreHandle, CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, dwSaveAs, CAPI.CERT_STORE_SAVE_TO_MEMORY, new IntPtr(&DataBlob), 0)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbBlob = new byte[DataBlob.cbData]; Marshal.Copy(DataBlob.pbData, pbBlob, 0, pbBlob.Length); break; default: throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidContentType)); } pbEncoded.Dispose(); safeCertContextHandle.Dispose(); return pbBlob; }
public virtual byte[] Export(X509ContentType contentType) { return(Export(contentType, (string)null)); }
public virtual byte[] Export(X509ContentType contentType) { return ExportHelper(contentType, null); }
/// <summary> /// Returns serialized certificate - Base64 encoded based on the content type /// </summary> /// <param name="cert">The certificate provided</param> /// <param name="contentType">Cert content type</param> /// <returns>The serialized cert value in string</returns> public static string SerializeCert(X509Certificate2 cert, X509ContentType contentType) { return Convert.ToBase64String(cert.Export(contentType)); }
[System.Security.SecurityCritical] // auto-generated private byte[] ExportHelper (X509ContentType contentType, object password) { switch(contentType) { case X509ContentType.Cert: break; #if FEATURE_CORECLR case (X509ContentType)0x02 /* X509ContentType.SerializedCert */: case (X509ContentType)0x03 /* X509ContentType.Pkcs12 */: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"), new NotSupportedException()); #else // FEATURE_CORECLR case X509ContentType.SerializedCert: break; #if !FEATURE_PAL case X509ContentType.Pkcs12: KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export); kp.Demand(); break; #endif // !FEATURE_PAL #endif // FEATURE_CORECLR else default: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType")); } #if !FEATURE_CORECLR IntPtr szPassword = IntPtr.Zero; byte[] encodedRawData = null; SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportCertToMemoryStore(this); RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); encodedRawData = X509Utils._ExportCertificatesToBlob(safeCertStoreHandle, contentType, szPassword); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); safeCertStoreHandle.Dispose(); } if (encodedRawData == null) throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_ExportFailed")); return encodedRawData; #else // !FEATURE_CORECLR return RawData; #endif // !FEATURE_CORECLR }
public static ICertificatePal FromBlob( byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(password != null); X509ContentType contentType = X509Certificate2.GetCertContentType(rawData); if (contentType == X509ContentType.Pkcs7) { // In single mode for a PKCS#7 signed or signed-and-enveloped file we're supposed to return // the certificate which signed the PKCS#7 file. // // X509Certificate2Collection::Export(X509ContentType.Pkcs7) claims to be a signed PKCS#7, // but doesn't emit a signature block. So this is hard to test. // // TODO(2910): Figure out how to extract the signing certificate, when it's present. throw new CryptographicException(SR.Cryptography_X509_PKCS7_NoSigner); } bool exportable = true; SafeKeychainHandle keychain; if (contentType == X509ContentType.Pkcs12) { if ((keyStorageFlags & X509KeyStorageFlags.EphemeralKeySet) == X509KeyStorageFlags.EphemeralKeySet) { throw new PlatformNotSupportedException(SR.Cryptography_X509_NoEphemeralPfx); } exportable = (keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable; bool persist = (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet; keychain = persist ? Interop.AppleCrypto.SecKeychainCopyDefault() : Interop.AppleCrypto.CreateTemporaryKeychain(); } else { keychain = SafeTemporaryKeychainHandle.InvalidHandle; password = SafePasswordHandle.InvalidHandle; } using (keychain) { SafeSecIdentityHandle identityHandle; SafeSecCertificateHandle certHandle = Interop.AppleCrypto.X509ImportCertificate( rawData, contentType, password, keychain, exportable, out identityHandle); if (identityHandle.IsInvalid) { identityHandle.Dispose(); return(new AppleCertificatePal(certHandle)); } if (contentType != X509ContentType.Pkcs12) { Debug.Fail("Non-PKCS12 import produced an identity handle"); identityHandle.Dispose(); certHandle.Dispose(); throw new CryptographicException(); } Debug.Assert(certHandle.IsInvalid); certHandle.Dispose(); return(new AppleCertificatePal(identityHandle)); } }