Scenario:
Encryption using Asymmetric keys
Solution:
Asymmetric can only encrypt/decrypt small amount of data (based on key size) and it can be used without shared a key.
//add nuget pakage - CertificateManager
|
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 | public sealed class RSAEncryption
{
public string Encrypt(string text, RSA rsa)
{
var data = Encoding.UTF8.GetBytes(text);
var cypher = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(cypher);
}
public string Decrypt(string encryptedText, RSA rsa)
{
var data = Convert.FromBase64String(encryptedText);
var cypher = rsa.Decrypt(data, RSAEncryptionPadding.Pkcs1);
return Encoding.UTF8.GetString(cypher);
}
public RSA CreateRSAPublicKey(X509Certificate2 cert)
{
return cert.GetRSAPublicKey();
}
public RSA CreateRSAPrivateKey(X509Certificate2 cert)
{
return cert.GetRSAPrivateKey();
}
public X509Certificate2 CreateRSACertificate(CreateCertificates createCertificates, int keySize)
{
var constraints = new BasicConstraints
{
CertificateAuthority = true,
HasPathLengthConstraint = true,
Critical = false,
PathLengthConstraint = 2
};
var name = new SubjectAlternativeName
{
DnsName = new List<string>
{
"CoreSigningCertificate"
}
};
var distinguishedName = new DistinguishedName { CommonName = "CoreSigningCertificate" };
var flags = X509KeyUsageFlags.KeyCertSign
| X509KeyUsageFlags.DigitalSignature
| X509KeyUsageFlags.CrlSign
| X509KeyUsageFlags.DataEncipherment
| X509KeyUsageFlags.KeyAgreement
| X509KeyUsageFlags.NonRepudiation;
var keyUsage = new OidCollection
{
OidLookup.CodeSigning,
OidLookup.SecureEmail,
OidLookup.TimeStamping
};
var validdity = new ValidityPeriod
{
ValidFrom = DateTimeOffset.UtcNow,
ValidTo = DateTimeOffset.UtcNow.AddYears(1)
};
var config = new RsaConfiguration
{
KeySize = keySize,
HashAlgorithmName = HashAlgorithmName.SHA256,
RSASignaturePadding = RSASignaturePadding.Pkcs1
};
var certificate = createCertificates.NewRsaSelfSignedCertificate
(distinguishedName, constraints, validdity, name, keyUsage, flags, config);
return certificate;
}
} |
| |
|
|
| |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 | static void Main(string[] args)
{
var serviceCollection = new ServiceCollection().AddCertificateManager().BuildServiceProvider();
var instance = serviceCollection.GetService<CreateCertificates>();
var e = new RSAEncryption();
//create certificate
var cert = e.CreateRSACertificate(instance, 3072);
var data = "User Data";
//encrypt using public key
var encryptedData = e.Encrypt(data, e.CreateRSAPublicKey(cert));
Console.WriteLine(encryptedData);
//decrypt using private key
var decryptedData = e.Decrypt(encryptedData, e.CreateRSAPrivateKey(cert));
Console.WriteLine(decryptedData);
Console.ReadLine();
} |
No comments:
Post a Comment