[★] Dpapi (Data Protection API) data encryption and decryption

Source: Internet
Author: User

================================== Why can't I target Chinese characters? ================
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. runtime. interopservices;

Namespace csharptest
{
Public sealed class dataprotection
{
Public Enum store
{
Machine,
User
}
# Region Data Protection API
// Uses a private class to reference the dpapi used
Private class Win32
{
// Declares Constants
Public const int cryptprotect_ui_forbidden = 0x1;
Public const int cryptprotect_local_machine = 0x4;
// Declare the data structure used in dpapi
[Structlayout (layoutkind. Sequential)]
Public struct data_blob
{
Public int cbdata;
Public intptr pbdata;
}
// Introduce the crypproectdata Function
[Dllimport ("crypt32", charset = charset. Auto)]
Public static extern bool cryptprotectdata (ref data_blob pdatain, string szdatadescr, ref data_blob poptionalentropy, intptr pvreserved, intptr ppromptstruct, int dwflags, ref data_blob pdataout );

// Introduce the cryptunprotectdata Function
[Dllimport ("crypt32", charset = charset. Auto)]
Public static extern bool cryptunprotectdata (ref data_blob pdatain, stringbuilder szdatadescr, ref data_blob struct, intptr pvreserved, intptr ppromptstruct, int dwflags, ref data_blob pdataout );

// Introduce the localfree Function
[Dllimport ("Kernel32")]
Public static extern intptr localfree (intptr hmem );
}
# Endregion
/// <Summary>
/// Fill the data in the data_blob structure and copy the data from the managed memory to the unmanaged memory
/// </Summary>
/// <Param name = "blob"> </param>
/// <Param name = "bits"> </param>
Private Static void setblobdata (ref win32.data _ blob, byte [] bits)
{
// Fill the data in the data_blob Structure
Blob. cbdata = bits. length;
Blob. pbdata = marshal. allochglobal (bits. Length );
// Copy data from managed memory to unmanaged memory
Marshal. Copy (bits, 0, blob. pbdata, Bits. Length );
}
/// <Summary>
/// Obtain the data from the data_blob structure and Code Copying memory to managed memory
/// </Summary>
/// <Param name = "blob"> </param>
/// <Returns> </returns>
Private Static byte [] getblobdata (ref win32.data _ BLOB)
{
// If blob is empty, an empty string is returned.
If (BLOB. pbdata. toint32 () = 0)
Return NULL;
// Obtain data from the data_blob Structure
// Copy data from the unmanaged memory to the managed memory
Byte [] DATA = new byte [blob. cbdata];
Marshal. Copy (BLOB. pbdata, Data, 0, blob. cbdata );
Win32.localfree (BLOB. pbdata );
Return data;
}
Private class consts
{
Public readonly static byte [] entropydata = asciiencoding. ASCII. getbytes ("B0D125B7-967E-4f94-9305-A6F9AF56A19A ");
}
Private dataprotection ()
{
}
// Use dpapi (Data Protection API) for encryption. The returned value is a base64-encoded string.
Public static string encrypt (string data, store)
{
String result = ""; // result string
// Blob variable used in crypteprotectdata function call
Win32.data _ blob inblob = new win32.data _ blob ();
Win32.data _ blob entropyblob = new win32.data _ blob ();
Win32.data _ blob outblob = new win32.data _ blob ();
Try
{
// Set the flag used to call cryptprotectdata
Int flags = win32.cryptprotect _ ui_forbidden | (INT) (store = store. Machine )? Win32.cryptprotect _ LOCAL_MACHINE: 0 );
// Set the input blog variable, the blog to be encrypted
Setblobdata (ref inblob, asciiencoding. ASCII. getbytes (data ));
Setblobdata (ref entropyblob, consts. entropydata );

// If the dpapi function is called successfully, the function returns true and the result is placed in outblob.
If (win32.cryptprotectdata (ref inblob, "", ref entropyblob, intptr. Zero, intptr. Zero, flags, ref outblob ))
{
// Obtain BLOB Data
Byte [] resultbits = getblobdata (ref outblob );
// Convert to a base64 string
If (resultbits! = NULL)
Result = convert. tobase64string (resultbits );
}
}
Catch (exception ex)
{
Throw ex;
// If an error occurs, an empty string \ is returned \

}
Finally
{
If (inblob. pbdata. toint32 ()! = 0)
Marshal. freehglobal (inblob. pbdata );
If (entropyblob. pbdata. toint32 ()! = 0)
Marshal. freehglobal (entropyblob. pbdata );
}
Return result;
}
// Use dpapi (Data Protection API) for decryption. The input data is base64 encoded.
Public static string decrypt (string data, store)
{
// Return a string
String result = "";
// Use the Blob variable in the cryptunprotectdata function call
Win32.data _ blob inblob = new win32.data _ blob ();
Win32.data _ blob entropyblob = new win32.data _ blob ();
Win32.data _ blob outblob = new win32.data _ blob ();
Try
{
Int flags = win32.cryptprotect _ ui_forbidden | (INT) (store = store. Machine )? Win32.cryptprotect _ LOCAL_MACHINE: 0 );
// Convert the base64 encoded string into a byte array
Byte [] bits = convert. frombase64string (data );
// Set input blob variables, blob variables to be decrypted, and other variables
Setblobdata (ref inblob, BITs );
Setblobdata (ref entropyblob, consts. entropydata );

// Call the dpapi function. If the function is successful, true is returned and the result is filled in with outblob.
If (win32.cryptunprotectdata (ref inblob, null, ref entropyblob, intptr. Zero, intptr. Zero, flags, ref outblob ))
{
Byte [] resultbits = getblobdata (ref outblob );
// Restore to a string
If (resultbits! = NULL)
Result = asciiencoding. ASCII. getstring (resultbits );
}

}< br> catch (exception ex)
{< br> throw ex;
// if an error occurs, returns an empty string.

}< br> finally
{< br> If (inblob. pbdata. toint32 ()! = 0)
marshal. freehglobal (inblob. pbdata);
If (entropyblob. pbdata. toint32 ()! = 0)
marshal. freehglobal (entropyblob. pbdata);
// clear heap data

}
// Return results
Return result;
}

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.