教学服务系统

 找回密码
 立即注册
搜索
查看: 581|回复: 2

信息计算2019级1班8号林荟萃

[复制链接]

8

主题

20

帖子

92

积分

注册会员

Rank: 2

积分
92
发表于 2022-6-2 17:03:44 | 显示全部楼层 |阅读模式

RSA大数加解密

1  RSA算法
   RSA算法的理论基础是一种特殊的可逆模幂运算。
   设n是两个不同奇素数p和q的积,即:n=pq, j(n)=(p-1)(q-1)。
   定义密钥空间  k={(n,p,q,d,e)|n=pq,p和q是素数,deº1 mod j(n),e为随机整数},
   对每一个k=(n,p,q,d,e),
   定义加密变换为   Ek(x)=xb mod n,xÎZn;
   解密变换为       Dk(x)=ya mod n,yÎZn,Zn为整数集合。
   公开n和b,保密p,q和a.

Encryptors.java
  1. package RSAEncryptionAlgorithm;
  2. import java.io.UnsupportedEncodingException;
  3. import java.math.BigInteger;
  4. import java.util.Random;
  5. import java.util.Base64;
  6. import java.util.Scanner;

  7. public class Encryptors {
  8.     public static void main(String[] args) throws UnsupportedEncodingException {
  9.         //System.out.println(RSATolls.GetGcd(new BigInteger("168468468"), new BigInteger("489416814641")));;
  10.         //System.out.println(RSATolls.GetModInv(new BigInteger("168468468"), new BigInteger("489416814641")));
  11.         BigInteger p = BigInteger.probablePrime(256, new Random());
  12.         BigInteger q = BigInteger.probablePrime(256, new Random());
  13.         BigInteger n = p.multiply(q);
  14.         String nn = Base64.getEncoder().encodeToString(n.toByteArray());//编码之后的n
  15.         System.out.println("n:");
  16.         System.out.println(nn);
  17.         BigInteger fai_n = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
  18.         BigInteger e = new BigInteger(fai_n.bitLength(), new Random());
  19.         //System.out.println(n);
  20.         //System.out.println(fai_n);
  21.         while (!RSATolls.GetGcd(e, fai_n).equals(BigInteger.ONE)) {
  22.             do {
  23.                 e = new BigInteger(fai_n.bitLength(), new Random());
  24.             } while (e.compareTo(fai_n) >= 1);
  25.         }//公钥
  26.         BigInteger d = RSATolls.GetModInv(e, fai_n);//私钥
  27.         String ee = Base64.getEncoder().encodeToString(e.toByteArray());//编码之后的公钥
  28.         System.out.println("公钥:");
  29.         System.out.println(ee);
  30.         String dd = Base64.getEncoder().encodeToString(d.toByteArray());//编码之后的密钥
  31.         System.out.println("私钥:");
  32.         System.out.println(dd);
  33.         //加密
  34.         System.out.println("加密:");
  35.         System.out.println("请输入需要加密的明文:");
  36.         Scanner scan = new Scanner(System.in);
  37.         String userInput = scan.nextLine();
  38.         byte[] plaintextByte = userInput.getBytes("UTF-8");
  39.         byte[] plaintextByteCode = Base64.getEncoder().encode(plaintextByte);
  40.         BigInteger plaintextBI = new BigInteger(plaintextByteCode);
  41.         //System.out.println(plaintextBI);
  42.         System.out.println("输入n:" + nn);
  43.         System.out.println("输入公钥e:" + ee);
  44.         n = new BigInteger(Base64.getDecoder().decode(nn.getBytes()));
  45.         e = new BigInteger(Base64.getDecoder().decode(ee.getBytes()));
  46.         BigInteger c = plaintextBI.modPow(e, n);
  47.         System.out.println("密文:");
  48.         System.out.println(Base64.getEncoder().encodeToString(c.toByteArray()));
  49.         //解密
  50.         System.out.println("解密:");
  51.         String cipher = Base64.getEncoder().encodeToString(c.toByteArray());
  52.         System.out.println("输入密文" + cipher);
  53.         c = new BigInteger(Base64.getDecoder().decode(cipher));
  54.         System.out.println("输入n:" + nn);
  55.         System.out.println("输入私钥d:" + dd);
  56.         n = new BigInteger(Base64.getDecoder().decode(nn.getBytes()));
  57.         d = new BigInteger(Base64.getDecoder().decode(dd.getBytes()));
  58.         BigInteger m = c.modPow(d, n);
  59.         System.out.println("得到明文:");
  60.         System.out.println(new String(Base64.getDecoder().decode(m.toByteArray()), "UTF-8"));
  61.         
  62.     }
  63. }
复制代码


RSATolls.java
  1. package RSAEncryptionAlgorithm;

  2. import java.math.BigInteger;

  3. public class RSATolls {
  4.     //求最大公因数
  5.     public static BigInteger GetGcd(BigInteger n, BigInteger u) {
  6.         BigInteger n1, n2;
  7.         n1 = n;
  8.         n2 = u;
  9.         while (true) {
  10.             //q = BigInteger.DivRem(n1, n2, out r);
  11.             BigInteger[] c = n1.divideAndRemainder(n2);
  12.             if (!c[1].equals(BigInteger.ZERO)) {
  13.                 n1 = n2;
  14.                 n2 = c[1];
  15.             } else
  16.                 break;
  17.         }
  18.         return n2;
  19.     }

  20.     //求模逆
  21.     public static BigInteger GetModInv(BigInteger value, BigInteger modulus) {
  22.         BigInteger n1, n2, b1 = BigInteger.ZERO, b2 = BigInteger.ONE, t;
  23.         n1 = modulus;
  24.         n2 = value;
  25.         while (true) {
  26.             BigInteger[] c = n1.divideAndRemainder(n2);
  27.             if (!c[1].equals(BigInteger.ZERO)) {
  28.                 n1 = n2;
  29.                 n2 = c[1];
  30.                 t = b2;
  31.                 b2 = b1.subtract(c[0].multiply(b2));
  32.                 b1 = t;
  33.             } else if (!n2.equals(BigInteger.ONE)) {
  34.                 b2 = modulus.add(new BigInteger("-1"));
  35.                 break;
  36.             } else {
  37.                 break;
  38.             }
  39.         }
  40.         if (b2.equals(modulus.add(new BigInteger("-1")))) {
  41.             return new BigInteger("-1");
  42.         }
  43.         while (b2.compareTo(BigInteger.ZERO) == -1) {
  44.             b2 = b2.add(modulus);
  45.         }
  46.         return b2.remainder(modulus);
  47.     }
  48. }
复制代码


运行结果:


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

8

主题

20

帖子

92

积分

注册会员

Rank: 2

积分
92
 楼主| 发表于 2022-6-2 17:08:44 | 显示全部楼层

RSA数字签名

1. RSA数字签名算法
   RSA数字签名算法的过程为:A对明文m用解密变换作: sº Dk (m)=md mod n,其中d,n为A的私人密钥,只有A才知道它;
B收到A的签名后,用A的公钥和加密变换得到明文,因: Ek(s)= Ek(Dk (m))= (md)e mod n,又 deº1 mod j(n)即de=lj(n)+1,根据欧拉定理mj(n)=1 mod n,所以Ek(s)=mlj(n)+1=[mj(n)]em=m mod n。若明文m和签名s一起送给用户B,B可以确信信息确实是A发送的。同时A也不能否认送给这个信息,因为除了A本人外,其他任何人都无法由明文m产生s.

  1. import java.security.KeyFactory;
  2. import java.security.KeyPair;
  3. import java.security.KeyPairGenerator;
  4. import java.security.NoSuchAlgorithmException;
  5. import java.security.PrivateKey;
  6. import java.security.PublicKey;
  7. import java.security.Signature;
  8. import java.security.spec.PKCS8EncodedKeySpec;
  9. import java.security.spec.X509EncodedKeySpec;


  10. public class JdkSignatureRsaUtils {
  11.     public static final String RSA = "RSA";
  12.     public static final String MD5withRSA = "MD5withRSA";

  13.     // 初始化密钥对
  14.     public static KeyPair initKey() {
  15.         try {
  16.             KeyPairGenerator generator = KeyPairGenerator.getInstance(RSA);
  17.             // 512 -65536 && 64 的倍数
  18.             generator.initialize(1024);
  19.             return generator.generateKeyPair();
  20.         } catch (NoSuchAlgorithmException e) {
  21.             throw new RuntimeException(e);
  22.         }
  23.     }

  24.     // 获取公钥
  25.     public static byte[] getPublicKey(KeyPair keyPair) {
  26.         byte[] bytes = keyPair.getPublic().getEncoded();
  27.         return bytes;
  28.     }

  29.     // 获取公钥
  30.     public static String getPublicKeyStr(KeyPair keyPair) {
  31.         byte[] bytes = keyPair.getPublic().getEncoded();
  32.         return encodeHex(bytes);
  33.     }

  34.     // 获取私钥
  35.     public static byte[] getPrivateKey(KeyPair keyPair) {
  36.         byte[] bytes = keyPair.getPrivate().getEncoded();
  37.         return bytes;
  38.     }

  39.     // 获取私钥
  40.     public static String getPrivateKeyStr(KeyPair keyPair) {
  41.         byte[] bytes = keyPair.getPrivate().getEncoded();
  42.         return encodeHex(bytes);
  43.     }

  44.     // 签名
  45.     public static byte[] sign(byte[] data, byte[] privateKey, String type) {
  46.         try {
  47.             // 还原使用
  48.             PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey);
  49.             KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  50.             PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
  51.             // 1、实例化Signature
  52.             Signature signature = Signature.getInstance(type);
  53.             // 2、初始化Signature
  54.             signature.initSign(priKey);
  55.             // 3、更新数据
  56.             signature.update(data);
  57.             // 4、签名
  58.             return signature.sign();
  59.         } catch (Exception e) {
  60.             throw new RuntimeException(e);
  61.         }
  62.     }

  63.     // 验证
  64.     public static boolean verify(byte[] data, byte[] publicKey, byte[] sign, String type) {
  65.         try {
  66.             X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
  67.             KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  68.             PublicKey pubKey = keyFactory.generatePublic(keySpec);
  69.             // 1、实例化Signature
  70.             Signature signature = Signature.getInstance(type);
  71.             // 2、初始化Signature
  72.             signature.initVerify(pubKey);
  73.             // 3、更新数据
  74.             signature.update(data);
  75.             // 4、签名
  76.             return signature.verify(sign);
  77.         } catch (Exception e) {
  78.             throw new RuntimeException(e);
  79.         }
  80.     }

  81.     // 数据准16进制编码
  82.     public static String encodeHex(final byte[] data) {
  83.         return encodeHex(data, true);
  84.     }

  85.     // 数据转16进制编码
  86.     public static String encodeHex(final byte[] data, final boolean toLowerCase) {
  87.         final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  88.         final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  89.         final char[] toDigits = toLowerCase ? DIGITS_LOWER : DIGITS_UPPER;
  90.         final int l = data.length;
  91.         final char[] out = new char[l << 1];
  92.         // two characters form the hex value.
  93.         for (int i = 0, j = 0; i < l; i++) {
  94.             out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
  95.             out[j++] = toDigits[0x0F & data[i]];
  96.         }
  97.         return new String(out);
  98.     }

  99.     public static void main(String[] args) {
  100.         String str = "java小工匠";
  101.         byte[] data = str.getBytes();
  102.         // 初始化密钥度
  103.         KeyPair keyPair = initKey();
  104.         byte[] publicKey = getPublicKey(keyPair);
  105.         byte[] privateKey = getPrivateKey(keyPair);
  106.         // 签名
  107.         String type = MD5withRSA;
  108.         byte[] sign = sign(str.getBytes(), privateKey, type);
  109.         // 验证
  110.         boolean b = verify(data, publicKey, sign, type);
  111.         System.out.println("验证:" + b);

  112.     }
  113. }
复制代码


运行结果:







本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

8

主题

20

帖子

92

积分

注册会员

Rank: 2

积分
92
 楼主| 发表于 2022-6-2 17:16:57 | 显示全部楼层

ECC椭圆曲线加密

1. 椭圆曲线加密算法(ECC):
椭圆曲线加密算法,简称ECC,是基于椭圆曲线数学理论实现的一种非对称加密算法。相比RSA,ECC优势是可以使用更短的密钥,来实现与RSA相当或更高的安全,RSA加密算法也是一种非对称加密算法,在公开密钥加密和电子商业中RSA被广泛使用。

ECC.cpp
  1. #include "StdAfx.h"
  2. #include "ECC.h"
  3. #include <math.h>
  4. #include <sstream>

  5. //E29(4,20) G(13,23) ord(G)=37 x=25,Q(14,6)
  6. //k=6
  7. ECC::ECC(int a=4,int b=20,int p=29)
  8. {
  9.         this->mA=a;
  10.         this->mB=b;
  11.         this->mP=p;
  12.         this->getAllPoints();
  13.         this->getAllOrders();
  14. }

  15. ECC::~ECC(void)
  16. {
  17. }
  18. //计算曲线上的点
  19. void ECC::getAllPoints()
  20. {
  21.         int left,right=0;
  22.         for (int x=0;x<mP;x++)
  23.         {
  24.                 right=x*x*x+mA*x+mB;//先计算式子右边的值
  25.                 for (int y=0;y<mP;y++)//判断右边是不是左边的平方剩余
  26.                 {
  27.                         left=y*y;
  28.                         if (mod(left,mP)==mod(right,mP))//如果两边相等
  29.                         {
  30.                                 mPoints.push_back(Point(x,y));//则该点在曲线上
  31.                         }
  32.                 }
  33.         }
  34. }
  35. //计算所有生成元的阶
  36. void ECC::getAllOrders()
  37. {
  38.         for (std::vector<Point>::const_iterator it=mPoints.begin();it!=mPoints.end();it++)
  39.         {
  40.                 mGenerators.push_back(Generator(*it,getOrder(*it)));
  41.         }
  42. }
  43. int ECC::getOrder(const Point&p)
  44. {
  45.         int i=1;
  46.         Point q=add(p,p);
  47.         while(q!=p && q.isInfinity()==false)
  48.         {
  49.                 i++;
  50.                 q=add(p,q);
  51.         }
  52.         return ++i;
  53. }
  54. int ECC::ex_gcd(int a,int b,int& x,int& y)
  55. {
  56.         if(b==0)
  57.         {
  58.                 x=1;
  59.                 y=0;
  60.                 return a;
  61.         }
  62.         int ans = this->ex_gcd(b,a%b,x,y);
  63.         int tmp = x;
  64.         x = y;
  65.         y = tmp-a/b*y;
  66.         return ans;
  67. }

  68. int ECC::getInverse(int a,int p)
  69. {
  70.         int x,y;
  71.         int n = ex_gcd(a,p,x,y);
  72.         if(1%n!=0) return -1;
  73.         x*=1/n;
  74.         p = abs(p);
  75.         int ans = x%p;
  76.         if(ans<=0) ans += p;
  77.         return ans;
  78. }

  79. Point ECC::getMultiplePoint(int k,const Point& p)
  80. {
  81.         Point q(p);
  82.         for (int i=1;i<k;i++)
  83.         {
  84.                 q=add(p,q);
  85.         }
  86.         return q;
  87. }

  88. Point ECC::add(const Point& p,const Point& q)
  89. {
  90.         int lambda,m,n;//斜率lambda=m/n
  91.         int x,y;
  92.         if (p.isInfinity())//p是无穷远点P+Q=O+Q=Q
  93.         {
  94.                 return q;
  95.         }
  96.         if (q.isInfinity())//q是无穷远点P+Q=P+O=P
  97.         {
  98.                 return p;
  99.         }
  100.         if (p==q)//P=Q
  101.         {
  102.                 m=mod(3*p.X*p.X+mA,mP);
  103.                 n=mod(2*p.Y,mP);
  104.                 //n不能为0,0没有乘法逆元
  105.         }
  106.         else//P≠Q
  107.         {
  108.                 m=mod(q.Y-p.Y,mP);
  109.                 n=mod(q.X-p.X,mP);
  110.                 //n不能为0
  111.                 //如果n=0,P、Q横坐标相同,即P、Q互逆P+Q=P+(-P)=O
  112.         }
  113.         if (n==0)
  114.         {
  115.                 return Point::Infinity();
  116.         }
  117.         lambda=mod(m*getInverse(n,mP),mP);
  118.         x=mod(lambda*lambda-p.X-q.X,mP);
  119.         y=mod(lambda*(p.X-x)-p.Y,mP);
  120.         return Point(x,y);
  121. }

  122. int ECC::mod(int a,int p)
  123. {
  124.         if (a>=0)
  125.         {
  126.                 return a%p;
  127.         }
  128.         else
  129.         {
  130.                 return ((a%p)+p)%p;
  131.         }
  132. }

  133. void ECC::encrypt(const std::vector<Point> &Pm,Key& key,std::vector<Cipher> &result,int k)
  134. {       
  135.         bool flag=k<=1||k>key.getGenerator().Order;
  136.         //开始加密
  137.         for (std::vector<Point>::const_iterator it=Pm.begin();it!=Pm.end();it++)
  138.         {
  139.                 if (flag)//如果k不符合条件
  140.                 {
  141.                         k=rand()%(key.getGenerator().Order-1)+1;//随机选取整数k,满足1<k<n
  142.                 }
  143.                 Point C1=getMultiplePoint(k,key.getGenerator().Value);//C1=kP
  144.                 Point C2=add(*it,getMultiplePoint(k,key.getPublicKey()));//C2=Pm+kQ
  145.                 result.push_back(Cipher(C1,C2));//密文c=(C1,C2)
  146.         }
  147. }

  148. void ECC::encodePlainText(const char* plainText,std::vector<Point>&result)
  149. {
  150.         mDictionary=Dictionary(plainText);
  151.         while(*plainText!='\0')
  152.         {
  153.                 int index=mDictionary.getIndex(*plainText);//获取该字符在字典中的索引
  154.                 //把该字符映射到曲线上的一个点,如果字典中元素个数多于曲线上点的个数,会发生数组越界
  155.                 result.push_back(mPoints[index]);
  156.                 plainText++;
  157.         }
  158. }
  159. void ECC::decodePlainPoints(const std::vector<Point>& Pm,std::string &result)
  160. {
  161.         std::stringstream ss;
  162.         for (std::vector<Point>::const_iterator it=Pm.begin();it!=Pm.end();it++)
  163.         {
  164.                 for (unsigned int i=0;i < mPoints.size();i++)
  165.                 {
  166.                         if (mPoints[i] == *it)
  167.                         {
  168.                                 unsigned char ch = mDictionary.getChar(i);
  169.                                 ss<<ch;
  170.                                 break;
  171.                         }
  172.                 }
  173.         }
  174.         ss>>result;
  175. }
  176. void ECC::decrypt(const std::vector<Cipher>& ciphers,int x,std::vector<Point> &result)
  177. {
  178.         for (std::vector<Cipher>::const_iterator it=ciphers.begin();it!=ciphers.end();it++)
  179.         {
  180.                 Point C1R=Point(it->C1.X,-it->C1.Y);//求C1的加法逆元P+(-P)=(x,y)+(x,-y)=O
  181.                 Point Pm = add(it->C2,getMultiplePoint(x,C1R));
  182.                 result.push_back(Pm);
  183.         }
  184. }
  185. bool ECC::isPrime(int n)
  186. {
  187.         if (n<2)
  188.                 return false;
  189.         if(n==2 || n==3)
  190.                 return true;
  191.         if(n%6!=1 && n%6!=5)
  192.                 return false;
  193.         float n_sqrt=floor(sqrt((float)n));
  194.         for(int i=5;i<=n_sqrt;i+=6)
  195.         {
  196.                 if(n%i==0 || n%(i+2)==0)
  197.                         return false;
  198.         }
  199.         return true;
  200. }
  201. //g是生成元,x是私钥
  202. void ECC::genKey(Key& result,int gIndex,int x)
  203. {
  204.         int n;
  205.         Generator G;
  206.         if (gIndex<0||isPrime(mGenerators[gIndex].Order)==false)
  207.         {
  208.                 do
  209.                 {
  210.                         gIndex = rand()%mGenerators.size();//随机选取一个阶为n的生成元,在数组中的下标为index
  211.                         n=mGenerators[gIndex].Order;
  212.                 } while (isPrime(n)==false);//如果选取的生成元的阶数不是素数,就重新选取
  213.         }
  214.         else
  215.         {
  216.                 n=mGenerators[gIndex].Order;
  217.         }
  218.         G=mGenerators[gIndex];//最终选择的生成元
  219.         if (x>=n||x<=1)//传入的私钥不对
  220.         {
  221.                 x=rand()%(n-1)+1;//随机选取整数x,满足1<x<n
  222.         }
  223.         Point Q=getMultiplePoint(x,G.Value);//计算Q=xG
  224.         result = Key(G,x,Q);//生成元为mGenerators[index],公钥为Q,私钥为x
  225. }
  226. const std::vector<Generator> ECC::getGenerators()const
  227. {
  228.         return mGenerators;
  229. }
复制代码


Key.cpp
  1. #include "StdAfx.h"
  2. #include "Key.h"

  3. Key::Key(const Generator& g,int x,const Point& Q)
  4. {
  5.         this->m_g=g;
  6.         this->m_Q=Q;
  7.         this->m_x=x;
  8. }
  9. Key::Key(void)
  10. {

  11. }

  12. Key::~Key(void)
  13. {
  14. }

  15. const Point& Key::getPublicKey()const
  16. {
  17.         return m_Q;
  18. }

  19. const int Key::getPrivateKey()const
  20. {
  21.         return m_x;
  22. }
  23. const Generator& Key::getGenerator()const
  24. {
  25.         return m_g;
  26. }
复制代码


Test.cpp
  1. #include "stdafx.h"
  2. #include "ECC.h"
  3. #include <stdlib.h>
  4. #include <string>
  5. #include <iomanip>
  6. #include <vector>

  7. using namespace std;

  8. template <typename T>
  9. void print(const vector<T>& list)//打印数组内容
  10. {
  11.         for (unsigned int i=0;i<list.size();i++)
  12.         {
  13.                 if (i%4==0)
  14.                 {
  15.                         cout<<endl;
  16.                 }
  17.                 cout<<setw(3)<<setfill(' ')<<i<<"、"<<list[i]<<"\t\t";
  18.         }
  19.         cout<<endl;
  20.         cout<<"-------------------------------------------------------"<<endl;
  21. }

  22. int main()
  23. {
  24.         int a,b,p,x,k;
  25.         Key key;
  26.         cout<<"椭圆曲线方程为:"<<"y^2 = x^3 + ax + b (mod p)"<<endl;
  27.         //选取方程参数
  28. input:        cout<<"请输入a的值(a是整数,a>0):";
  29.         cin>>a;
  30.         cout<<"请输入b的值(b是整数,b>0):";
  31.         cin>>b;
  32.         cout<<"请输入p的值(p是大素数,但目前用Int32表示):";
  33.         cin>>p;
  34.         if (ECC::isPrime(p)==false)
  35.         {
  36.                 cout<<"p不是素数,请重新输入!"<<endl;
  37.                 goto input;
  38.         }
  39.         if((4*(a*a*a)+27*(b*b))%p == 0)
  40.         {//当4a^3+27b^2≠0时,是一条非奇异椭圆曲线,此时可以在E(a,b)定义一个阿贝尔群
  41.                 cout<<"输入的参数有误,请重新输入!"<<endl;
  42.                 goto input;
  43.         }
  44.         //初始化椭圆曲线方程
  45.         ECC ecc(a,b,p);
  46.         //获取所有生成元以及对应的阶
  47.         vector<Generator> generators = ecc.getGenerators();
  48.         cout<<"下面是生成元及对应的阶数:"<<endl;
  49.         print(generators);
  50.         //选择基点G
  51.         cout<<"请选择基点G(x,y)的序号:";//G=P
  52.         cin>>k;
  53.         //输入私钥
  54.         cout<<"请输入私钥(x<"<<generators[k].Order<<"):x = ";
  55.         cin>>x;
  56.         //产生公私钥对
  57.         ecc.genKey(key,k,x);
  58.         if (generators[k]!=key.getGenerator())
  59.         {
  60.                 cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl;
  61.                 cout<<"你选择的生成元为:G = "<<generators[k]<<endl;
  62.                 cout<<"该生成元的阶数为:ord(G) = "<<generators[k].Order<<",不是素数"<<endl;
  63.                 cout<<"生成元已自动变更为:G = "<<key.getGenerator()<<endl;
  64.                 cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl;
  65.         }
  66.         cout<<"生成的公钥为:Q = "<<key.getPublicKey()<<endl;
  67.         cout<<"目前的私钥为:x = "<<key.getPrivateKey()<<endl;
  68.         //输入随机数k
  69.         cout<<"请输入k的值来计算 kG,kQ+Pm,输入负数使用随机值(1<k<"<<key.getGenerator().Order<<"):k = ";
  70.         cin>>k;

  71.         vector<Point> encodedPoints;
  72.         vector<Cipher> cipheredPoints;
  73.         //将明文m编码为椭圆曲线上的点
  74.         ecc.encodePlainText("Hello,我是明文",encodedPoints);
  75.         cout<<"编码后的明文点集为:Pme = "<<endl;
  76.         print(encodedPoints);
  77.         //加密
  78.         ecc.encrypt(encodedPoints,key,cipheredPoints,k);
  79.         cout<<"加密后的密文点集为:Pc = "<<endl;
  80.         print(cipheredPoints);
  81.        
  82.         vector<Point> decryptedPoints;
  83.         string decodedText;
  84.         //解密
  85.         ecc.decrypt(cipheredPoints,key.getPrivateKey(),decryptedPoints);
  86.         cout<<"解密后的明文点集为:Pm = "<<endl;
  87.         print(decryptedPoints);
  88.         //解码明文点集,得到明文字符串
  89.         ecc.decodePlainPoints(decryptedPoints,decodedText);
  90.         cout<<"解码后的字符串明文为:"<<endl;
  91.         cout<<decodedText<<endl;
  92.         system("Pause");
  93.         return 0;
  94. }
复制代码


运行结果:



本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

教学服务系统

GMT+8, 2025-4-30 07:45 , Processed in 0.019598 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表