📄 dpapi.cs
字号:
using System;
using Microsoft.Win32;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
#region 版权声明
///
/// 版权所有(C)2005,2006 作者:漆巧林。保留所有权利, davidqql@gmail.com, davidqql@hotmail.com
///
/// 作者不对本代码提供任何保证,因此,对于使用该代码带来的损害或者潜在的损害,作者不承担责任。
/// 在满足如下的条件下,你可以自由使用该代码:
/// 1. 非商业应用
/// 2. 保留本版权声明
/// 要进行商业应用,必须得到作者的书面许可。
/// 你可以修改和自由发布本代码,条件是保留前述的版权声明。
///
#endregion
namespace BizSecurity
{
public class DPAPI
{//必须自己捕获错误
[DllImport("Crypt32.dll",
SetLastError = true,
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool CryptProtectData(
ref DATA_BLOB pDataIn,
string szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct,
int dwFlags,
ref DATA_BLOB pDataOut);
[DllImport("Crypt32.dll", SetLastError=true,
CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool CryptUnprotectData(
ref DATA_BLOB pDataIn,
ref String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct,
int dwFlags,
ref DATA_BLOB pDataOut);
// [DllImport("kernel32.dll",
// CharSet=System.Runtime.InteropServices.CharSet.Auto)]
// private unsafe static extern int FormatMessage(int dwFlags,
// ref IntPtr lpSource,
// int dwMessageId,
// int dwLanguageId,
// ref String lpBuffer, int nSize,
// IntPtr *Arguments);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct DATA_BLOB
{
public int cbData;
public IntPtr pbData;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct CRYPTPROTECT_PROMPTSTRUCT
{
public int cbSize;
public int dwPromptFlags;
public IntPtr hwndApp;
public String szPrompt;
}
static private IntPtr NullPtr = ((IntPtr)((int)(0)));
private const int CRYPTPROTECT_UI_FORBIDDEN = 0x1;
private const int CRYPTPROTECT_LOCAL_MACHINE = 0x4;
private static void InitPrompt(ref CRYPTPROTECT_PROMPTSTRUCT ps)
{
ps.cbSize = Marshal.SizeOf(
typeof(CRYPTPROTECT_PROMPTSTRUCT));
ps.dwPromptFlags= 0;
ps.hwndApp = NullPtr;
ps.szPrompt = null;
}
private static void InitBLOB(byte[] data, ref DATA_BLOB blob)
{
// 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 enum KeyType {UserKey = 1, MachineKey};
// private static KeyType defaultKeyType = KeyType.MachineKey;
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);
}
}
public static string Encrypt(KeyType keyType,
string plainText,
string entropy,
string description)
{
// Make sure that parameters are valid.
if (plainText == null) plainText = String.Empty;
if (entropy == null) entropy = String.Empty;
// Call encryption routine and convert returned bytes into
// a base64-encoded value.
return Convert.ToBase64String(
Encrypt(keyType,
Encoding.UTF8.GetBytes(plainText),
Encoding.UTF8.GetBytes(entropy),
description));
}
public static string Encrypt(KeyType keyType, string plainText)
{
return Encrypt(keyType,plainText,string.Empty,string.Empty);
}
public static string Encrypt(string plainText)
{
return Encrypt(KeyType.MachineKey, plainText, String.Empty,
String.Empty);
}
/////////////////////////////////////////////
public static string Decrypt(string cipherText)
{
string description;
return Decrypt(cipherText, String.Empty, out description);
}
public static string Decrypt(string cipherText,
string entropy,
out string description)
{
// Make sure that parameters are valid.
if (entropy == null) entropy = String.Empty;
return Encoding.UTF8.GetString(
Decrypt(Convert.FromBase64String(cipherText),
Encoding.UTF8.GetBytes(entropy),
out description));
}
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 class RegistryAccess
{
public static string GetRegistry(string dir, string key)//错误虽然捕获,但是没有显示
{
try
{
string temp = @"software\" + dir;
return Registry.LocalMachine.OpenSubKey(temp).GetValue(key).ToString();
}
catch(Exception)
{
//MessageBox.Show(e.Message.ToString());
return string.Empty;
}
}
public static void SetRegistry(string dir, string key ,string keyValue)
{
try
{
string temp = @"software\" + dir;
RegistryKey reg = Registry.LocalMachine.CreateSubKey(temp);
reg.SetValue(key, keyValue);
}
catch(Exception)
{
//MessageBox.Show(e.Message.ToString());
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -