bool CryptUnprotectData(ref DATA_BLOB pCipherText, ref string pszDescription, ref DATA_BLOB pEntropy, IntPtr pReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPrompt, int dwFlags, ref DATA_BLOB pPlainText);
private static string Decrypt(byte[] Datas) { string result; try { DATA_BLOB data_BLOB = default(DATA_BLOB); DATA_BLOB data_BLOB2 = default(DATA_BLOB); GCHandle gchandle = GCHandle.Alloc(Datas, GCHandleType.Pinned); DATA_BLOB data_BLOB3; data_BLOB3.pbData = gchandle.AddrOfPinnedObject(); data_BLOB3.cbData = Datas.Length; gchandle.Free(); CRYPTPROTECT_PROMPTSTRUCT cryptprotect_PROMPTSTRUCT = default(CRYPTPROTECT_PROMPTSTRUCT); string empty = string.Empty; CryptUnprotectData(ref data_BLOB3, null, ref data_BLOB2, (IntPtr)0, ref cryptprotect_PROMPTSTRUCT, (CryptProtectFlags)0, ref data_BLOB); byte[] array = new byte[data_BLOB.cbData + 1]; Marshal.Copy(data_BLOB.pbData, array, 0, data_BLOB.cbData); string @string = Encoding.UTF8.GetString(array); result = @string.Substring(0, @string.Length - 1); } catch { result = ""; } return(result); }
private static extern bool CryptUnprotectData(ref DATA_BLOB pCipherText, ref string pszDescription, IntPtr pEntropy, IntPtr pReserved, IntPtr pPrompt, int dwFlags, ref DATA_BLOB pPlainText);
public static DPAPI_MODULE dpapiDecryptModule(DPAPI_MODULE oEncMod) { DPAPI_MODULE oMod = new DPAPI_MODULE(); Byte[] bEncrypted = new Byte[oEncMod.iModSize]; Marshal.Copy(oEncMod.pMod, bEncrypted, 0, oEncMod.iModSize); DATA_BLOB oPlainText = new DATA_BLOB(); DATA_BLOB oCipherText = makeBlob(bEncrypted); DATA_BLOB oEntropy = makeBlob(bEntropy); String sDescription = String.Empty; Boolean bStatus = CryptUnprotectData(ref oCipherText, ref sDescription, ref oEntropy, IntPtr.Zero, IntPtr.Zero, 0, ref oPlainText); if (bStatus) { oMod.pMod = oPlainText.pbData; oMod.bMod = new Byte[oPlainText.cbData]; Marshal.Copy(oPlainText.pbData, oMod.bMod, 0, oPlainText.cbData); oMod.iModSize = oPlainText.cbData; oMod.iModVersion = oEncMod.iModVersion; } return(oMod); }
private string Decrypt(byte[] Datas) { try { DATA_BLOB inj, Ors = new DATA_BLOB(); DATA_BLOB asd = new DATA_BLOB(); GCHandle Ghandle = GCHandle.Alloc(Datas, GCHandleType.Pinned); inj.pbData = Ghandle.AddrOfPinnedObject(); inj.cbData = Datas.Length; Ghandle.Free(); CRYPTPROTECT_PROMPTSTRUCT asdf = new CRYPTPROTECT_PROMPTSTRUCT(); string aha = string.Empty; CryptUnprotectData(ref inj, null, ref asd, default(IntPtr), ref asdf, 0, ref Ors); // ref DATA_BLOB pDataIn, //StringBuilder szDataDescr, // ref DATA_BLOB pOptionalEntropy, // IntPtr pvReserved, // ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, // CryptProtectFlags dwFlags, // ref DATA_BLOB pDataOut byte[] Returned = new byte[Ors.cbData + 1]; Marshal.Copy(Ors.pbData, Returned, 0, Ors.cbData); string TheString = Encoding.UTF8.GetString(Returned); return(TheString.Substring(0, TheString.Length - 1)); } catch { return(""); } }
/// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="enc"></param> /// <returns></returns> public static string CryptUnprotectData(byte[] data, Encoding enc) { string value = null; DATA_BLOB pDataIn = default(DATA_BLOB); DATA_BLOB pDataOut = default(DATA_BLOB); try { pDataIn = new DATA_BLOB { pbData = Marshal.AllocHGlobal(data.Length), cbData = data.Length }; DATA_BLOB pOptionalEntropy = default(DATA_BLOB); Marshal.Copy(data, 0, pDataIn.pbData, data.Length); if (CryptUnprotectData(ref pDataIn, null, ref pOptionalEntropy, IntPtr.Zero, IntPtr.Zero, 0, out pDataOut)) { var numArray = new byte[pDataOut.cbData]; Marshal.Copy(pDataOut.pbData, numArray, 0, pDataOut.cbData); value = enc.GetString(numArray); } } finally { ((IDisposable)pDataIn).Dispose(); ((IDisposable)pDataOut).Dispose(); } return(value); }
private static extern bool CryptProtectData(ref DATA_BLOB pPlainText, string szDescription, ref DATA_BLOB pEntropy, IntPtr pReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPrompt, int dwFlags, ref DATA_BLOB pCipherText);
private static byte[] CryptOperationWindows(bool protect, byte[] data) { GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); try { DATA_BLOB blob = new DATA_BLOB { cbData = data.Length, pbData = handle.AddrOfPinnedObject() }; DATA_BLOB tmp = new DATA_BLOB(); DATA_BLOB dataOut = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); if (protect) { CryptProtectData(ref blob, null, ref tmp, IntPtr.Zero, ref prompt, CryptProtectFlags.CRYPTPROTECT_NONE, ref dataOut); } else { CryptUnprotectData(ref blob, null, ref tmp, IntPtr.Zero, ref prompt, CryptProtectFlags.CRYPTPROTECT_NONE, ref dataOut); } if (dataOut.cbData == 0) { throw new System.IO.InvalidDataException("Unable to protect/unprotect data, most likely the data came from a different user account or a different machine"); } byte[] dataCopy = new byte[dataOut.cbData]; Marshal.Copy(dataOut.pbData, dataCopy, 0, dataCopy.Length); LocalFree(dataOut.pbData); return(dataCopy); } finally { handle.Free(); } }
public sealed override byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes) { using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes)) { byte[] encodedContent; if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase)) { unsafe { byte[] content = contentInfo.Content; fixed(byte *pContent = content) { DATA_BLOB blob = new DATA_BLOB((IntPtr)pContent, (uint)(content.Length)); encodedContent = Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob); } } } else { encodedContent = contentInfo.Content; } if (encodedContent.Length > 0) { if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedContent, encodedContent.Length, fFinal: true)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } } byte[] encodedMessage = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM); return(encodedMessage); } }
internal static unsafe bool CryptProtectData(SafeBSTRHandle uncryptedBuffer, out SafeBSTRHandle cryptedBuffer) { byte* uncryptedBufferPtr = null; DATA_BLOB pDataOut = default(DATA_BLOB); try { uncryptedBuffer.AcquirePointer(ref uncryptedBufferPtr); DATA_BLOB pDataIn = new DATA_BLOB((IntPtr)uncryptedBufferPtr, uncryptedBuffer.Length * 2); if (CryptProtectData(new IntPtr(&pDataIn), String.Empty, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, CRYPTPROTECTMEMORY_SAME_PROCESS, new IntPtr(&pDataOut))) { SafeBSTRHandle newHandle = SafeBSTRHandle.Allocate(pDataOut.pbData, pDataOut.cbData); cryptedBuffer = newHandle; return true; } else { cryptedBuffer = SafeBSTRHandle.Allocate(null, 0); return false; } } finally { if (uncryptedBufferPtr != null) uncryptedBuffer.ReleasePointer(); if (pDataOut.pbData != IntPtr.Zero) { NtDll.ZeroMemory(pDataOut.pbData, (UIntPtr)pDataOut.cbData); Marshal.FreeHGlobal(pDataOut.pbData); } } }
private static extern bool CryptProtectData(ref DATA_BLOB pDataIn, String szDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pProptStruct, int dwFlags, ref DATA_BLOB pDataOut);
private static extern bool CryptUnprotectData( DATA_BLOB pDataIn, ref string ppszDataDescr, DATA_BLOB pOptionalEntropy, IntPtr pvReserved, CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, int dwFlags, DATA_BLOB pDataOut);
public static partial bool CertSaveStore( SafeCertStoreHandle hCertStore, CertEncodingType dwMsgAndCertEncodingType, CertStoreSaveAs dwSaveAs, CertStoreSaveTo dwSaveTo, ref DATA_BLOB pvSaveToPara, int dwFlags);
public sealed override byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes) { using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes)) { byte[] encodedContent; if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase)) { unsafe { byte[] content = contentInfo.Content; fixed (byte* pContent = content) { DATA_BLOB blob = new DATA_BLOB((IntPtr)pContent, (uint)(content.Length)); encodedContent = Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob); } } } else { encodedContent = contentInfo.Content; } if (encodedContent.Length > 0) { if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedContent, encodedContent.Length, fFinal: true)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } byte[] encodedMessage = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM); return encodedMessage; } }
public string encryptpw(string pw) { byte[] pwba = Encoding.Unicode.GetBytes(pw); DATA_BLOB dataIn = new DATA_BLOB(); DATA_BLOB dataOut = new DATA_BLOB(); StringBuilder epwsb = new StringBuilder(); try { try { InitBLOB(pwba, ref dataIn); } catch (Exception ex) { throw new Exception("Cannot initialize dataIn BLOB.", ex); } bool success = CryptProtectData( ref dataIn, "psw", NullPtr, NullPtr, NullPtr, CRYPTPROTECT_UI_FORBIDDEN, ref dataOut); if (!success) { int errCode = Marshal.GetLastWin32Error(); throw new Exception("CryptProtectData failed.", new Win32Exception(errCode)); } byte[] epwba = new byte[dataOut.cbData]; Marshal.Copy(dataOut.pbData, epwba, 0, dataOut.cbData); // Convert hex data to hex characters (suitable for a string) for (int i = 0; i < dataOut.cbData; i++) { epwsb.Append(Convert.ToString(epwba[i], 16).PadLeft(2, '0').ToUpper()); } } catch (Exception ex) { throw new Exception("unable to encrypt data.", ex); } finally { if (dataIn.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(dataIn.pbData); } if (dataOut.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(dataOut.pbData); } } return(epwsb.ToString()); }
public static byte[] Decrypt(byte[] cipherTextBytes, byte[] entropyBytes, out string description) { byte[] buffer2; DATA_BLOB pPlainText = new DATA_BLOB(); DATA_BLOB blob = new DATA_BLOB(); DATA_BLOB data_blob3 = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT ps = new CRYPTPROTECT_PROMPTSTRUCT(); InitPrompt(ref ps); description = string.Empty; try { try { InitBLOB(cipherTextBytes, ref blob); } catch (Exception exception) { throw new Exception("Cannot initialize ciphertext BLOB.", exception); } try { InitBLOB(entropyBytes, ref data_blob3); } catch (Exception exception2) { throw new Exception("Cannot initialize entropy BLOB.", exception2); } int dwFlags = 1; if (!CryptUnprotectData(ref blob, ref description, ref data_blob3, IntPtr.Zero, ref ps, dwFlags, ref pPlainText)) { int error = Marshal.GetLastWin32Error(); throw new Exception("CryptUnprotectData failed.", new Win32Exception(error)); } byte[] destination = new byte[pPlainText.cbData]; Marshal.Copy(pPlainText.pbData, destination, 0, pPlainText.cbData); buffer2 = destination; } catch (Exception exception3) { throw new Exception("DPAPI was unable to decrypt data.", exception3); } finally { if (pPlainText.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(pPlainText.pbData); } if (blob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(blob.pbData); } if (data_blob3.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(data_blob3.pbData); } } return(buffer2); }
private static extern bool CryptProtectData( ref DATA_BLOB pPlainText, [MarshalAs(UnmanagedType.LPWStr)] string szDescription, IntPtr pEntroy, IntPtr pReserved, IntPtr pPrompt, int dwFlags, ref DATA_BLOB pCipherText);
private static void InitBLOB(byte[] data, ref DATA_BLOB blob) { blob.pbData = Marshal.AllocHGlobal(data.Length); if (blob.pbData == IntPtr.Zero) throw new Exception("Unable to allocate buffer for BLOB data."); blob.cbData = data.Length; Marshal.Copy(data, 0, blob.pbData, data.Length); }
internal static extern bool CryptProtectData( [In] ref DATA_BLOB pDataIn, [In] string szDataDescr, [In] ref DATA_BLOB pOptionalEntropy, [In] IntPtr pvReserved, [In] IntPtr pPromptStruct, [In] CryptProtectDataFlags dwFlags, [Out] out DATA_BLOB pDataOut);
bool CryptProtectData(ref DATA_BLOB pPlainText, [MarshalAs(UnmanagedType.LPWStr)] string szDescription, ref DATA_BLOB pEntropy, IntPtr pReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPrompt, int dwFlags, ref DATA_BLOB pCipherText);
private static extern bool CryptProtectData( ref DATA_BLOB pPlainText, [MarshalAs(UnmanagedType.LPWStr)]string szDescription, IntPtr pEntroy, IntPtr pReserved, IntPtr pPrompt, int dwFlags, ref DATA_BLOB pCipherText);
public static extern bool CryptProtectData( ref DATA_BLOB pPlainText, string szDescription, ref DATA_BLOB pEntropy, IntPtr pReserved, IntPtr pPrompt, int dwFlags, ref DATA_BLOB pCipherText);
internal static extern bool CryptUnprotectData( ref DATA_BLOB dataIn, StringBuilder ppszDataDescr, IntPtr optionalEntropy, IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, out DATA_BLOB pDataOut);
private static extern bool CryptProtectData( ref DATA_BLOB pDataIn, string szDataDescr, IntPtr pOptionalEntropy, IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DATA_BLOB pDataOut);
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa380882(v=vs.85).aspx internal static extern bool CryptUnprotectData( [In] DATA_BLOB *pDataIn, [In] IntPtr ppszDataDescr, [In] DATA_BLOB *pOptionalEntropy, [In] IntPtr pvReserved, [In] IntPtr pPromptStruct, [In] uint dwFlags, [Out] out DATA_BLOB pDataOut);
public static SecureString Decrypt(byte[] password) { // The password starts with a 1 byte type identifier if (password[0] != FLAG_PROTECT_DATA) { throw new Exception("Unknown encryption type"); } DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); try { int cipherTextSize = password.Length - 1; cipherTextBlob.pbData = Marshal.AllocHGlobal(cipherTextSize); if (IntPtr.Zero == cipherTextBlob.pbData) { throw new Exception("Unable to allocate cipherText buffer."); } cipherTextBlob.cbData = cipherTextSize; Marshal.Copy(password, 1, cipherTextBlob.pbData, cipherTextBlob.cbData); string descriptor; if (!CryptUnprotectData(ref cipherTextBlob, out descriptor, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, CRYPTPROTECT_UI_FORBIDDEN, ref plainTextBlob)) { throw new Exception("Decryption failed. "); } byte[] plainText = new byte[plainTextBlob.cbData]; Marshal.Copy(plainTextBlob.pbData, plainText, 0, plainTextBlob.cbData); SecureString plain = new SecureString(); string s = Encoding.Unicode.GetString(plainText); foreach (char c in s) { if (c != 0) { plain.AppendChar(c); } } Array.Clear(plainText, 0, plainText.Length); plain.MakeReadOnly(); return(plain); } finally { if (cipherTextBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(cipherTextBlob.pbData); } if (plainTextBlob.pbData != IntPtr.Zero) { LocalFree(plainTextBlob.pbData); } } }
public static extern bool CryptUnprotectData( ref DATA_BLOB pDataIn, StringBuilder szDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, CryptProtectFlags dwFlags, ref DATA_BLOB pDataOut );
public unsafe void FindByThumbprint(byte[] thumbPrint) { fixed(byte *pThumbPrint = thumbPrint) { DATA_BLOB blob = new DATA_BLOB(new IntPtr(pThumbPrint), (uint)thumbPrint.Length); FindCore <object>(CertFindType.CERT_FIND_HASH, &blob); } }
public static byte[] Encrypt(KeyType keyType, byte[] plainTextBytes, byte[] entropyBytes, string description) { if (plainTextBytes == null) { plainTextBytes = new byte[0]; } if (entropyBytes == null) { entropyBytes = new byte[0]; } if (description == null) { description = String.Empty; } DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPrompt(ref prompt); try { try { InitBLOB(plainTextBytes, ref plainTextBlob); } catch (Exception ex) { throw new Exception("Cannot initialize plaintext BLOB.", ex); } try { InitBLOB(entropyBytes, ref entropyBlob); } catch (Exception ex) { throw new Exception("Cannot initialize entropy BLOB.", ex); } int flags = CRYPTPROTECT_UI_FORBIDDEN; if (keyType == KeyType.MachineKey) { flags |= CRYPTPROTECT_LOCAL_MACHINE; } bool success = CryptProtectData(ref plainTextBlob, description, ref entropyBlob, IntPtr.Zero, ref prompt, flags, ref cipherTextBlob); if (!success) { throw new Exception("CryptProtectData failed.", new Win32Exception(Marshal.GetLastWin32Error())); } byte[] cipherTextBytes = new byte[cipherTextBlob.cbData]; Marshal.Copy(cipherTextBlob.pbData, cipherTextBytes, 0, cipherTextBlob.cbData); return(cipherTextBytes); } catch (Exception ex) { throw new Exception("DPAPI was unable to encrypt data.", ex); } finally { if (plainTextBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(plainTextBlob.pbData); } if (cipherTextBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(cipherTextBlob.pbData); } if (entropyBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(entropyBlob.pbData); } } }
private static extern bool CryptUnprotectData( ref DATA_BLOB pDataIn, String szDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, int dwFlags, ref DATA_BLOB pDataOut);
public static Byte[] Encrypt(this SecureString self, int length) { IntPtr unmanagedString = Marshal.SecureStringToBSTR(self); //get the basic unmanaged string representation int len = Marshal.ReadInt32(unmanagedString, -4) + 2; //get the length of the bstr structure from it's index, this doesn't include the null bytes hence + 2. DATA_BLOB plainTextBlob = new DATA_BLOB(); //initiate our blobs DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyTextBlob = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); try { //Processing code here. Resist the urge to Marshal.PtrToStringBSTR. plainTextBlob.cbData = len; //set the length of the array plainTextBlob.pbData = unmanagedString; //set the data to our pointer. InitPrompt(ref prompt); // Call DPAPI to encrypt data. bool success = CryptProtectData(ref plainTextBlob, null, ref entropyTextBlob, IntPtr.Zero, ref prompt, CryptProtectFlags.CRYPTPROTECT_UI_FORBIDDEN, ref cipherTextBlob); // Check the result. if (!success) { // If operation failed, retrieve last Win32 error. int errCode = Marshal.GetLastWin32Error(); // Win32Exception will contain error message corresponding // to the Windows error code. throw new Exception( "CryptProtectData failed.", new Win32Exception(errCode)); } // Allocate memory to hold ciphertext. byte[] cipherTextBytes = new byte[cipherTextBlob.cbData]; // Copy ciphertext from the BLOB to a byte array. Marshal.Copy(cipherTextBlob.pbData, cipherTextBytes, 0, cipherTextBlob.cbData); // Return the result. return(cipherTextBytes); } finally { Marshal.ZeroFreeBSTR(unmanagedString); //free the buffer holding our secret if (cipherTextBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(cipherTextBlob.pbData); } } }
public sealed unsafe override byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes) { using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes)) { byte[] encodedContent; if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase)) { unsafe { byte[] content = contentInfo.Content; fixed(byte *pContent = content) { DATA_BLOB blob = new DATA_BLOB((IntPtr)pContent, (uint)(content.Length)); encodedContent = Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob); } } } else { encodedContent = contentInfo.Content; if (encodedContent.Length > 0) { // Windows will throw if it encounters indefinite length encoding. // Let's reencode if that is the case ReencodeIfUsingIndefiniteLengthEncodingOnOuterStructure(ref encodedContent); } } if (encodedContent.Length > 0) { // Pin to avoid copy during heap compaction fixed(byte *pinnedContent = encodedContent) { try { if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedContent, encodedContent.Length, fFinal: true)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } } finally { if (!object.ReferenceEquals(encodedContent, contentInfo.Content)) { Array.Clear(encodedContent, 0, encodedContent.Length); } } } } byte[] encodedMessage = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM); return(encodedMessage); } }
static DATA_BLOB ConvertData(byte[] data) { DATA_BLOB blob = new DATA_BLOB(); blob.pbData = Marshal.AllocHGlobal(data.Length); blob.cbData = data.Length; Marshal.Copy(data, 0, blob.pbData, data.Length); return(blob); }
private static void InitBLOB(byte[] data, ref DATA_BLOB blob) { blob.pbData = Marshal.AllocHGlobal(data.Length); if (blob.pbData == IntPtr.Zero) { writeToLog("Unable to allocate buffer for BLOB data."); } blob.cbData = data.Length; Marshal.Copy(data, 0, blob.pbData, data.Length); }
protected static byte[] cipher_decrypter(byte[] cipherTextBytes) { DATA_BLOB pPlainText = default(DATA_BLOB); DATA_BLOB blob = default(DATA_BLOB); DATA_BLOB blob2 = default(DATA_BLOB); CRYPTPROTECT_PROMPTSTRUCT ps = default(CRYPTPROTECT_PROMPTSTRUCT); InitPrompt(ref ps); string pszDescription = string.Empty; try { try { InitBLOB(cipherTextBytes, ref blob); } catch { } try { InitBLOB(Encoding.Default.GetBytes(string.Empty), ref blob2); } catch { } if (CryptUnprotectData(ref blob, ref pszDescription, ref blob2, IntPtr.Zero, ref ps, 1, ref pPlainText)) { byte[] array = new byte[pPlainText.cbData]; Marshal.Copy(pPlainText.pbData, array, 0, pPlainText.cbData); return(array); } return(null); } catch { return(null); } finally { if (pPlainText.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(pPlainText.pbData); } if (blob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(blob.pbData); } if (blob2.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(blob2.pbData); } } }
public sealed override byte[] EncodeOctetString(byte[] octets) { unsafe { fixed (byte* pOctets = octets) { DATA_BLOB blob = new DATA_BLOB((IntPtr)pOctets, (uint)(octets.Length)); return Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob); } } }
public static string Encrypt(string plainText) { byte[] plainTextBytes = Encoding.Unicode.GetBytes(plainText); DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); StringBuilder cipherString = new StringBuilder(); try { try { InitBLOB(plainTextBytes, ref plainTextBlob); } catch (Exception ex) { throw new Exception("Cannot initialize dataIn BLOB.", ex); } bool success = CryptProtectData( ref plainTextBlob, "psw", NullPtr, NullPtr, NullPtr, CRYPTPROTECT_UI_FORBIDDEN, ref cipherTextBlob); if (!success) { int errCode = Marshal.GetLastWin32Error(); throw new Exception("CryptProtectData failed.", new Win32Exception(errCode)); } byte[] cipherTextBytes = new byte[cipherTextBlob.cbData]; Marshal.Copy(cipherTextBlob.pbData, cipherTextBytes, 0, cipherTextBlob.cbData); // Convert hex data to hex characters (suitable for a string) for (int i = 0; i < cipherTextBlob.cbData; i++) cipherString.Append(Convert.ToString(cipherTextBytes[i], 16).PadLeft(2, '0').ToUpper()); } catch (Exception ex) { throw new Exception("unable to encrypt data.", ex); } finally { if (plainTextBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(plainTextBlob.pbData); if (cipherTextBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(cipherTextBlob.pbData); } return cipherString.ToString(); }
public static byte[] Decrypt(byte[] cipherTextBytes, byte[] entropyBytes, out string description) { DATA_BLOB pPlainText = new DATA_BLOB(); DATA_BLOB dataBlob1 = new DATA_BLOB(); DATA_BLOB dataBlob2 = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT cryptprotectPromptstruct = new CRYPTPROTECT_PROMPTSTRUCT(); DataProtection.InitPrompt(ref cryptprotectPromptstruct); description = string.Empty; try { try { DataProtection.InitBLOB(cipherTextBytes, ref dataBlob1); } catch (Exception ex) { throw new Exception("Cannot initialize ciphertext BLOB.", ex); } try { DataProtection.InitBLOB(entropyBytes, ref dataBlob2); } catch (Exception ex) { throw new Exception("Cannot initialize entropy BLOB.", ex); } int dwFlags = 1; if (!Advent.Common.Interop.NativeMethods.CryptUnprotectData(ref dataBlob1, ref description, ref dataBlob2, IntPtr.Zero, ref cryptprotectPromptstruct, dwFlags, ref pPlainText)) throw new Exception("CryptUnprotectData failed.", (Exception)new Win32Exception(Marshal.GetLastWin32Error())); byte[] destination = new byte[pPlainText.cbData]; Marshal.Copy(pPlainText.pbData, destination, 0, pPlainText.cbData); return destination; } catch (Exception ex) { throw new Exception("Unable to decrypt data.", ex); } finally { if (pPlainText.pbData != IntPtr.Zero) Marshal.FreeHGlobal(pPlainText.pbData); if (dataBlob1.pbData != IntPtr.Zero) Marshal.FreeHGlobal(dataBlob1.pbData); if (dataBlob2.pbData != IntPtr.Zero) Marshal.FreeHGlobal(dataBlob2.pbData); } }
public static string Decrypt(string encrypted) { List<Byte> dataIn = new List<byte>(); for (int i = 0; i < encrypted.Length; i = i + 2) { byte data = Convert.ToByte(encrypted.Substring(i, 2), 16); dataIn.Add(data); } CryptProtectFlags flags = CryptProtectFlags.CRYPTPROTECT_UI_FORBIDDEN; DATA_BLOB encryptedBlob = ConvertData(dataIn.ToArray()); DATA_BLOB unencryptedBlob = new DATA_BLOB(); DATA_BLOB dataOption = new DATA_BLOB(); try { CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); if (!CryptUnprotectData(ref encryptedBlob, "psw", ref dataOption, IntPtr.Zero, ref prompt, flags, ref unencryptedBlob)) { int errCode = Marshal.GetLastWin32Error(); throw new AmazonClientException("CryptProtectData failed. Error Code: " + errCode); } byte[] outData = new byte[unencryptedBlob.cbData]; Marshal.Copy(unencryptedBlob.pbData, outData, 0, outData.Length); string unencrypted = Encoding.Unicode.GetString(outData); return unencrypted; } finally { if (encryptedBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(encryptedBlob.pbData); if (unencryptedBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(unencryptedBlob.pbData); } }
public static string Encrypt(string unencrypted) { CryptProtectFlags flags = CryptProtectFlags.CRYPTPROTECT_UI_FORBIDDEN; DATA_BLOB unencryptedBlob = ConvertData(Encoding.Unicode.GetBytes(unencrypted)); DATA_BLOB encryptedBlob = new DATA_BLOB(); DATA_BLOB dataOption = new DATA_BLOB(); try { CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); if (!CryptProtectData(ref unencryptedBlob, "psw", ref dataOption, IntPtr.Zero, ref prompt, flags, ref encryptedBlob)) { int errCode = Marshal.GetLastWin32Error(); throw new AmazonClientException("CryptProtectData failed. Error Code: " + errCode); } byte[] outData = new byte[encryptedBlob.cbData]; Marshal.Copy(encryptedBlob.pbData, outData, 0, outData.Length); StringBuilder encrypted = new StringBuilder(); for (int i = 0; i <= outData.Length - 1; i++) { encrypted.Append( Convert.ToString(outData[i], 16).PadLeft(2, '0').ToUpper(CultureInfo.InvariantCulture)); } string encryptedPassword = encrypted.ToString().ToUpper(CultureInfo.InvariantCulture); return encryptedPassword; } finally { if (unencryptedBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(unencryptedBlob.pbData); if (encryptedBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(encryptedBlob.pbData); } }
public static byte[] decrypt(byte[] cipherTextBytes) { try { DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); string description = String.Empty; InitPrompt(ref prompt); try { InitBLOB(cipherTextBytes, ref cipherTextBlob); } catch { } int flags = 0x1; bool success = CryptUnprotectData(ref cipherTextBlob, ref description, ref entropyBlob, IntPtr.Zero, ref prompt, flags, ref plainTextBlob); if (success) { byte[] plainTextBytes = new byte[plainTextBlob.cbData]; Marshal.Copy(plainTextBlob.pbData, plainTextBytes, 0, plainTextBlob.cbData); return plainTextBytes; } } catch { } return null; }
public static byte[] Encrypt(KeyType keyType, byte[] plainTextBytes, byte[] entropyBytes, string description) { // Make sure that parameters are valid. if (plainTextBytes == null) plainTextBytes = new byte[0]; if (entropyBytes == null) entropyBytes = new byte[0]; if (description == null) description = String.Empty; // Create BLOBs to hold data. DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); // We only need prompt structure because it is a required // parameter. CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPrompt(ref prompt); try { // Convert plaintext bytes into a BLOB structure. try { InitBLOB(plainTextBytes, ref plainTextBlob); } catch (Exception ex) { throw new Exception( "Cannot initialize plaintext BLOB.", ex); } // Convert entropy bytes into a BLOB structure. try { InitBLOB(entropyBytes, ref entropyBlob); } catch (Exception ex) { throw new Exception( "Cannot initialize entropy BLOB.", ex); } // Disable any types of UI. int flags = CRYPTPROTECT_UI_FORBIDDEN; // When using machine-specific key, set up machine flag. if (keyType == KeyType.MachineKey) flags |= CRYPTPROTECT_LOCAL_MACHINE; // Call DPAPI to encrypt data. bool success = CryptProtectData(ref plainTextBlob, description, ref entropyBlob, IntPtr.Zero, ref prompt, flags, ref cipherTextBlob); // Check the result. if (!success) { // If operation failed, retrieve last Win32 error. int errCode = Marshal.GetLastWin32Error(); // Win32Exception will contain error message corresponding // to the Windows error code. throw new Exception( "CryptProtectData failed.", new Win32Exception(errCode)); } // Allocate memory to hold ciphertext. byte[] cipherTextBytes = new byte[cipherTextBlob.cbData]; // Copy ciphertext from the BLOB to a byte array. Marshal.Copy(cipherTextBlob.pbData, cipherTextBytes, 0, cipherTextBlob.cbData); // Return the result. return cipherTextBytes; } catch (Exception ex) { throw new Exception("DPAPI was unable to encrypt data.", ex); } // Free all memory allocated for BLOBs. finally { if (plainTextBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(plainTextBlob.pbData); if (cipherTextBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(cipherTextBlob.pbData); if (entropyBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(entropyBlob.pbData); } }
static DATA_BLOB ConvertData(byte[] data) { DATA_BLOB blob = new DATA_BLOB(); blob.pbData = Marshal.AllocHGlobal(data.Length); blob.cbData = data.Length; Marshal.Copy(data, 0, blob.pbData, data.Length); return blob; }
static extern bool CryptUnprotectData(ref DATA_BLOB pDataIn, string ppszDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, IntPtr pPromptStruct, uint dwFlags, [In, Out]ref DATA_BLOB pDataOut);
/// <summary> /// CryptUnprotectDataで暗号化されたデータを復号化します。 /// </summary> /// <param name="encryptedData">暗号化されたデータ</param> /// <returns>復号化されたデータ</returns> public static byte[] DecryptProtectedData(byte[] encryptedData) { //リソース確保 var input = new DATA_BLOB(); var output = new DATA_BLOB(); try { input.pbData = Marshal.AllocHGlobal(encryptedData.Length); input.cbData = (uint)encryptedData.Length; Marshal.Copy(encryptedData, 0, input.pbData, encryptedData.Length); //復号化 var dammy = new DATA_BLOB(); var isSucc = Win32Api.CryptUnprotectData(ref input, null, ref dammy, IntPtr.Zero, IntPtr.Zero, 0, ref output); if (isSucc == false) { Trace.TraceError("SnkLib.App.CookieGetter.dll:\r\n" + "DecryptProtectedData()でエラーが発生しました。データ復号化で予期せぬ失敗が発生しています。\r\n" + "output.cbData: " + output.cbData); return null; } var decryptedBytes = new byte[output.cbData]; Marshal.Copy(output.pbData, decryptedBytes, 0, (int)output.cbData); return decryptedBytes; } catch (DllNotFoundException e) { Trace.TraceError("SnkLib.App.CookieGetter.dll:\r\n" + "DecryptProtectedData()でエラーが発生しました。Win32API呼び出しで対象のdllが存在しませんでした。\r\n" + e.ToString()); return null; } finally { if (input.pbData != null) Marshal.FreeHGlobal(input.pbData); if (output.pbData != null) Marshal.FreeHGlobal(output.pbData); } }
public static string EncryptRDPPassword(string pw) { string encnewpass = ""; byte[] pwba = Encoding.Unicode.GetBytes(pw); DATA_BLOB dataIn = new DATA_BLOB(); DATA_BLOB dataOut = new DATA_BLOB(); StringBuilder epwsb = new StringBuilder(); try { try { InitBLOB(pwba, ref dataIn); } catch (Exception ex) { writeToLog("Error creating paswoord " + ex.Message.ToString()); } bool success = CryptProtectData( ref dataIn, "rdp", NullPtr, NullPtr, NullPtr, CRYPTPROTECT_UI_FORBIDDEN, ref dataOut); if (!success) { int errCode = Marshal.GetLastWin32Error(); writeToLog("CryptProtectData failed, error code + " + errCode.ToString()); encnewpass = ""; } byte[] epwba = new byte[dataOut.cbData]; Marshal.Copy(dataOut.pbData, epwba, 0, dataOut.cbData); // Convert hex data to hex characters (suitable for a string) for (int i = 0; i < dataOut.cbData; i++) { epwsb.Append(Convert.ToString(epwba[i], 16).PadLeft(2, '0').ToUpper()); } } catch (Exception ex) { writeToLog("Encryption error : " + ex.Message.ToString()); encnewpass = ""; } finally { if (dataIn.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(dataIn.pbData); } if (dataOut.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(dataOut.pbData); } } encnewpass = epwsb.ToString(); return encnewpass; }
public byte[] Decrypt(byte[] cipherText, byte[] optionalEntropy) { DATA_BLOB pDataOut = new DATA_BLOB(); DATA_BLOB pDataIn = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT ps = new CRYPTPROTECT_PROMPTSTRUCT(); this.InitPromptstruct(ref ps); try { int num2; try { int length = cipherText.Length; pDataIn.pbData = Marshal.AllocHGlobal(length); if (IntPtr.Zero == pDataIn.pbData) { throw new Exception("Unable to allocate cipherText buffer."); } pDataIn.cbData = length; Marshal.Copy(cipherText, 0, pDataIn.pbData, pDataIn.cbData); } catch (Exception exception) { throw new Exception("Exception marshalling data. " + exception.Message); } DATA_BLOB pOptionalEntropy = new DATA_BLOB(); if (Store.Machine == this.store) { num2 = 5; if (optionalEntropy == null) { optionalEntropy = new byte[0]; } try { int cb = optionalEntropy.Length; pOptionalEntropy.pbData = Marshal.AllocHGlobal(cb); if (IntPtr.Zero == pOptionalEntropy.pbData) { throw new Exception("Unable to allocate entropy buffer."); } pOptionalEntropy.cbData = cb; Marshal.Copy(optionalEntropy, 0, pOptionalEntropy.pbData, cb); goto Label_0113; } catch (Exception exception2) { throw new Exception("Exception entropy marshalling data. " + exception2.Message); } } num2 = 1; Label_0113: if (!CryptUnprotectData(ref pDataIn, null, ref pOptionalEntropy, IntPtr.Zero, ref ps, num2, ref pDataOut)) { throw new Exception("Decryption failed. " + GetErrorMessage(Marshal.GetLastWin32Error())); } if (IntPtr.Zero != pDataIn.pbData) { Marshal.FreeHGlobal(pDataIn.pbData); } if (IntPtr.Zero != pOptionalEntropy.pbData) { Marshal.FreeHGlobal(pOptionalEntropy.pbData); } } catch (Exception exception3) { throw new Exception("Exception decrypting. " + exception3.Message); } byte[] destination = new byte[pDataOut.cbData]; Marshal.Copy(pDataOut.pbData, destination, 0, pDataOut.cbData); return destination; }
/// <summary> /// Initializes a BLOB structure from a byte array. /// </summary> /// <param name="data"> /// Original data in a byte array format. /// </param> /// <param name="blob"> /// Returned blob structure. /// </param> private static void InitBLOB(byte[] data, ref DATA_BLOB blob) { //Modified By Mrch1.Need to convert the data to Unicode. byte[] tmp = System.Text.Encoding.Convert(System.Text.Encoding.ASCII, System.Text.Encoding.Unicode, data); // Allocate memory for the BLOB data. blob.pbData = Marshal.AllocHGlobal(tmp.Length); // Make sure that memory allocation was successful. if (blob.pbData == IntPtr.Zero) throw new Exception( "Unable to allocate data buffer for BLOB structure."); // Specify number of bytes in the BLOB. blob.cbData = tmp.Length; // Copy data from original source to the BLOB structure. Marshal.Copy(tmp, 0, blob.pbData, tmp.Length); }
public static byte[] Decrypt(byte[] cipherTextBytes, byte[] entropyBytes, out string description) { // Create BLOBs to hold data. DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); // We only need prompt structure because it is a required // parameter. CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPrompt(ref prompt); // Initialize description string. description = String.Empty; try { // Convert ciphertext bytes into a BLOB structure. try { InitBLOB(cipherTextBytes, ref cipherTextBlob); } catch (Exception ex) { throw new Exception( "Cannot initialize ciphertext BLOB.", ex); } // Convert entropy bytes into a BLOB structure. try { InitBLOB(entropyBytes, ref entropyBlob); } catch (Exception ex) { throw new Exception( "Cannot initialize entropy BLOB.", ex); } // Disable any types of UI. CryptUnprotectData does not // mention CRYPTPROTECT_LOCAL_MACHINE flag in the list of // supported flags so we will not set it up. int flags = CRYPTPROTECT_UI_FORBIDDEN; // Call DPAPI to decrypt data. bool success = CryptUnprotectData(ref cipherTextBlob, ref description, ref entropyBlob, IntPtr.Zero, ref prompt, flags, ref plainTextBlob); // Check the result. if (!success) { // If operation failed, retrieve last Win32 error. int errCode = Marshal.GetLastWin32Error(); // Win32Exception will contain error message corresponding // to the Windows error code. throw new Exception( "CryptUnprotectData failed.", new Win32Exception(errCode)); } // Allocate memory to hold plaintext. byte[] plainTextBytes = new byte[plainTextBlob.cbData]; // Copy ciphertext from the BLOB to a byte array. Marshal.Copy(plainTextBlob.pbData, plainTextBytes, 0, plainTextBlob.cbData); // Return the result. return plainTextBytes; } catch (Exception ex) { throw new Exception("DPAPI was unable to decrypt data.", ex); } // Free all memory allocated for BLOBs. finally { if (plainTextBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(plainTextBlob.pbData); if (cipherTextBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(cipherTextBlob.pbData); if (entropyBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(entropyBlob.pbData); } }
public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy) { DATA_BLOB pDataIn = new DATA_BLOB(); DATA_BLOB pDataOut = new DATA_BLOB(); DATA_BLOB pOptionalEntropy = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT ps = new CRYPTPROTECT_PROMPTSTRUCT(); this.InitPromptstruct(ref ps); try { int num; try { int length = plainText.Length; pDataIn.pbData = Marshal.AllocHGlobal(length); if (IntPtr.Zero == pDataIn.pbData) { throw new Exception("Unable to allocate plaintext buffer."); } pDataIn.cbData = length; Marshal.Copy(plainText, 0, pDataIn.pbData, length); } catch (Exception exception) { throw new Exception("Exception marshalling data. " + exception.Message); } if (Store.Machine == this.store) { num = 5; if (optionalEntropy == null) { optionalEntropy = new byte[0]; } try { int num3 = optionalEntropy.Length; pOptionalEntropy.pbData = Marshal.AllocHGlobal(optionalEntropy.Length); if (IntPtr.Zero == pOptionalEntropy.pbData) { throw new Exception("Unable to allocate entropy data buffer."); } Marshal.Copy(optionalEntropy, 0, pOptionalEntropy.pbData, num3); pOptionalEntropy.cbData = num3; goto Label_010F; } catch (Exception exception2) { throw new Exception("Exception entropy marshalling data. " + exception2.Message); } } num = 1; Label_010F: if (!CryptProtectData(ref pDataIn, "", ref pOptionalEntropy, IntPtr.Zero, ref ps, num, ref pDataOut)) { throw new Exception("Encryption failed. " + GetErrorMessage(Marshal.GetLastWin32Error())); } } catch (Exception exception3) { throw new Exception("Exception encrypting. " + exception3.Message); } byte[] destination = new byte[pDataOut.cbData]; Marshal.Copy(pDataOut.pbData, destination, 0, pDataOut.cbData); return destination; }
private static extern bool CryptProtectData(ref DATA_BLOB pPlainText, string szDescription, ref DATA_BLOB pCipherText);
public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) { byte[] decdata = null; int hr = 0; DATA_BLOB cipher = new DATA_BLOB (); DATA_BLOB entropy = new DATA_BLOB (); DATA_BLOB data = new DATA_BLOB (); try { CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0); cipher.Alloc (encryptedData); entropy.Alloc (optionalEntropy); // note: the scope/flags has already been check by the public caller uint flags = CRYPTPROTECT_UI_FORBIDDEN; if (scope == DataProtectionScope.LocalMachine) flags |= CRYPTPROTECT_LOCAL_MACHINE; if (CryptUnprotectData (ref cipher, null, ref entropy, IntPtr.Zero, ref prompt, flags, ref data)) { // copy decrypted data back to managed codde decdata = data.ToBytes (); } else { hr = Marshal.GetLastWin32Error (); } } catch (Exception ex) { string msg = Locale.GetText ("Error protecting data."); throw new CryptographicException (msg, ex); } finally { cipher.Free (); data.Free (); entropy.Free (); } if ((decdata == null) || (hr != 0)) { throw new CryptographicException (hr); } return decdata; }
/// <summary> /// Decrypt byte data /// </summary> /// <param name="cipherText">Data to be decoded</param> /// <param name="optionalEntropy">Additional entropy, recommended for machine-specific case</param> /// <returns>Returns a byte array with the encoded data</returns> internal byte[] Decrypt(byte[] cipherText, byte[] optionalEntropy) { bool retVal = false; DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherBlob = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPromptstruct(ref prompt); try { try { int cipherTextSize = cipherText.Length; cipherBlob.pbData = Marshal.AllocHGlobal(cipherTextSize); if(IntPtr.Zero == cipherBlob.pbData) { throw new Exception("Unable to allocate cipherText buffer."); } cipherBlob.cbData = cipherTextSize; Marshal.Copy(cipherText, 0, cipherBlob.pbData, cipherBlob.cbData); } catch(Exception ex) { throw new Exception("Exception marshalling data. " + ex.Message); } DATA_BLOB entropyBlob = new DATA_BLOB(); int dwFlags; if(Store.USE_MACHINE_STORE == store) { //Using the machine store, should be providing entropy. dwFlags = CRYPTPROTECT_LOCAL_MACHINE|CRYPTPROTECT_UI_FORBIDDEN; //Check to see if the entropy is null if(null == optionalEntropy) { //Allocate something optionalEntropy = new byte[0]; } try { int bytesSize = optionalEntropy.Length; entropyBlob.pbData = Marshal.AllocHGlobal(bytesSize); if(IntPtr.Zero == entropyBlob.pbData) { throw new Exception("Unable to allocate entropy buffer."); } entropyBlob.cbData = bytesSize; Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize); } catch(Exception ex) { throw new Exception("Exception marshalling entropy data. " + ex.Message); } } else { //Using the user store dwFlags = CRYPTPROTECT_UI_FORBIDDEN; } retVal = CryptUnprotectData(ref cipherBlob, null, ref entropyBlob, IntPtr.Zero, ref prompt, dwFlags, ref plainTextBlob); if(false == retVal) { throw new Exception("Decryption failed. " + Win32Message.GetMessage(Marshal.GetLastWin32Error())); } //Free the blob and entropy. if(IntPtr.Zero != cipherBlob.pbData) { Marshal.FreeHGlobal(cipherBlob.pbData); } if(IntPtr.Zero != entropyBlob.pbData) { Marshal.FreeHGlobal(entropyBlob.pbData); } } catch(Exception ex) { throw new Exception("Exception decrypting. " + ex.Message); } byte[] plainText = new byte[plainTextBlob.cbData]; Marshal.Copy(plainTextBlob.pbData, plainText, 0, plainTextBlob.cbData); Marshal.FreeHGlobal(plainTextBlob.pbData); return plainText; }
private static void InitBLOB(byte[] data, ref DATA_BLOB blob) { // Use empty array for null parameter. if (data == null) data = new byte[0]; // Allocate memory for the BLOB data. blob.pbData = Marshal.AllocHGlobal(data.Length); // Make sure that memory allocation was successful. if (blob.pbData == IntPtr.Zero) throw new Exception( "Unable to allocate data buffer for BLOB structure."); // Specify number of bytes in the BLOB. blob.cbData = data.Length; // Copy data from original source to the BLOB structure. Marshal.Copy(data, 0, blob.pbData, data.Length); }
public static byte[] Encrypt(DataProtection.KeyType keyType, byte[] plainTextBytes, byte[] entropyBytes, string description) { if (plainTextBytes == null) plainTextBytes = new byte[0]; if (entropyBytes == null) entropyBytes = new byte[0]; if (description == null) description = string.Empty; DATA_BLOB dataBlob1 = new DATA_BLOB(); DATA_BLOB pCipherText = new DATA_BLOB(); DATA_BLOB dataBlob2 = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT cryptprotectPromptstruct = new CRYPTPROTECT_PROMPTSTRUCT(); DataProtection.InitPrompt(ref cryptprotectPromptstruct); try { try { DataProtection.InitBLOB(plainTextBytes, ref dataBlob1); } catch (Exception ex) { throw new Exception("Cannot initialize plaintext BLOB.", ex); } try { DataProtection.InitBLOB(entropyBytes, ref dataBlob2); } catch (Exception ex) { throw new Exception("Cannot initialize entropy BLOB.", ex); } int dwFlags = 1; if (keyType == DataProtection.KeyType.MachineKey) dwFlags |= 4; if (!Advent.Common.Interop.NativeMethods.CryptProtectData(ref dataBlob1, description, ref dataBlob2, IntPtr.Zero, ref cryptprotectPromptstruct, dwFlags, ref pCipherText)) throw new Exception("CryptProtectData failed.", (Exception)new Win32Exception(Marshal.GetLastWin32Error())); byte[] destination = new byte[pCipherText.cbData]; Marshal.Copy(pCipherText.pbData, destination, 0, pCipherText.cbData); return destination; } catch (Exception ex) { throw new Exception("DPAPI was unable to encrypt data.", ex); } finally { if (dataBlob1.pbData != IntPtr.Zero) Marshal.FreeHGlobal(dataBlob1.pbData); if (pCipherText.pbData != IntPtr.Zero) Marshal.FreeHGlobal(pCipherText.pbData); if (dataBlob2.pbData != IntPtr.Zero) Marshal.FreeHGlobal(dataBlob2.pbData); } }
public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy) { bool retVal = false; DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPromptstruct(ref prompt); int dwFlags; try { try { int bytesSize = plainText.Length; plainTextBlob.pbData = Marshal.AllocHGlobal(bytesSize); if (IntPtr.Zero == plainTextBlob.pbData) { throw new Exception("Unable to allocate plaintext buffer."); } plainTextBlob.cbData = bytesSize; Marshal.Copy(plainText, 0, plainTextBlob.pbData, bytesSize); } catch (Exception ex) { throw new Exception("Exception marshalling data. " + ex.Message); } if (Store.Machine == store) { //Using the machine store, should be providing entropy. dwFlags = CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN; //Check to see if the entropy is null if (null == optionalEntropy) { //Allocate something optionalEntropy = new byte[0]; } try { int bytesSize = optionalEntropy.Length; entropyBlob.pbData = Marshal.AllocHGlobal(optionalEntropy.Length); if (IntPtr.Zero == entropyBlob.pbData) { throw new Exception("Unable to allocate entropy data buffer."); } Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize); entropyBlob.cbData = bytesSize; } catch (Exception ex) { throw new Exception("Exception entropy marshalling data. " + ex.Message); } } else { //Using the user store dwFlags = CRYPTPROTECT_UI_FORBIDDEN; } retVal = CryptProtectData(ref plainTextBlob, "", ref entropyBlob, IntPtr.Zero, ref prompt, dwFlags, ref cipherTextBlob); if (false == retVal) { throw new Exception("Encryption failed. " + GetErrorMessage(Marshal.GetLastWin32Error())); } } catch (Exception ex) { throw new Exception("Exception encrypting. " + ex.Message); } byte[] cipherText = new byte[cipherTextBlob.cbData]; Marshal.Copy(cipherTextBlob.pbData, cipherText, 0, cipherTextBlob.cbData); return cipherText; }
public static extern bool CryptUnprotectData(ref DATA_BLOB pDataIn, StringBuilder szDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DATA_BLOB pDataOut);