通过RSA算法对值进行加密和解密

时间:2019-04-02 03:50:01

标签: c# rsa

我创建了一个用于RSA加密和解密的程序。对于某些数字值,解密结果与原始值不匹配。

例如:

  • 327:解密效果很好
  • 512:解密问题

对于加密和解密,我使用BigInteger.ModPow()

using System;
using System.Numerics;

namespace ExperimentsWithCryptographicAlgorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger number = new BigInteger(327);

            KeyPair keys = new KeyPair();
            keys.OpenKey = new Key(new BigInteger(5), new BigInteger(493));
            keys.SecurityKey = new Key(new BigInteger(269), new BigInteger(493));

            BigInteger hash = Encrypt(number, keys.OpenKey);
            if (Decrypt(hash, keys.SecurityKey) == number)
            {
                Console.WriteLine("Succesfully encrypted / decrypted!");
            }
            else
            {
                Console.WriteLine("Error in encryption or decryption!");
            }
        }

        static BigInteger Encrypt(BigInteger encryptedValue, Key publicKey)
        {
            return BigInteger.ModPow(encryptedValue, publicKey.FirstPart, publicKey.SecondPart);
        }

        static BigInteger Decrypt(BigInteger decryptedValue, Key securityKey)
        {
            return BigInteger.ModPow(decryptedValue, securityKey.FirstPart, securityKey.SecondPart);
        }
    }

    public struct Key
    {
        public BigInteger FirstPart { get; set; }
        public BigInteger SecondPart { get; set; }

        public Key(BigInteger fPart, BigInteger sPart)
        {
            FirstPart = fPart;
            SecondPart = sPart;
        }
    }

    public struct KeyPair
    {
        public Key OpenKey { get; set; }
        public Key SecurityKey { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

我检查了您的算法,它对于-492到492范围内的数字非常有用。这似乎是算法的物理限制,因为最后的算术运算是使用securityKey.SecondPart进行的模运算,恰好是493。