49 lines
1.5 KiB
C#
49 lines
1.5 KiB
C#
using System.Numerics;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace Encryption;
|
|
|
|
public static class RSA
|
|
{
|
|
// Hash funciton to use. Only cryptographic hash functions can be used.
|
|
private static Func<byte[], byte[]> _hash = (data) => SHA256.HashData(data);
|
|
|
|
/// <summary>
|
|
/// Encrypt message with (message^e) mod n
|
|
/// </summary>
|
|
/// <param name="publicKey"></param>
|
|
/// <param name="data"></param>
|
|
/// <returns></returns>
|
|
public static byte[] Encrypt(RsaPublicKey publicKey, byte[] data)
|
|
{
|
|
var dataAsBigint = new BigInteger(data);
|
|
return BigInteger.ModPow(dataAsBigint, publicKey.E, publicKey.N).ToByteArray();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Decrypt cipher with (cipher^d) mod n
|
|
/// </summary>
|
|
/// <param name="publicKey"></param>
|
|
/// <param name="data"></param>
|
|
/// <returns></returns>
|
|
public static byte[] Decrypt(RsaPrivateKey privateKey, byte[] data)
|
|
{
|
|
var dataAsBigint = new BigInteger(data);
|
|
return BigInteger.ModPow(dataAsBigint, privateKey.D, privateKey.N).ToByteArray();
|
|
}
|
|
|
|
public static byte[] Sign(RsaPrivateKey privateKey, byte[] data)
|
|
{
|
|
var dataHash = _hash(data);
|
|
return Decrypt(privateKey, dataHash);
|
|
}
|
|
|
|
public static bool Verify(RsaPublicKey publicKey, byte[] data, byte[] signature)
|
|
{
|
|
var dataHash = _hash(data);
|
|
var encryptedSignature = Encrypt(publicKey, signature);
|
|
|
|
return dataHash == encryptedSignature;
|
|
}
|
|
|
|
} |