Scenario:
Use X509 Certificates 2 for encryption/decryption
Solution:
- makecert -r -pe -n "CN=CERT_SIGN_TEST_CERT" -b 08/13/2021 -e 08/15/2021 -sky exchange -ss my
- -r - Creates a self-signed certificate.
- -pe - Mark private key as exportable.
- -n - Name [X.500 standard]
- -b - Start date
- -e - End Date
- -sky - Subject's key specification [Signature/Exchange]
- -ss - SubjectCertStoreName
- MMC -> File->Add/Remove Snap-in -> Certificates -> Personal -> Certificates -> CERT_SIGN_TEST_CERT -> ThumbPrint
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 | class ProgramX509Certificate2
{
static void Main(string[] args)
{
var originalData = "This is top secret!!!!";
var thumbPrint = "c6aedff377b3c970b3447c3319241111e1188";
X509Certificate2 cert = GetCertificate(thumbPrint);
if (cert == null)
{
Console.WriteLine("Certificate 'CN=CERT_SIGN_TEST_CERT' not found.");
Console.ReadLine();
}
var encryptData = Encrypt(thumbPrint, originalData);
var decryptData = Decrypt(thumbPrint, encryptData);
Console.WriteLine($"Message is: {decryptData}");
Console.ReadLine();
}
private static X509Certificate2 GetCertificate(string thumbprint)
{
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var cert = store.Certificates.Cast<X509Certificate2>()
.FirstOrDefault(
c => c.Thumbprint.Equals(thumbprint.Replace(" ", "").ToUpper(), StringComparison.InvariantCultureIgnoreCase));
return cert;
}
private static RSA GetPublicKey(string thumbprint)
{
var cert = GetCertificate(thumbprint);
return (RSA)cert.PublicKey.Key;
}
private static RSA GetPrivateKey(string thumbprint)
{
var cert = GetCertificate(thumbprint);
return (RSA)cert.GetRSAPrivateKey();
}
private static string Encrypt(string thumbprint, string value)
{
var encryptData = GetPublicKey(thumbprint).Encrypt(System.Text.Encoding.UTF8.GetBytes(value), RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(encryptData);
}
private static string Decrypt(string thumbprint, string value)
{
var decrypttData = GetPrivateKey(thumbprint).Decrypt(Convert.FromBase64String(value), RSAEncryptionPadding.Pkcs1);
return System.Text.Encoding.UTF8.GetString(decrypttData);
}
} |
| |
No comments:
Post a Comment