适用于RSA算法实现的数据结构

时间:2014-07-06 23:11:49

标签: c# data-structures rsa

我是C#的新手,并试图实现RSA算法。这是我的实施:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RSA
{
    class Program
    {
        static void Main(string[] args)
        {
            int p = 7;
            int q = 19;
            int message = 6;

            int n = p * q;
            int m = (p - 1) * (q - 1);

            int publicKey = 0;
            int secretKey = 0;

            //find a number e(1<e<m) such that e is coprime of m. e is the public key
            for (int value = 1; value < m; value++ )
            {
                if((m % value) != 0)
                {
                    publicKey = value;
                    break;
                }
            }

            //find a number d such that de%m = 1. d is called the secret key
            for (int value = 0; value <= n; value++ )
            { 
                 double d = (1.0 + (double)(value * m)) / (double)publicKey;
                 if((d % 1) == 0)
                 {
                     secretKey = (int)d;
                     break;
                 }
            }

            int encryptedMessage = Encryption(n, message, publicKey);
            int decryptedMessage = Decryption(n, encryptedMessage, secretKey);

            Console.WriteLine(message);
            Console.WriteLine(encryptedMessage);
            Console.WriteLine(decryptedMessage);
            Console.ReadLine();
       }

       //function for message encryption
       public static int Encryption(int n, int message, int publicKey)
       {
            int temp = (int)Math.Pow(message, publicKey);
            int encryptedMessage = temp % n;
            return encryptedMessage;
       }

       //function for message decryption
       public static int Decryption(int n, int encryptedMessage, int secretKey)
       {
            int temp = (int)Math.Pow(encryptedMessage, secretKey);
            int decryptedMessage = (int)temp % n;
            return decryptedMessage;
       }

  }
}

我收到正确的加密邮件但解密后错误的值。我想这是由于生成的数字太大而无法保持双倍。任何人都可以建议一种方法来纠正这个问题吗?

0 个答案:

没有答案