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 _hash = (data) => SHA256.HashData(data); /// /// Encrypt message with (message^e) mod n /// /// /// /// public static byte[] Encrypt(RsaPublicKey publicKey, byte[] data) { var dataAsBigint = new BigInteger(data); return BigInteger.ModPow(dataAsBigint, publicKey.E, publicKey.N).ToByteArray(); } /// /// Decrypt cipher with (cipher^d) mod n /// /// /// /// 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; } }