forked from JanisEst/KeePassBrowserImporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cryptography.cs
87 lines (70 loc) · 1.9 KB
/
Cryptography.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
namespace KeePassBrowserImporter
{
public class Cryptography
{
#region Extern
[DllImport("crypt32.dll")]
private static extern bool CryptUnprotectData(
DATA_BLOB pCipherText,
IntPtr pszDescription,
DATA_BLOB pEntropy,
IntPtr pReserved,
IntPtr pPrompt,
int dwFlags,
DATA_BLOB pPlainText
);
[StructLayout(LayoutKind.Sequential)]
internal class DATA_BLOB
{
public int cbData;
public IntPtr pbData;
public static DATA_BLOB CreateFrom(byte[] data)
{
var blob = new DATA_BLOB();
if (data == null)
{
data = new byte[0];
}
blob.pbData = Marshal.AllocHGlobal(data.Length);
if (blob.pbData == IntPtr.Zero)
{
throw new Exception();
}
blob.cbData = data.Length;
Marshal.Copy(data, 0, blob.pbData, data.Length);
return blob;
}
}
#endregion
/// <summary>
/// Decrypt the provided data using CryptUnprotectData.
/// </summary>
/// <param name="data">The data to decrypt</param>
/// <returns>The decrypted data</returns>
public static byte[] DecryptUserData(byte[] data)
{
return DecryptUserData(data, null);
}
/// <summary>
/// Decrypt the provided data using CryptUnprotectData.
/// </summary>
/// <param name="data">The data to decrypt</param>
/// <param name="entropy">The entropy to use (can be null)</param>
/// <returns>The decrypted data</returns>
public static byte[] DecryptUserData(byte[] data, byte[] entropy)
{
Contract.Requires(data != null);
var result = new byte[0];
var plain = new DATA_BLOB();
if (CryptUnprotectData(DATA_BLOB.CreateFrom(data), IntPtr.Zero, entropy != null ? DATA_BLOB.CreateFrom(entropy) : null, IntPtr.Zero, IntPtr.Zero, 0, plain))
{
result = new byte[plain.cbData];
Marshal.Copy(plain.pbData, result, 0, plain.cbData);
}
return result;
}
}
}