教学服务系统

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

信息计算2019级1班28号李舫

[复制链接]

8

主题

18

帖子

84

积分

注册会员

Rank: 2

积分
84
发表于 2022-5-3 19:12:18 | 显示全部楼层 |阅读模式

本帖子中包含更多资源

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

x
回复

使用道具 举报

8

主题

18

帖子

84

积分

注册会员

Rank: 2

积分
84
 楼主| 发表于 2022-5-3 23:46:04 | 显示全部楼层
运行截图

App.java
  1. import java.math.BigInteger;
  2. import java.util.ArrayList;
  3. import java.util.Scanner;

  4. public class App {
  5.         static BigInteger x, y;

  6.         public static boolean fun(BigInteger x, BigInteger y) {
  7.                 BigInteger t;
  8.                 while (!(y.equals(new BigInteger("0")))) {
  9.                         t = x;
  10.                         x = y;
  11.                         y = t.mod(y);
  12.                 }
  13.                 if (x.equals(new BigInteger("1")))
  14.                         return false;
  15.                 else
  16.                         return true;
  17.         }

  18.         public static BigInteger siyue(BigInteger a, BigInteger b) {
  19.                 BigInteger temp;
  20.                 if (b.equals(new BigInteger("0"))) {
  21.                         x = new BigInteger("1");
  22.                         y = new BigInteger("0");
  23.                         return x;
  24.                 }
  25.                 siyue(b, a.mod(b));
  26.                 temp = x;
  27.                 x = y;
  28.                 y = temp.subtract((a.divide(b).multiply(y)));
  29.                 return x;
  30.         }

  31.         public static double entropy(String mess) {
  32.                 ArrayList<Node> jieguo = new ArrayList<Node>();
  33.                 jieguo.clear();
  34.                 double num = mess.length();
  35.                 for (int i = 0; i < num; i++) {
  36.                         boolean flag_exit = true;
  37.                         for (int j = 0; j < jieguo.size(); j++) {
  38.                                 if (jieguo.get(j).getalpha() == mess.charAt(i)) {
  39.                                         flag_exit = false;
  40.                                         jieguo.get(j).setp(jieguo.get(j).getp() + 1 / num);
  41.                                 }
  42.                         }
  43.                         if (flag_exit)
  44.                                 jieguo.add(new Node(1 / num, mess.charAt(i)));
  45.                 }
  46.                 /** 计算熵 */
  47.                 double entropy = 0;
  48.                 for (int i = 0; i < jieguo.size(); i++) {
  49.                         double p1 = jieguo.get(i).getp();
  50.                         entropy += (-p1 * (Math.log(p1) / Math.log(2)));
  51.                 }
  52.                 return entropy;
  53.         }

  54.         public static void main(String[] args) {
  55.                 BigInteger p = null;
  56.                 BigInteger e, d, n, t, c;
  57.                 BigInteger q = null;
  58.                 for (int i = 0; i < 2; i++) {
  59.                         int numDigits;
  60.                         Prime pri = new Prime();
  61.                         try {
  62.                                 numDigits = Integer.parseInt("15");
  63.                         } catch (Exception e1) {
  64.                                 numDigits = 128;
  65.                         }
  66.                         BigInteger start = pri.bigRandom(numDigits);
  67.                         BigInteger big = pri.nextPrime(start);
  68.                         if (i == 0)
  69.                                 p = big;
  70.                         else
  71.                                 q = big;
  72.                 }
  73.                 try (Scanner input = new Scanner(System.in)) {
  74.             n = p.multiply(q);
  75.             t = p.subtract(new BigInteger("1")).multiply(
  76.                             q.subtract(new BigInteger("1")));
  77.             int numDigits;
  78.             Prime pri = new Prime();
  79.             try {
  80.                     numDigits = Integer.parseInt("15");
  81.             } catch (Exception e1) {
  82.                     numDigits = 128;
  83.             }
  84.             BigInteger start = pri.bigRandom(numDigits);
  85.             BigInteger big = pri.nextPrime(start);
  86.             e = big;
  87.             while (e.compareTo(t) == 1 || fun(e, t)) {
  88.                     System.out.println("e不合要求,请重新产生" + (e.compareTo(t) == 1)
  89.                                     + fun(e, t));
  90.                     pri = new Prime();
  91.                     try {
  92.                             numDigits = Integer.parseInt("15");
  93.                     } catch (Exception e1) {
  94.                             numDigits = 128;
  95.                     }
  96.                     start = pri.bigRandom(numDigits);
  97.                     big = pri.nextPrime(start);
  98.                     e = big;
  99.             }
  100.             // 求出私钥d
  101.             d = siyue(e, t);
  102.             System.out.println("由计算机随机产生2个素数p,q,分别如下:");
  103.             System.out.println(p);
  104.             System.out.println(q);
  105.             System.out.println("计算得到的n:");
  106.             System.out.println(n);
  107.             System.out.println("计算得到的t:");
  108.             System.out.println(t);
  109.             System.out.println("随机产生的公钥:");
  110.             System.out.println(e);
  111.             System.out.println("由扩展的欧几里德算法求得私钥:");
  112.             System.out.println(d);
  113.             while (true) {
  114.                     System.out.println("请输入明文:");
  115.                     String mess = input.nextLine();
  116.                     //
  117.                     BigInteger m = new BigInteger(mess.getBytes());// 把字串转成一个BigInteger对象
  118.                     System.out.println("明文的大整数表示形式:" + m);
  119.                     /** 调用函数计算信息,统计信息 */
  120.                     mess = m.toString();
  121.                     System.out.println("计算得明文熵:" + entropy(mess));
  122.                     // 修改第一位,+1
  123.                     c = m.modPow(e, n);// JAVA中的方法
  124.                     System.out.println("密文的大整数表示形式:" + c);
  125.                     System.out.println("计算得密文熵:" + entropy(c.toString()));
  126.                     System.out.println("密文的字符串表示形式:" + new String(c.toByteArray()));
  127.                     m = c.modPow(d, n);
  128.                     System.out.println("解密得到明文的大整数表示形式:" + c);
  129.                     String str = new String(m.toByteArray());// 把返回的结果还原成一个字串
  130.                     System.out.println("解密得到明文为:" + str);
  131.             }
  132.         }
  133.         }
  134. }
复制代码
Prime.java
  1. import java.math.BigInteger;

  2. public class Prime {
  3.         public boolean sushu(double n) {
  4.                 // 判断素数
  5.                 boolean isPrime = true;
  6.                 // 如果n大于2 继续判断 否则 isPrime的值不变 2素数
  7.                 if (n > 2) {
  8.                         // 如果n是大于2的偶数 认定不是素数 修改变量值为false
  9.                         if (n % 2 == 0) {
  10.                                 isPrime = false;
  11.                         } else {
  12.                                 // 循环判断如果找到一个可以整除的数 则判定不是素数跳出循环 因为是判断奇数 因此 2 4 6 ...?
  13.                                 // 不用考虑 循环递增2 即?3 5 7 ...
  14.                                 for (int i = 3; i <= (int) Math.sqrt(n); i += 2) {
  15.                                         if (n % i == 0) {
  16.                                                 isPrime = false;
  17.                                                 break;
  18.                                         }
  19.                                 }
  20.                         }

  21.                 }
  22.                 return isPrime;
  23.         }

  24.         private static final BigInteger ZERO = BigInteger.ZERO;
  25.         private static final BigInteger ONE = BigInteger.ONE;
  26.         private static final BigInteger TWO = new BigInteger("2");
  27.         private static final int ERR_VAL = 100;

  28.         public BigInteger nextPrime(BigInteger start) {
  29.                 // 产生一个比给定大整数 start 大的素数,错误率低于 1/2 的 ERR_VAL 次方
  30.                 if (isEven(start))
  31.                         start = start.add(ONE);
  32.                 else
  33.                         start = start.add(TWO);
  34.                 if (start.isProbablePrime(ERR_VAL))
  35.                         return (start);
  36.                 else
  37.                         // 采用递归方式(递归的层数会是个天文数字吗?)
  38.                         return (nextPrime(start));
  39.         }

  40.         private static boolean isEven(BigInteger n) {
  41.                 // 测试一个大整数是否为偶数
  42.                 return (n.mod(TWO).equals(ZERO));
  43.         }

  44.         public BigInteger bigRandom(int numDigits) {
  45.                 // 产生一个随机大整数,各位上的数字都是随机产生的,首位不为 0
  46.                 StringBuffer s = new StringBuffer("");
  47.                 for (int i = 0; i < numDigits; i++)
  48.                         if (i == 0)
  49.                                 s.append(randomDigit(false));
  50.                         else
  51.                                 s.append(randomDigit(true));
  52.                 return (new BigInteger(s.toString()));
  53.         }

  54.         private StringBuffer randomDigit(boolean isZeroOK) {
  55.                 // 产生一个随机的数字(字符串形式的),isZeroOK 决定这个数字是否可以为 0
  56.                 int index;
  57.                 if (isZeroOK)
  58.                         index = (int) Math.floor(Math.random() * 10);
  59.                 else
  60.                         index = 1 + (int) Math.floor(Math.random() * 9);
  61.                 return (digits[index]);
  62.         }

  63.         private static StringBuffer[] digits = { new StringBuffer("0"),
  64.                         new StringBuffer("1"), new StringBuffer("2"),
  65.                         new StringBuffer("3"), new StringBuffer("4"),
  66.                         new StringBuffer("5"), new StringBuffer("6"),
  67.                         new StringBuffer("7"), new StringBuffer("8"), new StringBuffer("9") };

  68.         public static void main(String[] args) {

  69.         }
  70. }
复制代码
Node.java
  1. public class Node {
  2.         private double p;// 记录概率
  3.         private char alpha;// 记录对应的字母

  4.         public Node(double p, char alpha) {
  5.                 this.p = p;
  6.                 this.alpha = alpha;
  7.         }

  8.         public void setp(double p) {
  9.                 this.p = p;
  10.         }

  11.         public void setalpha(char a) {
  12.                 this.alpha = a;
  13.         }

  14.         public double getp() {
  15.                 return p;
  16.         }

  17.         public char getalpha() {
  18.                 return alpha;
  19.         }
  20. }
复制代码

本帖子中包含更多资源

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

x
回复

使用道具 举报

8

主题

18

帖子

84

积分

注册会员

Rank: 2

积分
84
 楼主| 发表于 2022-6-2 16:47:52 | 显示全部楼层


  1. import javax.crypto.Cipher;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.security.*;
  5. import java.security.cert.CertificateFactory;
  6. import java.security.cert.X509Certificate;
  7. import java.security.interfaces.ECPrivateKey;
  8. import java.security.interfaces.ECPublicKey;
  9. import java.util.Base64;

  10. public class EccUtils {
  11.     /**
  12.      * @see org.bouncycastle.jcajce.provider.asymmetric.ec.KeyPairGeneratorSpi.ecParameters (line #173)
  13.      * 192, 224, 239, 256, 384, 521
  14.      * */
  15.     private final static int KEY_SIZE = 256;//bit
  16.     private final static String SIGNATURE = "SHA256withECDSA";

  17.     static {
  18.         Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  19.     }

  20.     private static void printProvider() {
  21.         Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
  22.         for (Provider.Service service : provider.getServices()) {
  23.             System.out.println(service.getType() + ": "
  24.                     + service.getAlgorithm());
  25.         }
  26.     }

  27.     public static void main(String[] args) {
  28.         try {
  29.             KeyPair keyPair = getKeyPair();
  30.             ECPublicKey pubKey = (ECPublicKey) keyPair.getPublic();
  31.             ECPrivateKey priKey = (ECPrivateKey) keyPair.getPrivate();
  32.             //System.out.println("[pubKey]:\n" + getPublicKey(keyPair));
  33.             //System.out.println("[priKey]:\n" + getPrivateKey(keyPair));

  34.             //测试文本
  35.             String content = "abcdefg";

  36.             //加密
  37.             byte[] cipherTxt = encrypt(content.getBytes(), pubKey);
  38.             //解密
  39.             byte[] clearTxt = decrypt(cipherTxt, priKey);
  40.             //打印
  41.             System.out.println("content:" + content);
  42.             System.out.println("cipherTxt["+cipherTxt.length+"]:" + new String(cipherTxt));
  43.             System.out.println("clearTxt:" + new String(clearTxt));

  44.             //签名
  45.             byte[] sign = sign(content, priKey);
  46.             //验签
  47.             boolean ret = verify(content, sign, pubKey);
  48.             //打印
  49.             System.out.println("content:" + content);
  50.             System.out.println("sign["+sign.length+"]:" + new String(sign));
  51.             System.out.println("verify:" + ret);

  52.         } catch (Exception e) {
  53.             e.printStackTrace();
  54.             System.out.println("[main]-Exception:" + e.toString());
  55.         }
  56.     }

  57.     //生成秘钥对
  58.     public static KeyPair getKeyPair() throws Exception {
  59.         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");//BouncyCastle
  60.         keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
  61.         KeyPair keyPair = keyPairGenerator.generateKeyPair();
  62.         return keyPair;
  63.     }

  64.     //获取公钥(Base64编码)
  65.     public static String getPublicKey(KeyPair keyPair) {
  66.         ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
  67.         byte[] bytes = publicKey.getEncoded();
  68.         return Base64.getEncoder().encodeToString(bytes);
  69.     }

  70.     //获取私钥(Base64编码)
  71.     public static String getPrivateKey(KeyPair keyPair) {
  72.         ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
  73.         byte[] bytes = privateKey.getEncoded();
  74.         return Base64.getEncoder().encodeToString(bytes);
  75.     }

  76.     //公钥加密
  77.     public static byte[] encrypt(byte[] content, ECPublicKey pubKey) throws Exception {
  78.         Cipher cipher = Cipher.getInstance("ECIES", "BC");
  79.         cipher.init(Cipher.ENCRYPT_MODE, pubKey);
  80.         return cipher.doFinal(content);
  81.     }

  82.     //私钥解密
  83.     public static byte[] decrypt(byte[] content, ECPrivateKey priKey) throws Exception {
  84.         Cipher cipher = Cipher.getInstance("ECIES", "BC");
  85.         cipher.init(Cipher.DECRYPT_MODE, priKey);
  86.         return cipher.doFinal(content);
  87.     }

  88.     //私钥签名
  89.     public static byte[] sign(String content, ECPrivateKey priKey) throws Exception {
  90.         //这里可以从证书中解析出签名算法名称
  91.         //Signature signature = Signature.getInstance(getSigAlgName(pubCert));
  92.         Signature signature = Signature.getInstance(SIGNATURE);//"SHA256withECDSA"
  93.         signature.initSign(priKey);
  94.         signature.update(content.getBytes());
  95.         return signature.sign();
  96.     }

  97.     //公钥验签
  98.     public static boolean verify(String content, byte[] sign, ECPublicKey pubKey) throws Exception {
  99.         //这里可以从证书中解析出签名算法名称
  100.         //Signature signature = Signature.getInstance(getSigAlgName(priCert));
  101.         Signature signature = Signature.getInstance(SIGNATURE);//"SHA256withECDSA"
  102.         signature.initVerify(pubKey);
  103.         signature.update(content.getBytes());
  104.         return signature.verify(sign);
  105.     }

  106.     /**
  107.      * 解析证书的签名算法,单独一本公钥或者私钥是无法解析的,证书的内容远不止公钥或者私钥
  108.      * */
  109.     private static String getSigAlgName(File certFile) throws Exception {
  110.         CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
  111.         X509Certificate x509Certificate = (X509Certificate) cf.generateCertificate(new FileInputStream(certFile));
  112.         return x509Certificate.getSigAlgName();
  113.     }
  114. }
复制代码
回复

使用道具 举报

8

主题

18

帖子

84

积分

注册会员

Rank: 2

积分
84
 楼主| 发表于 2022-6-2 16:48:11 | 显示全部楼层


  1. import javax.crypto.Cipher;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.security.*;
  5. import java.security.cert.CertificateFactory;
  6. import java.security.cert.X509Certificate;
  7. import java.security.interfaces.ECPrivateKey;
  8. import java.security.interfaces.ECPublicKey;
  9. import java.util.Base64;

  10. public class EccUtils {
  11.     /**
  12.      * @see org.bouncycastle.jcajce.provider.asymmetric.ec.KeyPairGeneratorSpi.ecParameters (line #173)
  13.      * 192, 224, 239, 256, 384, 521
  14.      * */
  15.     private final static int KEY_SIZE = 256;//bit
  16.     private final static String SIGNATURE = "SHA256withECDSA";

  17.     static {
  18.         Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  19.     }

  20.     private static void printProvider() {
  21.         Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
  22.         for (Provider.Service service : provider.getServices()) {
  23.             System.out.println(service.getType() + ": "
  24.                     + service.getAlgorithm());
  25.         }
  26.     }

  27.     public static void main(String[] args) {
  28.         try {
  29.             KeyPair keyPair = getKeyPair();
  30.             ECPublicKey pubKey = (ECPublicKey) keyPair.getPublic();
  31.             ECPrivateKey priKey = (ECPrivateKey) keyPair.getPrivate();
  32.             //System.out.println("[pubKey]:\n" + getPublicKey(keyPair));
  33.             //System.out.println("[priKey]:\n" + getPrivateKey(keyPair));

  34.             //测试文本
  35.             String content = "abcdefg";

  36.             //加密
  37.             byte[] cipherTxt = encrypt(content.getBytes(), pubKey);
  38.             //解密
  39.             byte[] clearTxt = decrypt(cipherTxt, priKey);
  40.             //打印
  41.             System.out.println("content:" + content);
  42.             System.out.println("cipherTxt["+cipherTxt.length+"]:" + new String(cipherTxt));
  43.             System.out.println("clearTxt:" + new String(clearTxt));

  44.             //签名
  45.             byte[] sign = sign(content, priKey);
  46.             //验签
  47.             boolean ret = verify(content, sign, pubKey);
  48.             //打印
  49.             System.out.println("content:" + content);
  50.             System.out.println("sign["+sign.length+"]:" + new String(sign));
  51.             System.out.println("verify:" + ret);

  52.         } catch (Exception e) {
  53.             e.printStackTrace();
  54.             System.out.println("[main]-Exception:" + e.toString());
  55.         }
  56.     }

  57.     //生成秘钥对
  58.     public static KeyPair getKeyPair() throws Exception {
  59.         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");//BouncyCastle
  60.         keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
  61.         KeyPair keyPair = keyPairGenerator.generateKeyPair();
  62.         return keyPair;
  63.     }

  64.     //获取公钥(Base64编码)
  65.     public static String getPublicKey(KeyPair keyPair) {
  66.         ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
  67.         byte[] bytes = publicKey.getEncoded();
  68.         return Base64.getEncoder().encodeToString(bytes);
  69.     }

  70.     //获取私钥(Base64编码)
  71.     public static String getPrivateKey(KeyPair keyPair) {
  72.         ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
  73.         byte[] bytes = privateKey.getEncoded();
  74.         return Base64.getEncoder().encodeToString(bytes);
  75.     }

  76.     //公钥加密
  77.     public static byte[] encrypt(byte[] content, ECPublicKey pubKey) throws Exception {
  78.         Cipher cipher = Cipher.getInstance("ECIES", "BC");
  79.         cipher.init(Cipher.ENCRYPT_MODE, pubKey);
  80.         return cipher.doFinal(content);
  81.     }

  82.     //私钥解密
  83.     public static byte[] decrypt(byte[] content, ECPrivateKey priKey) throws Exception {
  84.         Cipher cipher = Cipher.getInstance("ECIES", "BC");
  85.         cipher.init(Cipher.DECRYPT_MODE, priKey);
  86.         return cipher.doFinal(content);
  87.     }

  88.     //私钥签名
  89.     public static byte[] sign(String content, ECPrivateKey priKey) throws Exception {
  90.         //这里可以从证书中解析出签名算法名称
  91.         //Signature signature = Signature.getInstance(getSigAlgName(pubCert));
  92.         Signature signature = Signature.getInstance(SIGNATURE);//"SHA256withECDSA"
  93.         signature.initSign(priKey);
  94.         signature.update(content.getBytes());
  95.         return signature.sign();
  96.     }

  97.     //公钥验签
  98.     public static boolean verify(String content, byte[] sign, ECPublicKey pubKey) throws Exception {
  99.         //这里可以从证书中解析出签名算法名称
  100.         //Signature signature = Signature.getInstance(getSigAlgName(priCert));
  101.         Signature signature = Signature.getInstance(SIGNATURE);//"SHA256withECDSA"
  102.         signature.initVerify(pubKey);
  103.         signature.update(content.getBytes());
  104.         return signature.verify(sign);
  105.     }

  106.     /**
  107.      * 解析证书的签名算法,单独一本公钥或者私钥是无法解析的,证书的内容远不止公钥或者私钥
  108.      * */
  109.     private static String getSigAlgName(File certFile) throws Exception {
  110.         CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
  111.         X509Certificate x509Certificate = (X509Certificate) cf.generateCertificate(new FileInputStream(certFile));
  112.         return x509Certificate.getSigAlgName();
  113.     }
  114. }
复制代码
回复

使用道具 举报

8

主题

18

帖子

84

积分

注册会员

Rank: 2

积分
84
 楼主| 发表于 2022-6-2 16:49:33 | 显示全部楼层

本帖子中包含更多资源

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

x
回复

使用道具 举报

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

本版积分规则

教学服务系统

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

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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