Skip to content

Commit b258e2c

Browse files
committed
feat: add base Rsa encryption class with method for data encryption and decryption including method to generate keys
1 parent ea3b02c commit b258e2c

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
using System.Security.Cryptography;
2+
using System.Text;
3+
using System;
4+
using System.Threading.Tasks;
5+
6+
namespace SafeCrypt.RsaEncryption
7+
{
8+
public class RsaEncryption
9+
{
10+
/// <summary>
11+
/// Generates RSA key pair.
12+
/// </summary>
13+
/// <param name="keySize">The size of the key pair (e.g., 1024, 2048 bits).</param>
14+
/// <returns>The generated RSA key pair.</returns>
15+
public static Tuple<string, string> GenerateRsaKeys(int keySize)
16+
{
17+
using (var rsa = new RSACryptoServiceProvider(keySize))
18+
{
19+
string publicKey = rsa.ToXmlString(false); // Don't include private key
20+
string privateKey = rsa.ToXmlString(true); // Include private key
21+
22+
return new Tuple<string, string>(publicKey, privateKey);
23+
}
24+
}
25+
26+
/// <summary>
27+
/// Encrypts data using RSA public key.
28+
/// </summary>
29+
/// <param name="data">The data to be encrypted.</param>
30+
/// <param name="publicKey">The RSA public key.</param>
31+
/// <returns>The encrypted data.</returns>
32+
public static async Task<byte[]> EncryptAsync(string data, string publicKey)
33+
{
34+
35+
return await Task.Run(() => {
36+
using (var rsa = new RSACryptoServiceProvider())
37+
{
38+
rsa.FromXmlString(publicKey);
39+
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
40+
byte[] encryptedData = rsa.Encrypt(dataBytes, false);
41+
return encryptedData;
42+
}
43+
});
44+
}
45+
46+
/// <summary>
47+
/// Decrypts data using RSA private key.
48+
/// </summary>
49+
/// <param name="encryptedData">The encrypted data.</param>
50+
/// <param name="privateKey">The RSA private key.</param>
51+
/// <returns>The decrypted data.</returns>
52+
public static async Task<string> DecryptAsync(byte[] encryptedData, string privateKey)
53+
{
54+
return await Task.Run(() =>
55+
{
56+
using (var rsa = new RSACryptoServiceProvider())
57+
{
58+
rsa.FromXmlString(privateKey);
59+
byte[] decryptedData = rsa.Decrypt(encryptedData, false);
60+
return Encoding.UTF8.GetString(decryptedData);
61+
}
62+
});
63+
}
64+
}
65+
}

0 commit comments

Comments
 (0)