教学服务系统

 找回密码
 立即注册
搜索
查看: 776|回复: 4

信息计算2019级2班31号吴明霞

[复制链接]

8

主题

20

帖子

152

积分

注册会员

Rank: 2

积分
152
发表于 2022-6-1 14:17:28 | 显示全部楼层 |阅读模式
RSA的加密和签名

一、RSA加密和签名的简介
  RSA加密是一种非对称加密。可以在不直接传递密钥的情况下,完成解密;是由一对密钥来进行加解密的过程,分别称为公钥和私钥。两者之间有数学相关,该加密算法的原理就是对一极大整数做因数分解的困难性来保证安全性。通常个人保存私钥,公钥是公开的。
加密:加密是为了防止信息被泄露;
签名:签名是为了防止信息被篡改,保证数据完整性和发送方角色的可靠性和不可抵赖性。
二、加密和签名的过程
A理解为客户端,B理解为服务端,A、B分别有一对公钥和密钥。
1、加解密过程简述
  A和B进行通信加密,B要先生成一对RSA密钥,B自己持有私钥,给A公钥 —>A使用B的公钥加密要发送的内容,然后B接收到密文后通过自己的私钥解密内容。
2、签名和验签过程简述
  A给B发送消息,A先计算出消息的消息摘要,然后使用自己的私钥加密消息摘要,被加密的消息摘要就是签名.(A用自己的私钥给消息摘要加密成为签名)
  B收到消息后,也会使用和A相同的方法提取消息摘要,然后用A的公钥解密签名,并与自己计算出来的消息摘要进行比较–>如果相同则说明消息是A发送给B的,同时,A也无法否认自己发送消息给B的事实.(B使用A的公钥解密签名文件的过程,叫做"验签")
三、对签名和验签完整过程详细理解
1、签名过程:
(1)A计算消息m的消息摘要,记为h(m);
(2)A使用私钥(n,d)h(m)加密,生成签名s, s满足:s=(h(m))^d mod n;由于A是用自己的私钥对消息摘要加密,所以只用使用s的公钥才能解密该消息摘要,这样A就不可否认自己发送了该消息给B
(3) A发送消息和签名(m,s)B;
2、验签过程:
(1) B计算消息m的消息摘要(计算方式和A相同),记为h(m)
(2) B使用A的公钥(n,e)解密s,得到 H(m), H(m) = s^e mod n
(3) B比较H(m)h(m),相同才能证明验签成功



回复

使用道具 举报

8

主题

20

帖子

152

积分

注册会员

Rank: 2

积分
152
 楼主| 发表于 2022-6-1 14:33:44 | 显示全部楼层
本帖最后由 吴明霞 于 2022-6-1 16:41 编辑

四、运行代码:
RSAEncrypt
  1. package rsa;
  2. import javax.crypto.*;
  3. import java.io.*;
  4. import java.security.*;
  5. public class RSAEncrypt {
  6.     private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
  7.             '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  8.     public static void genKeyPair(String filePath) {
  9.         KeyPairGenerator keyPairGen = null;
  10.         try {
  11.             keyPairGen = KeyPairGenerator.getInstance("RSA");
  12.         } catch (NoSuchAlgorithmException e) {
  13.             e.printStackTrace();
  14.         }
  15.         keyPairGen.initialize(1024, new SecureRandom());
  16.         KeyPair keyPair = keyPairGen.generateKeyPair();
  17.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
  18.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  19.         try {
  20.             String publicKeyString = Base64.encode(publicKey.getEncoded());
  21.             String privateKeyString = Base64.encode(privateKey.getEncoded());
  22.             FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
  23.             FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
  24.             BufferedWriter pubbw = new BufferedWriter(pubfw);
  25.             BufferedWriter pribw = new BufferedWriter(prifw);
  26.             pubbw.write(publicKeyString);
  27.             pribw.write(privateKeyString);
  28.             pubbw.flush();
  29.             pubbw.close();
  30.             pubfw.close();
  31.             pribw.flush();
  32.             pribw.close();
  33.             prifw.close();
  34.         } catch (Exception e) {
  35.             e.printStackTrace();
  36.         }
  37.     }
  38.     public static String loadPublicKeyByFile(String path) throws Exception {
  39.         try {
  40.             BufferedReader br = new BufferedReader(new FileReader(path
  41.                     + "/publicKey.keystore"));
  42.             String readLine = null;
  43.             StringBuilder sb = new StringBuilder();
  44.             while ((readLine = br.readLine()) != null) {
  45.                 sb.append(readLine);
  46.             }
  47.             br.close();
  48.             return sb.toString();
  49.         } catch (IOException e) {
  50.             throw new Exception("公钥数据流读取错误");
  51.         } catch (NullPointerException e) {
  52.             throw new Exception("公钥输入流为空");
  53.         }
  54.     }
  55.     public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
  56.             throws Exception {
  57.         try {
  58.             byte[] buffer = Base64.decode(publicKeyStr);
  59.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  60.             X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
  61.             return (RSAPublicKey) keyFactory.generatePublic(keySpec);
  62.         } catch (NoSuchAlgorithmException e) {
  63.             throw new Exception("无此算法");
  64.         } catch (InvalidKeySpecException e) {
  65.             throw new Exception("公钥非法");
  66.         } catch (NullPointerException e) {
  67.             throw new Exception("公钥数据为空");
  68.         }
  69.     }
  70.     public static String loadPrivateKeyByFile(String path) throws Exception {
  71.         try {
  72.             BufferedReader br = new BufferedReader(new FileReader(path
  73.                     + "/privateKey.keystore"));
  74.             String readLine = null;
  75.             StringBuilder sb = new StringBuilder();
  76.             while ((readLine = br.readLine()) != null) {
  77.                 sb.append(readLine);
  78.             }
  79.             br.close();
  80.             return sb.toString();
  81.         } catch (IOException e) {
  82.             throw new Exception("私钥数据读取错误");
  83.         } catch (NullPointerException e) {
  84.             throw new Exception("私钥输入流为空");
  85.         }
  86.     }
  87.     public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
  88.             throws Exception {
  89.         try {
  90.             byte[] buffer = Base64.decode(privateKeyStr);
  91.             PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
  92.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  93.             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
  94.         } catch (NoSuchAlgorithmException e) {
  95.             throw new Exception("无此算法");
  96.         } catch (InvalidKeySpecException e) {
  97.             throw new Exception("私钥非法");
  98.         } catch (NullPointerException e) {
  99.             throw new Exception("私钥数据为空");
  100.         }
  101.     }
  102.     public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
  103.             throws Exception {
  104.         if (publicKey == null) {
  105.             throw new Exception("加密公钥为空, 请设置");
  106.         }
  107.         Cipher cipher = null;
  108.         try {
  109.             cipher = Cipher.getInstance("RSA");
  110.             cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  111.             byte[] output = cipher.doFinal(plainTextData);
  112.             return output;
  113.         } catch (NoSuchAlgorithmException e) {
  114.             throw new Exception("无此加密算法");
  115.         } catch (NoSuchPaddingException e) {
  116.             e.printStackTrace();
  117.             return null;
  118.         } catch (InvalidKeyException e) {
  119.             throw new Exception("加密公钥非法,请检查");
  120.         } catch (IllegalBlockSizeException e) {
  121.             throw new Exception("明文长度非法");
  122.         } catch (BadPaddingException e) {
  123.             throw new Exception("明文数据已损坏");
  124.         }
  125.     }
  126.     public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
  127.             throws Exception {
  128.         if (privateKey == null) {
  129.             throw new Exception("加密私钥为空, 请设置");
  130.         }
  131.         Cipher cipher = null;
  132.         try {
  133.             cipher = Cipher.getInstance("RSA");
  134.             cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  135.             byte[] output = cipher.doFinal(plainTextData);
  136.             return output;
  137.         } catch (NoSuchAlgorithmException e) {
  138.             throw new Exception("无此加密算法");
  139.         } catch (NoSuchPaddingException e) {
  140.             e.printStackTrace();
  141.             return null;
  142.         } catch (InvalidKeyException e) {
  143.             throw new Exception("加密私钥非法,请检查");
  144.         } catch (IllegalBlockSizeException e) {
  145.             throw new Exception("明文长度非法");
  146.         } catch (BadPaddingException e) {
  147.             throw new Exception("明文数据已损坏");
  148.         }
  149.     }
  150.     public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
  151.             throws Exception {
  152.         if (privateKey == null) {
  153.             throw new Exception("解密私钥为空, 请设置");
  154.         }
  155.         Cipher cipher = null;
  156.         try {
  157.             cipher = Cipher.getInstance("RSA");
  158.             cipher.init(Cipher.DECRYPT_MODE, privateKey);
  159.             byte[] output = cipher.doFinal(cipherData);
  160.             return output;
  161.         } catch (NoSuchAlgorithmException e) {
  162.             throw new Exception("无此解密算法");
  163.         } catch (NoSuchPaddingException e) {
  164.             e.printStackTrace();
  165.             return null;
  166.         } catch (InvalidKeyException e) {
  167.             throw new Exception("解密私钥非法,请检查");
  168.         } catch (IllegalBlockSizeException e) {
  169.             throw new Exception("密文长度非法");
  170.         } catch (BadPaddingException e) {
  171.             throw new Exception("密文数据已损坏");
  172.         }
  173.     }
  174.     public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
  175.             throws Exception {
  176.         if (publicKey == null) {
  177.             throw new Exception("解密公钥为空, 请设置");
  178.         }
  179.         Cipher cipher = null;
  180.         try {
  181.             cipher = Cipher.getInstance("RSA");
  182.             cipher.init(Cipher.DECRYPT_MODE, publicKey);
  183.             byte[] output = cipher.doFinal(cipherData);
  184.             return output;
  185.         } catch (NoSuchAlgorithmException e) {
  186.             throw new Exception("无此解密算法");
  187.         } catch (NoSuchPaddingException e) {
  188.             e.printStackTrace();
  189.             return null;
  190.         } catch (InvalidKeyException e) {
  191.             throw new Exception("解密公钥非法,请检查");
  192.         } catch (IllegalBlockSizeException e) {
  193.             throw new Exception("密文长度非法");
  194.         } catch (BadPaddingException e) {
  195.             throw new Exception("密文数据已损坏");
  196.         }
  197.     }
  198.     public static String byteArrayToString(byte[] data) {
  199.         StringBuilder stringBuilder = new StringBuilder();
  200.         for (int i = 0; i < data.length; i++) {
  201.             stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
  202.             stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
  203.             if (i < data.length - 1) {
  204.                 stringBuilder.append(' ');
  205.             }
  206.         }
  207.         return stringBuilder.toString();
  208.     }
  209. }
复制代码
回复

使用道具 举报

8

主题

20

帖子

152

积分

注册会员

Rank: 2

积分
152
 楼主| 发表于 2022-6-1 14:35:23 | 显示全部楼层
本帖最后由 吴明霞 于 2022-6-1 14:41 编辑

RSASignature
  1. package rsa;
  2. import java.security.*;
  3. public class RSASignature {
  4.     public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
  5.     public static String sign(String content, String privateKey, String encode) {
  6.         try {
  7.             PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
  8.             KeyFactory keyf = KeyFactory.getInstance("RSA");
  9.             PrivateKey priKey = keyf.generatePrivate(priPKCS8);
  10.             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
  11.             signature.initSign(priKey);
  12.             signature.update(content.getBytes(encode));
  13.             byte[] signed = signature.sign();
  14.             return Base64.encode(signed);
  15.         } catch (Exception e) {
  16.             e.printStackTrace();
  17.         }
  18.         return null;
  19.     }
  20.     public static String sign(String content, String privateKey) {
  21.         try {
  22.             PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
  23.             KeyFactory keyf = KeyFactory.getInstance("RSA");
  24.             PrivateKey priKey = keyf.generatePrivate(priPKCS8);
  25.             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
  26.             signature.initSign(priKey);
  27.             signature.update(content.getBytes());
  28.             byte[] signed = signature.sign();
  29.             return Base64.encode(signed);
  30.         } catch (Exception e) {
  31.             e.printStackTrace();
  32.         }
  33.         return null;
  34.     }
  35.     public static boolean doCheck(String content, String sign, String publicKey, String encode) {
  36.         try {
  37.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  38.             byte[] encodedKey = Base64.decode(publicKey);
  39.             PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
  40.             java.security.Signature signature = java.security.Signature
  41.                     .getInstance(SIGN_ALGORITHMS);
  42.             signature.initVerify(pubKey);
  43.             signature.update(content.getBytes(encode));
  44.             boolean bverify = signature.verify(Base64.decode(sign));
  45.             return bverify;
  46.         } catch (Exception e) {
  47.             e.printStackTrace();
  48.         }
  49.         return false;
  50.     }

  51.     public static boolean doCheck(String content, String sign, String publicKey) {
  52.         try {
  53.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  54.             byte[] encodedKey = Base64.decode(publicKey);
  55.             PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
  56.             java.security.Signature signature = java.security.Signature
  57.                     .getInstance(SIGN_ALGORITHMS);
  58.             signature.initVerify(pubKey);
  59.             signature.update(content.getBytes());
  60.             boolean bverify = signature.verify(Base64.decode(sign));
  61.             return bverify;
  62.         } catch (Exception e) {
  63.             e.printStackTrace();
  64.         }
  65.         return false;
  66.     }
  67. }
复制代码

MianTest
  1. package rsa;

  2. public class MainTest {

  3.     public static void main(String[] args) throws Exception {
  4.         String filepath = "D:/密码学/";

  5.         RSAEncrypt.genKeyPair(filepath);

  6.         System.out.println("--------------公钥加密私钥解密过程-------------------");
  7.         String plainText = "wumingxia";
  8.         // 公钥加密过程,得到加密后的数据
  9.         byte[] cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), plainText.getBytes());
  10.         // 对加密数据进行编码处理,得到加密后的字符串
  11.         String cipher = Base64.encode(cipherData);
  12.         // 私钥解密过程
  13.         byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), Base64.decode(cipher));
  14.         String restr = new String(res);
  15.         System.out.println("原文:" + plainText);
  16.         System.out.println("加密:" + cipher);
  17.         System.out.println("解密:" + restr);
  18.         System.out.println();

  19.         System.out.println("--------------私钥加密公钥解密过程-------------------");
  20.         plainText = "今天天气很好";
  21.         //私钥加密过程
  22.         cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), plainText.getBytes());
  23.         cipher = Base64.encode(cipherData);
  24.         //公钥解密过程
  25.         res = RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), Base64.decode(cipher));
  26.         restr = new String(res);
  27.         System.out.println("原文:" + plainText);
  28.         System.out.println("加密:" + cipher);
  29.         System.out.println("解密:" + restr);
  30.         System.out.println();

  31.         System.out.println("---------------私钥签名过程------------------");
  32.         String content = "今天天气很好";
  33.         String signstr = RSASignature.sign(content, RSAEncrypt.loadPrivateKeyByFile(filepath));
  34.         System.out.println("签名原串:" + content);
  35.         System.out.println("签名串:" + signstr);
  36.         System.out.println();

  37.         System.out.println("---------------公钥校验签名------------------");
  38.         System.out.println("签名原串:" + content);
  39.         System.out.println("签名串:" + signstr);

  40.         System.out.println("验签结果:" + RSASignature.doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath)));
  41.         System.out.println();

  42.     }
  43. }
复制代码
五、运行结果:





本帖子中包含更多资源

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

x
回复

使用道具 举报

8

主题

20

帖子

152

积分

注册会员

Rank: 2

积分
152
 楼主| 发表于 2022-6-1 16:38:52 | 显示全部楼层
本帖最后由 吴明霞 于 2022-6-1 16:48 编辑

ECC椭圆曲线的加密
一、ECC算法的简介     
  椭圆曲线加密算法,简称RCC,是基于椭圆曲线数学理论实现的一种非对称加密算法。相比RSA,ECC优势是可以使用更短的密钥,来实现与RSA相当或更高的安全,RSA加密算法也是一种非对称加密算法,在公开密钥加密和电子商业中RSA被广泛使用。
二、ECC加密原理
1、用户A选定一条适合加密的椭圆曲线Ep(a,b)(如:y2=x3+ax+b),并取椭圆曲线上一点,作为基点G。
2、用户A选择一个私有密钥k,并生成公开密钥K=kG。
3、用户A将Ep(a,b)和点K,G传给用户B。
4、用户B接到信息后 ,将待传输的明文编码到Ep(a,b)上一点M,并产生一个随机整数r(r<n)。
5、用户B计算点C1=M+rK;C2=rG。
6、用户B将C1、C2传给用户A。
7、用户A接到信息后,计算C1-kC2,结果就是点M。因为 C1-kC2=M+rK-k(rG)=M+rK-r(kG)=M;再对点M进行解码就可以得到明文。




回复

使用道具 举报

8

主题

20

帖子

152

积分

注册会员

Rank: 2

积分
152
 楼主| 发表于 2022-6-1 16:40:06 | 显示全部楼层
本帖最后由 吴明霞 于 2022-6-1 16:48 编辑

三、运行代码:
  1. import it.unisa.dia.gas.jpbc.*;
  2. import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;
  3. import java.io.*;
  4. import java.math.BigInteger;
  5. import java.util.*;
  6. public class ECC {
  7.     public static Pairing initPairing(String parameter) {
  8.         System.out.println("系统正在导入椭圆曲线的相关参数……");
  9.         Pairing pairing = PairingFactory.getPairing(parameter);
  10.         System.out.println("系统已经导入完毕");
  11.         return pairing;
  12.     }
  13.     public static Field initG_1(Pairing pairing) {
  14.         System.out.println("系统正在产生椭圆曲线……");
  15.         Field G1 = pairing.getG1();
  16.         System.out.println("系统已经产生椭圆曲线");
  17.         return G1;
  18.     }
  19.     public static Element initG(Field G1) {
  20.         System.out.println("系统正在挑选生成元点G……");
  21.         Element G = G1.newRandomElement().getImmutable();
  22.         System.out.println("系统已经挑选好生成元点G");
  23.         return G;
  24.     }
  25.     public static Element initP_t(Field G1) {
  26.         System.out.println("系统正在挑选随机点P_t……");
  27.         Element P_t = G1.newRandomElement().getImmutable();
  28.         System.out.println("系统已经挑选好随机点P_t");
  29.         return P_t;
  30.     }
  31.     public static void KeyGenerator(Element G,Field G_1) throws Exception {
  32.         Random random = new Random();
  33.         BigInteger n_b = new BigInteger(160, 160,random);//大整数做为私钥1
  34.         Element P_b = G.duplicate().mul(n_b);
  35.         byte[] b = P_b.toCanonicalRepresentation();
  36.         System.out.println("\n");
  37.         String path = new File("").getCanonicalPath();
  38.         out(path + "\\privateKey.key", n_b.toString());
  39.         out(path + "\\publicKey.key",
  40.         Base64.getEncoder().encodeToString(P_b.toCanonicalRepresentation()) + ",,,,,," +
  41.         Base64.getEncoder().encodeToString(G.toCanonicalRepresentation()));
  42.         System.out.println("你的私钥存放在:" + path + "\\privateKey.key");
  43.         System.out.println("你的公钥存放在:" + path + "\\publicKey.key");
  44.     }
  45.     public static String encrypt(Element P_b, String data, BigInteger k, Element P_t, Element G){
  46.       try {
  47.             byte[] datasource=data.getBytes("utf8");
  48.             String CArray = "A";
  49.             Element P_1 = G.duplicate().getImmutable().mul(k);
  50.             System.out.println("加密过程当中计算出的P_1:"+ P_1);
  51.             Element P_2 = P_b.duplicate().getImmutable().mul(k);
  52.             System.out.println("加密过程当中计算出的P_2:"+ P_2);
  53.             Element P_end = P_t.add(P_2);
  54.             System.out.println("加密过程当中计算出的P_end:"+ P_end);
  55.             String[] p_txy = P_t.toString().split(",");
  56.             BigInteger p_tx = new BigInteger(p_txy[0]);
  57.             BigInteger p_ty = new BigInteger(p_txy[1]);
  58.             for(int i=0;i<datasource.length;i++)
  59.             {
  60.                 BigInteger M = new BigInteger(datasource[i]+"");
  61.                 BigInteger C_mid = M.multiply(p_tx).add(p_ty);
  62.                 CArray = CArray +","+C_mid.toString();
  63.             }
  64.             CArray = CArray + ",,"+
  65.             Base64.getEncoder().encodeToString(P_1.toCanonicalRepresentation())+",,"+
  66.             Base64.getEncoder().encodeToString(P_end.toCanonicalRepresentation());
  67.             return Base64.getEncoder().encodeToString(CArray.getBytes());
  68.         }
  69.         catch(Exception ex) {
  70.             ex.printStackTrace();
  71.         }
  72.         return null;
  73.     }
  74.     public static String decrypt(BigInteger Privatekey, String data, Field G_1,Element G) {
  75.       try {
  76.             String ciphertext= new String(Base64.getDecoder().decode(data),"utf8");
  77.             String[] CS=ciphertext.split(",,");
  78.             String m = "";
  79.             Element P_end = G_1.newElementFromBytes(Base64.getDecoder().decode(CS[2]));
  80.             Element P_1 = G_1.newElementFromBytes(Base64.getDecoder().decode(CS[1]));
  81.             Element P_t = P_end.getImmutable().sub(P_1.getImmutable().mul(Privatekey));
  82.             System.out.println("解密过程当中计算出的P_t:"+ P_t);
  83.             String[] p_txy = P_t.toString().split(",");
  84.             BigInteger p_tx = new BigInteger(p_txy[0]);
  85.             BigInteger p_ty = new BigInteger(p_txy[1]);
  86.             String[] Plaintext = CS[0].split(",");
  87.             for(int i=1;i<Plaintext.length;i++){
  88.                 BigInteger C = new BigInteger(Plaintext[i]);
  89.                 BigInteger M_mid = C.subtract(p_ty).divide(p_tx);
  90.                 m = m+new String(M_mid.toByteArray(),"GBK");;
  91.             }
  92.             return m;
  93.         }
  94.         catch(Exception ex) {
  95.             ex.printStackTrace();
  96.         }
  97.         return null;
  98.     }
  99.     public static void out(String path, String val) {
  100.        try {
  101.             val = Base64.getEncoder().encodeToString(val.getBytes("utf8"));
  102.             FileWriter fw = new FileWriter(path);
  103.             BufferedWriter bw = new BufferedWriter(fw);
  104.             PrintWriter outs = new PrintWriter(bw);
  105.             outs.println(val);
  106.             outs.flush();
  107.             outs.close();
  108.         } catch (Exception ex) {
  109.             ex.printStackTrace();
  110.         }
  111.     }
  112.     public static Element readPk(String path, Field G_1){
  113.         Element sk = null;
  114.         try {
  115.             File f=new File(path);
  116.             FileReader fr=new FileReader(f);
  117.             BufferedReader br=new BufferedReader(fr);
  118.             String line=null;
  119.             StringBuffer sb=new StringBuffer();
  120.             while((line=br.readLine())!=null) {
  121.                 byte[] b = Base64.getDecoder().decode(line);
  122.                 String[] key = new String(b).split(",,,,,,");
  123.                 byte [] a = Base64.getDecoder().decode(key[0]);
  124.                 System.out.println("\n");
  125.                 if(key.length == 2){
  126.                     sk = G_1.newElementFromBytes(a);
  127.                 } else{
  128.                     throw new Exception("文件错误");
  129.                 }
  130.             }
  131.             br.close();
  132.             return sk;
  133.         }
  134.         catch(Exception ex)
  135.         {
  136.             ex.printStackTrace(); }
  137.         return sk;
  138.     }
  139. public static BigInteger readSk(String path, Field G_1){
  140.         BigInteger sk = null;
  141.         try {
  142.             File f=new File(path);
  143.             FileReader fr=new FileReader(f);
  144.             BufferedReader br=new BufferedReader(fr);
  145.             String line=null;
  146.             StringBuffer sb=new StringBuffer();
  147.             while((line=br.readLine())!=null) {
  148.                 byte[] b = Base64.getDecoder().decode(line);
  149.                 String[] key = new String(b).split(",,,,,,");
  150.                 if (key.length == 1) {
  151.                     sk = new BigInteger(key[0]);
  152.                 }else{
  153.                     throw new Exception("文件错误");
  154.                 }
  155.             }
  156.             br.close();
  157.             return sk;
  158.         }
  159.         catch(Exception ex)
  160.         {
  161.             ex.printStackTrace();
  162.         }
  163.         return sk;
  164.     }
  165. public static void main(String[] args) {
  166.      try {
  167.             BigInteger k = new BigInteger(10, new Random());
  168.             Pairing pairing = initPairing("C:\\Users\\89763\\Desktop\\a.properties");
  169.             Field G_1 = initG_1(pairing);
  170.             Element G = initG(G_1);
  171.             Element P_t = initP_t(G_1);
  172.             KeyGenerator(G,G_1);
  173.             Scanner sc = new Scanner(System.in);
  174.             String str = "";
  175.             sc.useDelimiter("\n");
  176.             System.out.print("\n"+"请输入公钥地址按回车结束:");
  177.             if (sc.hasNext()) {
  178.                 str = sc.next();
  179.             }
  180.             Element publicKey = readPk(str.substring(0, str.length()-1), G_1);
  181.             System.out.print("\n"+"请输入须要加密的文字按回车结束:");
  182.             if (sc.hasNext()) {
  183.                 str = sc.next();
  184.             }
  185.             String c = encrypt(publicKey, str, k, P_t, G);
  186.             System.out.println("\n"+"加密结果:" + c+"\n");
  187.             System.out.print("请输入私钥地址按回车可对密文数据进行解密:");
  188.             if (sc.hasNext()) {
  189.                 str = sc.next();}
  190.             BigInteger privateKey = readSk(str.substring(0, str.length()-1 ), G_1);
  191.             String m = decrypt(privateKey, c, G_1, G);
  192.             System.out.println("\n"+"解密明文:" + m+"\n");
  193.             sc.close();
  194.         } catch (Exception ex) {
  195.             ex.printStackTrace();
  196.         }
  197.     }
  198. }
复制代码


回复

使用道具 举报

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

本版积分规则

教学服务系统

GMT+8, 2025-4-30 08:06 , Processed in 0.015656 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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