教学服务系统

 找回密码
 立即注册
搜索
查看: 640|回复: 3

信息计算2019级1班16好舒圣斌

[复制链接]

8

主题

17

帖子

118

积分

注册会员

Rank: 2

积分
118
发表于 2022-5-2 23:01:10 | 显示全部楼层 |阅读模式
  1. import java.math.BigInteger;
  2. import java.util.ArrayList;
  3. import java.util.Scanner;
  4. class Node {
  5.         private double p;
  6.         private char alpha;
  7.         public Node(double p, char alpha) {
  8.                 this.p=p;
  9.                 this.alpha=alpha;
  10.         }
  11.         public void setp(double p) {
  12.                 this.p=p;
  13.         }
  14.         public void setalpha(char a) {
  15.                 this.alpha=a;
  16.         }
  17.         public double getp() {
  18.                 return p;
  19.         }
  20.         public char getalpha() {
  21.                 return alpha;
  22.         }
  23. }
  24. class Prime {
  25.         public boolean sushu(double n) {
  26.                 boolean isPrime=true;
  27.                 if (n>2) {
  28.                         if (n%2==0) {
  29.                                 isPrime=false;
  30.                         } else {
  31.                                 for (int i=3;i<=(int)Math.sqrt(n);i+=2) {
  32.                                         if (n%i==0) {
  33.                                                 isPrime=false;
  34.                                                 break;
  35.                                         }
  36.                                 }
  37.                         }

  38.                 }
  39.                 return isPrime;
  40.         }
  41.         private static final BigInteger ZERO=BigInteger.ZERO;
  42.         private static final BigInteger ONE=BigInteger.ONE;
  43.         private static final BigInteger TWO=new BigInteger("2");
  44.         private static final int ERR_VAL=100;
  45.         public BigInteger nextPrime(BigInteger start) {
  46.                 if (isEven(start))
  47.                         start=start.add(ONE);
  48.                 else
  49.                         start=start.add(TWO);
  50.                 if (start.isProbablePrime(ERR_VAL))
  51.                         return (start);
  52.                 else
  53.                         return (nextPrime(start));
  54.         }

  55.         private static boolean isEven(BigInteger n) {
  56.                 return (n.mod(TWO).equals(ZERO));
  57.         }
  58.         public BigInteger bigRandom(int numDigits) {
  59.                 StringBuffer s=new StringBuffer("");
  60.                 for (int i=0;i<numDigits;i++)
  61.                         if (i==0)
  62.                                 s.append(randomDigit(false));
  63.                         else
  64.                                 s.append(randomDigit(true));
  65.                 return (new BigInteger(s.toString()));
  66.         }

  67.         private StringBuffer randomDigit(boolean isZeroOK) {
  68.                 int index;
  69.                 if (isZeroOK)
  70.                         index=(int)Math.floor(Math.random()*10);
  71.                 else
  72.                         index=1+(int)Math.floor(Math.random()*9);
  73.                 return (digits[index]);
  74.         }

  75.         private static StringBuffer[] digits={ new StringBuffer("0"),
  76.                         new StringBuffer("1"),new StringBuffer("2"),
  77.                         new StringBuffer("3"),new StringBuffer("4"),
  78.                         new StringBuffer("5"),new StringBuffer("6"),
  79.                         new StringBuffer("7"),new StringBuffer("8"),new StringBuffer("9") };
  80.         public static void main(String[] args) {
  81.         }
  82. }
  83. public class RSA {
  84.         static BigInteger x,y;
  85.         public static boolean fun(BigInteger x,BigInteger y) {
  86.                 BigInteger t;
  87.                 while (!(y.equals(new BigInteger("0")))) {
  88.                         t=x;
  89.                         x=y;
  90.                         y=t.mod(y);
  91.                 }
  92.                 if (x.equals(new BigInteger("1")))
  93.                         return false;
  94.                 else
  95.                         return true;
  96.         }
  97.         public static BigInteger siyue(BigInteger a,BigInteger b) {
  98.                 BigInteger temp;
  99.                 if (b.equals(new BigInteger("0"))) {
  100.                         x=new BigInteger("1");
  101.                         y=new BigInteger("0");
  102.                         return x;
  103.                 }
  104.                 siyue(b,a.mod(b));
  105.                 temp=x;
  106.                 x=y;
  107.                 y=temp.subtract((a.divide(b).multiply(y)));
  108.                 return x;
  109.         }

  110.         public static double entropy(String mess) {
  111.                 ArrayList<Node> jieguo=new ArrayList<Node>();
  112.                 jieguo.clear();
  113.                 double num=mess.length();
  114.                 for (int i=0;i<num;i++) {
  115.                         boolean flag_exit=true;
  116.                         for (int j=0;j<jieguo.size();j++) {
  117.                                 if (jieguo.get(j).getalpha()==mess.charAt(i)) {
  118.                                         flag_exit=false;
  119.                                         jieguo.get(j).setp(jieguo.get(j).getp()+1/num);
  120.                                 }
  121.                         }
  122.                         if (flag_exit)
  123.                                 jieguo.add(new Node(1/num,mess.charAt(i)));
  124.                 }
  125.                 double entropy=0;
  126.                 for (int i=0;i<jieguo.size();i++) {
  127.                         double p1=jieguo.get(i).getp();
  128.                         entropy+=(-p1*(Math.log(p1)/Math.log(2)));
  129.                 }
  130.                 return entropy;
  131.         }
  132.         public static void main(String[] args) {
  133.                 BigInteger p=null;
  134.                 BigInteger e,d,n,t,c;
  135.                 BigInteger q=null;
  136.                 for (int i=0;i<2;i++) {
  137.                         int numDigits;
  138.                         Prime pri=new Prime();
  139.                         try {
  140.                                 numDigits=Integer.parseInt("15");
  141.                         } catch (Exception e1) {
  142.                                 numDigits=128;
  143.                         }
  144.                         BigInteger start=pri.bigRandom(numDigits);
  145.                         BigInteger big=pri.nextPrime(start);
  146.                         if (i==0)
  147.                                 p=big;
  148.                         else
  149.                                 q=big;
  150.                 }
  151.                 Scanner input=new Scanner(System.in);
  152.                 n=p.multiply(q);
  153.                 t=p.subtract(new BigInteger("1")).multiply(q.subtract(new BigInteger("1")));
  154.                 int numDigits;
  155.                 Prime pri=new Prime();
  156.                 try {
  157.                         numDigits=Integer.parseInt("15");
  158.                 } catch (Exception e1) {
  159.                         numDigits=128;
  160.                 }
  161.                 BigInteger start=pri.bigRandom(numDigits);
  162.                 BigInteger big=pri.nextPrime(start);
  163.                 e=big;
  164.                 while (e.compareTo(t)==1||fun(e,t)) {
  165.                         System.out.println("e不合要求,请重新产生"+(e.compareTo(t)==1)+fun(e,t));
  166.                         pri = new Prime();
  167.                         try {
  168.                                 numDigits=Integer.parseInt("15");
  169.                         } catch (Exception e1) {
  170.                                 numDigits=128;
  171.                         }
  172.                         start=pri.bigRandom(numDigits);
  173.                         big=pri.nextPrime(start);
  174.                         e=big;
  175.                 }
  176.                 d=siyue(e,t);
  177.                 System.out.println("由计算机随机产生2个素数p,q,分别如下:");
  178.                 System.out.println(p);
  179.                 System.out.println(q);
  180.                 System.out.println("计算得到的n:");
  181.                 System.out.println(n);
  182.                 System.out.println("计算得到的t:");
  183.                 System.out.println(t);
  184.                 System.out.println("随机产生的公钥:");
  185.                 System.out.println(e);
  186.                 System.out.println("私钥为:");
  187.                 System.out.println(d);
  188.                 while (true) {
  189.                         System.out.println("请输入明文:");
  190.                         String mess=input.nextLine();
  191.                         BigInteger m=new BigInteger(mess.getBytes());
  192.                         System.out.println("明文的大整数表示形式:"+m);
  193.                         mess=m.toString();
  194.                         System.out.println("计算得明文熵:"+entropy(mess));
  195.                         c=m.modPow(e,n);
  196.                         System.out.println("密文的大整数表示形式:"+c);
  197.                         System.out.println("计算得密文熵:"+entropy(c.toString()));
  198.                         System.out.println("密文的字符串表示形式:"+new String(c.toByteArray()));
  199.                         m=c.modPow(d, n);
  200.                         System.out.println("解密得到明文的大整数表示形式:"+c);
  201.                         String str=new String(m.toByteArray());
  202.                         System.out.println("解密得到明文为:"+str);
  203.                 }
  204.         }
  205. }
复制代码

本帖子中包含更多资源

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

x
回复

使用道具 举报

8

主题

17

帖子

118

积分

注册会员

Rank: 2

积分
118
 楼主| 发表于 2022-5-3 15:55:14 | 显示全部楼层

本帖子中包含更多资源

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

x
回复

使用道具 举报

8

主题

17

帖子

118

积分

注册会员

Rank: 2

积分
118
 楼主| 发表于 2022-6-2 10:10:43 | 显示全部楼层
RSA加密、签名区别
  加密和签名都是为了安全性考虑,但略有不同。常有人问加密和签名是用私钥还是公钥?其实都是对加密和签名的作用有所混淆。简单的说,加密是为了防止信息被泄露,而签名是为了防止信息被篡改。这里举2个例子说明。
第一个场景:战场上,B要给A传递一条消息,内容为某一指令。
RSA的加密过程如下:
(1)A生成一对密钥(公钥和私钥),私钥不公开,A自己保留。公钥为公开的,任何人可以获取。
(2)A传递自己的公钥给B,B用A的公钥对消息进行加密。
(3)A接收到B加密的消息,利用A自己的私钥对消息进行解密。
  在这个过程中,只有2次传递过程,第一次是A传递公钥给B,第二次是B传递加密消息给A,即使都被敌方截获,也没有危险性,因为只有A的私钥才能对消息进行解密,防止了消息内容的泄露。
第二个场景:A收到B发的消息后,需要进行回复“收到”。
RSA签名的过程如下:
(1)A生成一对密钥(公钥和私钥),私钥不公开,A自己保留。公钥为公开的,任何人可以获取。
(2)A用自己的私钥对消息加签,形成签名,并将加签的消息和消息本身一起传递给B。
(3)B收到消息后,在获取A的公钥进行验签,如果验签出来的内容与消息本身一致,证明消息是A回复的。
  1. import java.io.ByteArrayOutputStream;
  2. import java.security.KeyFactory;
  3. import java.security.KeyPair;
  4. import java.security.KeyPairGenerator;
  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. import javax.crypto.Cipher;
  11. import org.apache.commons.codec.binary.Base64;
  12. public class TestRSA {
  13.     private static final int MAX_ENCRYPT_BLOCK = 117;
  14.     private static final int MAX_DECRYPT_BLOCK = 128;
  15.     public static KeyPair getKeyPair() throws Exception {
  16.         KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
  17.         generator.initialize(1024);
  18.         return generator.generateKeyPair();
  19.     }
  20.     public static PrivateKey getPrivateKey(String privateKey) throws Exception {
  21.         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  22.         byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
  23.         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
  24.         return keyFactory.generatePrivate(keySpec);
  25.     }
  26.     public static PublicKey getPublicKey(String publicKey) throws Exception {
  27.         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  28.         byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
  29.         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
  30.         return keyFactory.generatePublic(keySpec);
  31.     }
  32.     public static String encrypt(String data, PublicKey publicKey) throws Exception {
  33.         Cipher cipher = Cipher.getInstance("RSA");
  34.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  35.         int inputLen = data.getBytes().length;
  36.         ByteArrayOutputStream out = new ByteArrayOutputStream();
  37.         int offset = 0;
  38.         byte[] cache;
  39.         int i = 0;
  40.         while (inputLen - offset > 0) {
  41.             if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
  42.                 cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
  43.             } else {
  44.                 cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
  45.             }
  46.             out.write(cache, 0, cache.length);
  47.             i++;
  48.             offset = i * MAX_ENCRYPT_BLOCK;
  49.         }
  50.         byte[] encryptedData = out.toByteArray();
  51.         out.close();
  52.         return new String(Base64.encodeBase64String(encryptedData));
  53.     }
  54.     public static String decrypt(String data, PrivateKey privateKey) throws Exception {
  55.         Cipher cipher = Cipher.getInstance("RSA");
  56.         cipher.init(Cipher.DECRYPT_MODE, privateKey);
  57.         byte[] dataBytes = Base64.decodeBase64(data);
  58.         int inputLen = dataBytes.length;
  59.         ByteArrayOutputStream out = new ByteArrayOutputStream();
  60.         int offset = 0;
  61.         byte[] cache;
  62.         int i = 0;
  63.         while (inputLen - offset > 0) {
  64.             if (inputLen - offset > MAX_DECRYPT_BLOCK) {
  65.                 cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
  66.             } else {
  67.                 cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
  68.             }
  69.             out.write(cache, 0, cache.length);
  70.             i++;
  71.             offset = i * MAX_DECRYPT_BLOCK;
  72.         }
  73.         byte[] decryptedData = out.toByteArray();
  74.         out.close();
  75.         return new String(decryptedData, "UTF-8");
  76.     }
  77.     public static String sign(String data, PrivateKey privateKey) throws Exception {
  78.         byte[] keyBytes = privateKey.getEncoded();
  79.         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
  80.         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  81.         PrivateKey key = keyFactory.generatePrivate(keySpec);
  82.         Signature signature = Signature.getInstance("MD5withRSA");
  83.         signature.initSign(key);
  84.         signature.update(data.getBytes());
  85.         return new String(Base64.encodeBase64(signature.sign()));
  86.     }
  87.     public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
  88.         byte[] keyBytes = publicKey.getEncoded();
  89.         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
  90.         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  91.         PublicKey key = keyFactory.generatePublic(keySpec);
  92.         Signature signature = Signature.getInstance("MD5withRSA");
  93.         signature.initVerify(key);
  94.         signature.update(srcData.getBytes());
  95.         return signature.verify(Base64.decodeBase64(sign.getBytes()));
  96.     }
  97.     public static void main(String[] args) {
  98.         try {
  99.             KeyPair keyPair = getKeyPair();
  100.             String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
  101.             String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
  102.             System.out.println("私钥:" + privateKey);
  103.             System.out.println("公钥:" + publicKey);
  104.             String data = "待加密的文字内容";
  105.             String encryptData = encrypt(data, getPublicKey(publicKey));
  106.             System.out.println("加密后内容:" + encryptData);
  107.             String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
  108.             System.out.println("解密后内容:" + decryptData);
  109.             String sign = sign(data, getPrivateKey(privateKey));
  110.             boolean result = verify(data, getPublicKey(publicKey), sign);
  111.             System.out.print("验签结果:" + result);
  112.         } catch (Exception e) {
  113.             e.printStackTrace();
  114.             System.out.print("加解密异常");
  115.         }
  116.     }
  117. }
复制代码


回复

使用道具 举报

8

主题

17

帖子

118

积分

注册会员

Rank: 2

积分
118
 楼主| 发表于 2022-6-2 10:23:05 | 显示全部楼层
ECC加密算法原理介绍
ECC也是使用了正向运算很简单,但是反向运算很难的单向函数,但是和RSA的原理不同,RSA使用的时模函数作为单向函数,而
ECC是建立在基于椭圆曲线的离散对数问题上的密码体制,给定椭圆曲线上的一个点G,并选取一个整数k,求解K=kG很容易;反过来,在椭圆曲线上给定两个点K和G,若使K=kG,求整数k是一个难题。ECC就是建立在此数学难题之上,这一数学难题称为椭圆曲线离散对数问题。其中椭圆曲线上的点K则为公钥,整数k则为私钥。
  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.     private final static int KEY_SIZE = 256;
  12.     private final static String SIGNATURE = "SHA256withECDSA";
  13.     static {
  14.         Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  15.     }
  16.     private static void printProvider() {
  17.         Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
  18.         for (Provider.Service service : provider.getServices()) {
  19.             System.out.println(service.getType() + ": "
  20.                     + service.getAlgorithm());
  21.         }
  22.     }
  23.     public static void main(String[] args) {
  24.         try {
  25.             KeyPair keyPair = getKeyPair();
  26.             ECPublicKey pubKey = (ECPublicKey) keyPair.getPublic();
  27.             ECPrivateKey priKey = (ECPrivateKey) keyPair.getPrivate();
  28. System.out.println("[pubKey]:\n" + getPublicKey(keyPair));
  29. System.out.println("[priKey]:\n" + getPrivateKey(keyPair));
  30.             String content = "abcdefg";
  31.             byte[] cipherTxt = encrypt(content.getBytes(), pubKey);
  32.             byte[] clearTxt = decrypt(cipherTxt, priKey);
  33.             System.out.println("content:" + content);
  34.             System.out.println("cipherTxt["+cipherTxt.length+"]:" + new String(cipherTxt));
  35.             System.out.println("clearTxt:" + new String(clearTxt));
  36.             byte[] sign = sign(content, priKey);
  37.             boolean ret = verify(content, sign, pubKey);
  38.             System.out.println("content:" + content);
  39.             System.out.println("sign["+sign.length+"]:" + new String(sign));
  40.             System.out.println("verify:" + ret);
  41.         } catch (Exception e) {
  42.             e.printStackTrace();
  43.             System.out.println("[main]-Exception:" + e.toString());
  44.         }
  45.     }
  46.     public static KeyPair getKeyPair() throws Exception {
  47.         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
  48.         keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
  49.         KeyPair keyPair = keyPairGenerator.generateKeyPair();
  50.         return keyPair;
  51.     }
  52.     public static String getPublicKey(KeyPair keyPair) {
  53.         ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
  54.         byte[] bytes = publicKey.getEncoded();
  55.         return Base64.getEncoder().encodeToString(bytes);
  56.     }
  57.     public static String getPrivateKey(KeyPair keyPair) {
  58.         ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
  59.         byte[] bytes = privateKey.getEncoded();
  60.         return Base64.getEncoder().encodeToString(bytes);
  61.     }
  62.     public static byte[] encrypt(byte[] content, ECPublicKey pubKey) throws Exception {
  63.         Cipher cipher = Cipher.getInstance("ECIES", "BC");
  64.         cipher.init(Cipher.ENCRYPT_MODE, pubKey);
  65.         return cipher.doFinal(content);
  66.     }
  67.     public static byte[] decrypt(byte[] content, ECPrivateKey priKey) throws Exception {
  68.         Cipher cipher = Cipher.getInstance("ECIES", "BC");
  69.         cipher.init(Cipher.DECRYPT_MODE, priKey);
  70.         return cipher.doFinal(content);
  71.     }
  72.     public static byte[] sign(String content, ECPrivateKey priKey) throws Exception {
  73. Signature signature = Signature.getInstance(getSigAlgName(pubCert));
  74.         Signature signature = Signature.getInstance(SIGNATURE);//"SHA256withECDSA"
  75.         signature.initSign(priKey);
  76.         signature.update(content.getBytes());
  77.         return signature.sign();
  78.     }
  79.     public static boolean verify(String content, byte[] sign, ECPublicKey pubKey) throws Exception {
  80. Signature signature = Signature.getInstance(getSigAlgName(priCert));
  81.         Signature signature = Signature.getInstance(SIGNATURE);
  82.         signature.initVerify(pubKey);
  83.         signature.update(content.getBytes());
  84.         return signature.verify(sign);
  85.     }
  86.     private static String getSigAlgName(File certFile) throws Exception {
  87.         CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
  88.         X509Certificate x509Certificate = (X509Certificate) cf.generateCertificate(new FileInputStream(certFile));
  89.         return x509Certificate.getSigAlgName();
  90.     }
  91. }
复制代码



回复

使用道具 举报

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

本版积分规则

教学服务系统

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

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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