教学服务系统

 找回密码
 立即注册
搜索
查看: 518|回复: 6

信息计算2019级2班2号胡莘梅

[复制链接]

10

主题

25

帖子

118

积分

注册会员

Rank: 2

积分
118
发表于 2022-6-2 00:03:59 | 显示全部楼层 |阅读模式
本帖最后由 信计19-2胡莘梅 于 2022-6-2 00:17 编辑

RSA加解密与签名

一、RSA加密
  RSA密码体制是一种公钥密码体制,加密算法公开,以分配的密钥作为加密解密的关键。一般来说,在一对公私钥中,公钥和私钥都可以用来加密和解密,即公钥加密能且只能被对应的私钥进行解密,私钥加密能且只能被对应的公钥进行解密。但我们一般都用公钥加密,私钥解密,而且生成的私钥往往会比公钥蕴含了更多的信息量。
二、RSA签名
      签名就是在这份资料后面增加一段强而有力的证明,以此证明这段信息的发布者和这段信息的有效性完整性。RSA签名常用的就是将这份信息进行hash,得到一个hash值,再将hash值加密作为签名,后缀在信息的末尾。接收方接到传输的资料后,使用私钥解密这段加密过的hash,得到hash值,然后对信息原文进行hash,对比两次hash是否一致(验签)。签名的过程是不可逆的,因为hash是不可逆的,毕竟那么大的文件被hash成一段字符串还能还原的话那就碉堡了。
      在使用RSA进行通讯的时候,一般是两者结合,即:加密>签名>解密>验签
三、运行截图


本帖子中包含更多资源

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

x
回复

使用道具 举报

10

主题

25

帖子

118

积分

注册会员

Rank: 2

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


回复

使用道具 举报

10

主题

25

帖子

118

积分

注册会员

Rank: 2

积分
118
 楼主| 发表于 2022-6-2 00:14:52 | 显示全部楼层
RSAEncrypt.java 引用包:
  1. import java.io.BufferedReader;  
  2. import java.io.BufferedWriter;  
  3. import java.io.FileReader;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.security.InvalidKeyException;  
  7. import java.security.KeyFactory;  
  8. import java.security.KeyPair;  
  9. import java.security.KeyPairGenerator;  
  10. import java.security.NoSuchAlgorithmException;  
  11. import java.security.SecureRandom;  
  12.    
  13. import java.security.interfaces.RSAPrivateKey;  
  14. import java.security.interfaces.RSAPublicKey;  
  15. import java.security.spec.InvalidKeySpecException;  
  16. import java.security.spec.PKCS8EncodedKeySpec;  
  17. import java.security.spec.X509EncodedKeySpec;  
  18.    
  19. import javax.crypto.BadPaddingException;  
  20. import javax.crypto.Cipher;  
  21. import javax.crypto.IllegalBlockSizeException;  
  22. import javax.crypto.NoSuchPaddingException;
复制代码
(2)RSASignature.java
  1. package mmxzy;

  2. import java.security.KeyFactory;  
  3. import java.security.PrivateKey;  
  4. import java.security.PublicKey;  
  5. import java.security.spec.PKCS8EncodedKeySpec;  
  6. import java.security.spec.X509EncodedKeySpec;  

  7. public class RSASignature{  
  8.     public static final String SIGN_ALGORITHMS = "SHA1WithRSA";  
  9.     public static String sign(String content, String privateKey, String encode)  
  10.     {  
  11.         try   
  12.         {  
  13.             PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );  
  14.             KeyFactory keyf                 = KeyFactory.getInstance("RSA");  
  15.             PrivateKey priKey               = keyf.generatePrivate(priPKCS8);  
  16.             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);  
  17.             signature.initSign(priKey);  
  18.             signature.update( content.getBytes(encode));  
  19.             byte[] signed = signature.sign();
  20.             return Base64.encode(signed);  
  21.         }  
  22.         catch (Exception e)   
  23.         {  
  24.             e.printStackTrace();  
  25.         }  
  26.         return null;  
  27.     }  
  28.     public static String sign(String content, String privateKey)  
  29.     {  
  30.         try   
  31.         {  
  32.             PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );   
  33.             KeyFactory keyf = KeyFactory.getInstance("RSA");  
  34.             PrivateKey priKey = keyf.generatePrivate(priPKCS8);  
  35.             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);  
  36.             signature.initSign(priKey);  
  37.             signature.update( content.getBytes());  
  38.             byte[] signed = signature.sign();  
  39.             return Base64.encode(signed);  
  40.         }  
  41.         catch (Exception e)   
  42.         {  
  43.             e.printStackTrace();  
  44.         }  
  45.         return null;  
  46.     }  
  47.     public static boolean doCheck(String content, String sign, String publicKey,String encode)  
  48.     {  
  49.         try   
  50.         {  
  51.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
  52.             byte[] encodedKey = Base64.decode(publicKey);  
  53.             PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));  
  54.             java.security.Signature signature = java.security.Signature  
  55.             .getInstance(SIGN_ALGORITHMS);  
  56.             signature.initVerify(pubKey);  
  57.             signature.update( content.getBytes(encode) );
  58.             boolean bverify = signature.verify( Base64.decode(sign) );  
  59.             return bverify;  
  60.         }   
  61.         catch (Exception e)   
  62.         {  
  63.             e.printStackTrace();  
  64.         }  
  65.         return false;  
  66.     }  
  67.     public static boolean doCheck(String content, String sign, String publicKey)  
  68.     {  
  69.         try   
  70.         {  
  71.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
  72.             byte[] encodedKey = Base64.decode(publicKey);  
  73.             PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));  
  74.             java.security.Signature signature = java.security.Signature  
  75.             .getInstance(SIGN_ALGORITHMS);  
  76.             signature.initVerify(pubKey);  
  77.             signature.update( content.getBytes() );  
  78.             boolean bverify = signature.verify( Base64.decode(sign) );  
  79.             return bverify;  
  80.         }   
  81.         catch (Exception e)   
  82.         {
  83.             e.printStackTrace();  
  84.         }
  85.         return false;  
  86.     }  
  87. }
复制代码

回复

使用道具 举报

10

主题

25

帖子

118

积分

注册会员

Rank: 2

积分
118
 楼主| 发表于 2022-6-2 00:16:05 | 显示全部楼层
(3)Base64.java
  1. package mmxzy;

  2. public final class Base64 {  
  3.     static private final int     BASELENGTH           = 128;  
  4.     static private final int     LOOKUPLENGTH         = 64;  
  5.     static private final int     TWENTYFOURBITGROUP   = 24;  
  6.     static private final int     EIGHTBIT             = 8;  
  7.     static private final int     SIXTEENBIT           = 16;  
  8.     static private final int     FOURBYTE             = 4;  
  9.     static private final int     SIGN                 = -128;  
  10.     static private final char    PAD                  = '=';  
  11.     static private final boolean fDebug               = false;  
  12.     static final private byte[]  base64Alphabet       = new byte[BASELENGTH];  
  13.     static final private char[]  lookUpBase64Alphabet = new char[LOOKUPLENGTH];  
  14.     static {  
  15.         for (int i = 0; i < BASELENGTH; ++i) {  
  16.             base64Alphabet[i] = -1;  
  17.         }  
  18.         for (int i = 'Z'; i >= 'A'; i--) {  
  19.             base64Alphabet[i] = (byte) (i - 'A');  
  20.         }  
  21.         for (int i = 'z'; i >= 'a'; i--) {  
  22.             base64Alphabet[i] = (byte) (i - 'a' + 26);  
  23.         }  
  24.         for (int i = '9'; i >= '0'; i--) {  
  25.             base64Alphabet[i] = (byte) (i - '0' + 52);  
  26.         }  
  27.         base64Alphabet['+'] = 62;  
  28.         base64Alphabet['/'] = 63;  
  29.         for (int i = 0; i <= 25; i++) {  
  30.             lookUpBase64Alphabet[i] = (char) ('A' + i);  
  31.         }     
  32.         for (int i = 26, j = 0; i <= 51; i++, j++) {  
  33.             lookUpBase64Alphabet[i] = (char) ('a' + j);  
  34.         }   
  35.         for (int i = 52, j = 0; i <= 61; i++, j++) {  
  36.             lookUpBase64Alphabet[i] = (char) ('0' + j);  
  37.         }  
  38.         lookUpBase64Alphabet[62] = (char) '+';  
  39.         lookUpBase64Alphabet[63] = (char) '/';  
  40.     }
  41.     private static boolean isWhiteSpace(char octect) {  
  42.         return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);  
  43.     }  
  44.     private static boolean isPad(char octect) {  
  45.         return (octect == PAD);  
  46.     }
  47.     private static boolean isData(char octect) {  
  48.         return (octect < BASELENGTH && base64Alphabet[octect] != -1);  
  49.     }  
  50.     public static String encode(byte[] binaryData) {  
  51.         if (binaryData == null) {  
  52.             return null;  
  53.         }  
  54.         int lengthDataBits = binaryData.length * EIGHTBIT;  
  55.         if (lengthDataBits == 0) {  
  56.             return "";  
  57.         }  
  58.         int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;  
  59.         int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;  
  60.         int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;  
  61.         char encodedData[] = null;  
  62.         encodedData = new char[numberQuartet * 4];  
  63.         byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;  
  64.         int encodedIndex = 0;  
  65.         int dataIndex = 0;  
  66.         if (fDebug) {  
  67.             System.out.println("number of triplets = " + numberTriplets);  
  68.         }  
  69.         for (int i = 0; i < numberTriplets; i++) {  
  70.             b1 = binaryData[dataIndex++];  
  71.             b2 = binaryData[dataIndex++];  
  72.             b3 = binaryData[dataIndex++];  
  73.             if (fDebug) {  
  74.                 System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);  
  75.             }  
  76.             l = (byte) (b2 & 0x0f);  
  77.             k = (byte) (b1 & 0x03);  
  78.             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
  79.             byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);  
  80.             byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);  
  81.             if (fDebug) {  
  82.                 System.out.println("val2 = " + val2);  
  83.                 System.out.println("k4   = " + (k << 4));  
  84.                 System.out.println("vak  = " + (val2 | (k << 4)));  
  85.             }
  86.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
  87.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];  
  88.             encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];  
  89.             encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];  
  90.         }   
  91.         if (fewerThan24bits == EIGHTBIT) {  
  92.             b1 = binaryData[dataIndex];  
  93.             k = (byte) (b1 & 0x03);  
  94.             if (fDebug) {  
  95.                 System.out.println("b1=" + b1);  
  96.                 System.out.println("b1<<2 = " + (b1 >> 2));  
  97.             }  
  98.             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
  99.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
  100.             encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];  
  101.             encodedData[encodedIndex++] = PAD;  
  102.             encodedData[encodedIndex++] = PAD;  
  103.         } else if (fewerThan24bits == SIXTEENBIT) {  
  104.             b1 = binaryData[dataIndex];  
  105.             b2 = binaryData[dataIndex + 1];  
  106.             l = (byte) (b2 & 0x0f);  
  107.             k = (byte) (b1 & 0x03);  
  108.             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
  109.             byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);  
  110.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
  111.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];  
  112.             encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];  
  113.             encodedData[encodedIndex++] = PAD;  
  114.         }
  115.         return new String(encodedData);  
  116.     }  
  117.     public static byte[] decode(String encoded) {  
  118.         if (encoded == null) {  
  119.             return null;  
  120.         }  
  121.         char[] base64Data = encoded.toCharArray();  
  122.         int len = removeWhiteSpace(base64Data);
  123.         if (len % FOURBYTE != 0) {  
  124.             return null;
  125.         }  
  126.         int numberQuadruple = (len / FOURBYTE);
  127.         if (numberQuadruple == 0) {  
  128.             return new byte[0];  
  129.         }  
  130.         byte decodedData[] = null;  
  131.         byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;  
  132.         char d1 = 0, d2 = 0, d3 = 0, d4 = 0;  
  133.         int i = 0;  
  134.         int encodedIndex = 0;  
  135.         int dataIndex = 0;  
  136.         decodedData = new byte[(numberQuadruple) * 3];
  137.         for (; i < numberQuadruple - 1; i++) {
  138.             if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))  
  139.                 || !isData((d3 = base64Data[dataIndex++]))  
  140.                 || !isData((d4 = base64Data[dataIndex++]))) {  
  141.                 return null;  
  142.             }
  143.             b1 = base64Alphabet[d1];  
  144.             b2 = base64Alphabet[d2];  
  145.             b3 = base64Alphabet[d3];  
  146.             b4 = base64Alphabet[d4];
  147.             decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
  148.             decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
  149.             decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);  
  150.         }  
  151.         if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {  
  152.             return null;//if found "no data" just return null  
  153.         }  
  154.         b1 = base64Alphabet[d1];  
  155.         b2 = base64Alphabet[d2];
  156.         d3 = base64Data[dataIndex++];  
  157.         d4 = base64Data[dataIndex++];  
  158.         if (!isData((d3)) || !isData((d4))) {
  159.             if (isPad(d3) && isPad(d4)) {  
  160.                 if ((b2 & 0xf) != 0)
  161.                 {  
  162.                     return null;  
  163.                 }  
  164.                 byte[] tmp = new byte[i * 3 + 1];  
  165.                 System.arraycopy(decodedData, 0, tmp, 0, i * 3);  
  166.                 tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);  
  167.                 return tmp;  
  168.             } else if (!isPad(d3) && isPad(d4)) {  
  169.                 b3 = base64Alphabet[d3];  
  170.                 if ((b3 & 0x3) != 0)
  171.                 {  
  172.                     return null;  
  173.                 }  
  174.                 byte[] tmp = new byte[i * 3 + 2];  
  175.                 System.arraycopy(decodedData, 0, tmp, 0, i * 3);  
  176.                 tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
  177.                 tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
  178.                 return tmp;  
  179.             } else {  
  180.                 return null;  
  181.             }  
  182.         } else {  
  183.             b3 = base64Alphabet[d3];  
  184.             b4 = base64Alphabet[d4];  
  185.             decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
  186.             decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
  187.             decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);  
  188.         }  
  189.         return decodedData;  
  190.     }  
  191.     private static int removeWhiteSpace(char[] data) {  
  192.         if (data == null) {  
  193.             return 0;  
  194.         }   
  195.         int newSize = 0;  
  196.         int len = data.length;  
  197.         for (int i = 0; i < len; i++) {  
  198.             if (!isWhiteSpace(data[i])) {  
  199.                 data[newSize++] = data[i];  
  200.             }  
  201.         }  
  202.         return newSize;  
  203.     }  
  204. }
复制代码


回复

使用道具 举报

10

主题

25

帖子

118

积分

注册会员

Rank: 2

积分
118
 楼主| 发表于 2022-6-2 00:18:24 | 显示全部楼层
(4)MainTest.java
  1. package mmxzy;

  2. public class MainTest {  
  3.     public static void main(String[] args) throws Exception {  
  4.         String filepath="D:/tmp/";  
  5.         RSAEncrypt.genKeyPair(filepath);
  6.         System.out.println("--------------公钥加密私钥解密过程-------------------");  
  7.         String plainText="2022年6月1日儿童节快乐";
  8.         byte[] cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),plainText.getBytes());  
  9.         String cipher=Base64.encode(cipherData);  
  10.         byte[] res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), Base64.decode(cipher));  
  11.         String restr=new String(res);  
  12.         System.out.println("原文:"+plainText);  
  13.         System.out.println("加密:"+cipher);  
  14.         System.out.println("解密:"+restr);  
  15.         System.out.println();  
  16.         System.out.println("--------------私钥加密公钥解密过程-------------------");  
  17.         plainText="2022年6月1日晚安";  
  18.         cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)),plainText.getBytes());  
  19.         cipher=Base64.encode(cipherData);  
  20.         res=RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), Base64.decode(cipher));  
  21.         restr=new String(res);  
  22.         System.out.println("原文:"+plainText);  
  23.         System.out.println("加密:"+cipher);  
  24.         System.out.println("解密:"+restr);  
  25.         System.out.println();  
  26.         System.out.println("---------------私钥签名过程------------------");  
  27.         String content="2022年6月1日写作业";  
  28.         String signstr=RSASignature.sign(content,RSAEncrypt.loadPrivateKeyByFile(filepath));  
  29.         System.out.println("签名原串:"+content);  
  30.         System.out.println("签名串:"+signstr);  
  31.         System.out.println();  
  32.         System.out.println("---------------公钥校验签名------------------");  
  33.         System.out.println("签名原串:"+content);  
  34.         System.out.println("签名串:"+signstr);
  35.         System.out.println("验签结果:"+RSASignature.doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath)));  
  36.         System.out.println();  
  37.            
  38.     }  
  39. }
复制代码


回复

使用道具 举报

10

主题

25

帖子

118

积分

注册会员

Rank: 2

积分
118
 楼主| 发表于 2022-6-2 00:47:57 | 显示全部楼层
本帖最后由 信计19-2胡莘梅 于 2022-6-2 00:50 编辑

ECC椭圆曲线加密

一、关于ECC
ECC是Elliptic Curve Cryptography(椭圆曲线密码学)的缩写,是一种基于椭圆曲线数学的公开密钥加密算法,其本质是利用离散对数问题实现加密。
ECC的主要优势,是在使用更小的密钥的同时,提供更快的性能和更高等级的安全。
二、关于椭圆曲线
一条椭圆曲线就是一组被 y2 = x3 + ax + b 定义的且满足 4a3 + 27b2 ≠ 0 的点集。
4a3 + 27b2 ≠ 0 这个限定条件是为了保证曲线不包含奇点(在数学中是指曲线上任意一点都存在切线)。
三、加解密过程
  1、选定一条椭圆曲线 Ep(a,b) 并取椭圆曲线上一点,作为基点P。
  2、选择一个大数k作为私钥,并生成公钥 Q=kP。
  3、将 Ep(a,b) 和点Q、P传给用户。
  4、用户接到信息后 ,将待传输的明文编码到Ep(a,b)上的一点M,并产生一个随机整数r。
  5、公钥加密(密文C是一个点对):
     C={rP, M+rQ}
  6、私钥解密(M + rQ - k(rP) ,解密结果就是点M),公式如下:
    M + rQ - k(rP) = M + r(kP) - k(rP) = M
  7、对点M进行解码就可以得到明文
  假设在加密过程中,有一个第三者H,H只能知道椭圆曲线 Ep(a,b)、公钥Q、基点P、密文点C,而通过公钥Q、基点P求私钥k或者通过密文点C、基点P求随机数r都是非常困难的,因此得以保证数据传输的安全。
四、运行截图





本帖子中包含更多资源

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

x
回复

使用道具 举报

10

主题

25

帖子

118

积分

注册会员

Rank: 2

积分
118
 楼主| 发表于 2022-6-2 00:50:34 | 显示全部楼层
五、源代码
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #include<math.h>
  5. #include<time.h>
  6. #define MAX 100

  7. typedef struct point{
  8.         int point_x;
  9.         int point_y;
  10. }Point;
  11. typedef struct ecc{
  12.         struct point p[MAX];
  13.         int len;
  14. }ECCPoint;
  15. typedef struct generator{
  16.         Point p;
  17.         int p_class;
  18. }GENE_SET;

  19. void get_all_points();
  20. int int_sqrt(int s);
  21. Point timesPiont(int k,Point p);
  22. Point add_two_points(Point p1,Point p2);
  23. int inverse(int n,int b);
  24. void get_generetor_class();
  25. void encrypt_ecc();
  26. void decrypt_ecc();
  27. int mod_p(int s);
  28. void print();
  29. int isPrime(int n);
  30. char alphabet[26]="abcdefghijklmnopqrstuvwxyz";
  31. int a=-1,b=0,p=89;
  32. ECCPoint eccPoint;
  33. GENE_SET geneSet[MAX];
  34. int geneLen;
  35. char plain[]="yes";
  36. int m[MAX];
  37. int cipher[MAX];
  38. int nB;
  39. Point P1,P2,Pt,G,PB;
  40. Point Pm;
  41. int C[MAX];
  42. int main()
  43. {       
  44.         get_generetor_class();
  45.         encrypt_ecc();
  46.         decrypt_ecc();
  47.         return 0;
  48. }
  49. void encrypt_ecc()
  50. {
  51.         int num,i,j;
  52.         int gene_class;
  53.         int num_t;
  54.         int k;
  55.         srand(time(NULL));
  56.         for(i=0;i<strlen(plain);i++)
  57.         {
  58.                 for(j=0;j<26;j++)
  59.                 {
  60.                         if(plain[i]==alphabet[j])
  61.                         {
  62.                                 m[i]=j;
  63.                         }
  64.                 }         
  65.         }
  66.         num=rand()%geneLen;
  67.         gene_class=geneSet[num].p_class;
  68.         while(isPrime(gene_class)==-1)
  69.         {
  70.                  num=rand()%(geneLen-3)+3;
  71.                  gene_class=geneSet[num].p_class;
  72.         }
  73.         G=geneSet[num].p;
  74.         nB=rand()%(gene_class-1)+1;
  75.         PB=timesPiont(nB,G);
  76.         printf("\n公钥:\n");
  77.         printf("{y^2=x^3%d*x+%d,%d,(%d,%d),(%d,%d)}\n",a,b,gene_class,G.point_x,G.point_y,PB.point_x,PB.point_y);
  78.         printf("私钥:\n");
  79.         printf("nB=%d\n",nB);
  80.         k=rand()%(gene_class-2)+1;
  81.         P1=timesPiont(k,G);
  82.         num_t=rand()%eccPoint.len;
  83.         Pt=eccPoint.p[num_t];
  84.         P2=timesPiont(k,PB);
  85.         Pm=add_two_points(Pt,P2);
  86.         printf("加密数据:\n");
  87.         printf("kG=(%d,%d),Pt+kPB=(%d,%d),C={",P1.point_x,P1.point_y,Pm.point_x,Pm.point_y);
  88.         for(i=0;i<strlen(plain);i++)
  89.         {
  90.                 C[i]=m[i]*Pt.point_x+Pt.point_y;
  91.                 printf("{%d}",C[i]);
  92.         }       
  93.         printf("}\n");
  94. }
  95. void decrypt_ecc()
  96. {
  97.         Point temp,temp1;
  98.         int m,i;
  99.         temp=timesPiont(nB,P1);
  100.         temp.point_y=0-temp.point_y;
  101.         temp1=add_two_points(Pm,temp);
  102.         printf("\n解密结果:\n");
  103.         for(i=0;i<strlen(plain);i++)
  104.         {
  105.                 m=(C[i]-temp1.point_y)/temp1.point_x;
  106.                 printf("%c",alphabet[m]);
  107.         }
  108.         printf("\n");
  109. }
  110. int isPrime(int n)
  111. {
  112.         int i,k;
  113.     k = sqrt(n);
  114.     for (i = 2; i <= k;i++)
  115.     {
  116.             if (n%i == 0)
  117.                         break;
  118.         }      
  119.     if (i <=k){
  120.             return -1;
  121.         }
  122.     else {
  123.              return 0;
  124.         }
  125. }
  126. void get_generetor_class()
  127. {       
  128.         int i,j=0;
  129.         int count=1;
  130.         Point p1,p2;
  131.         get_all_points();
  132.         printf("\n**********************************输出生成元以及阶:*************************************\n");
  133.         for(i=0;i<eccPoint.len;i++)
  134.         {
  135.                 count=1;
  136.                 p1.point_x=p2.point_x=eccPoint.p[i].point_x;
  137.                 p1.point_y=p2.point_y=eccPoint.p[i].point_y;               
  138.                 while(1)
  139.                 {       
  140.                         p2=add_two_points(p1,p2);                                       
  141.                         if(p2.point_x==-1 && p2.point_y==-1)
  142.                         {
  143.                                 break;
  144.                         }
  145.                         count++;
  146.                         if(p2.point_x==p1.point_x)
  147.                         {
  148.                                 break;
  149.                         }                                               
  150.                 }
  151.                 count++;
  152.                 if(count<=eccPoint.len+1)
  153.                 {
  154.                         geneSet[j].p.point_x=p1.point_x;
  155.                         geneSet[j].p.point_y=p1.point_y;
  156.                         geneSet[j].p_class=count;
  157.                         printf("(%d,%d)--->>%d\t",geneSet[j].p.point_x,geneSet[j].p.point_y,geneSet[j].p_class);
  158.                         j++;
  159.                         if(j % 6 ==0){
  160.                                 printf("\n");
  161.                         }
  162.                 }
  163.                 geneLen=j;       
  164.         }
  165. }
  166. Point timesPiont(int k,Point p0)
  167. {
  168.         if(k==1){
  169.                 return p0;
  170.         }                
  171.         else if(k==2){
  172.                 return add_two_points(p0,p0);
  173.         }else{
  174.                 return add_two_points(p0,timesPiont(k-1,p0));
  175.         }
  176. }
  177. Point add_two_points(Point p1,Point p2)
  178. {
  179.         long t;
  180.         int x1=p1.point_x;
  181.         int y1=p1.point_y;
  182.         int x2=p2.point_x;
  183.         int y2=p2.point_y;
  184.         int tx,ty;
  185.         int x3,y3;
  186.         int flag=0;
  187.         if((x2==x1)&& (y2==y1) )
  188.         {
  189.                 if(y1==0)
  190.                 {
  191.                         flag=1;
  192.                 }else{
  193.                         t=(3*x1*x1+a)*inverse(p,2*y1) % p;
  194.                 }
  195.         }else{
  196.                 ty=y2-y1;
  197.                 tx=x2-x1;
  198.                 while(ty<0)
  199.                 {
  200.                         ty+=p;
  201.                 }
  202.                 while(tx<0)
  203.                 {
  204.                         tx+=p;
  205.                 }
  206.                 if(tx==0 && ty !=0)
  207.                 {
  208.                         flag=1;
  209.                 }else{
  210.                         t=ty*inverse(p,tx) % p;
  211.                 }
  212.         }
  213.         if(flag==1)
  214.         {
  215.                 p2.point_x=-1;
  216.                 p2.point_y=-1;
  217.         }else{
  218.                 x3=(t*t-x1-x2) % p;
  219.                 y3=(t*(x1-x3)-y1) % p;
  220.                 while(x3<0)
  221.                 {
  222.                         x3+=p;
  223.                 }
  224.                 while(y3<0)
  225.                 {
  226.                         y3+=p;
  227.                 }
  228.                 p2.point_x=x3;
  229.                 p2.point_y=y3;
  230.         }       
  231.         return p2;
  232. }
  233. int inverse(int n,int b)
  234. {
  235.         int q,r,r1=n,r2=b,t,t1=0,t2=1,i=1;
  236.         while(r2>0)
  237.         {
  238.                 q=r1/r2;
  239.                 r=r1%r2;
  240.                 r1=r2;
  241.                 r2=r;
  242.                 t=t1-q*t2;
  243.                 t1=t2;
  244.                 t2=t;
  245.         }
  246.         if(t1>=0)
  247.                 return t1%n;
  248.         else{  
  249.                 while((t1+i*n)<0)
  250.                         i++;
  251.                 return t1+i*n;
  252.         }
  253. }
  254. void get_all_points()
  255. {
  256.         int i=0;
  257.         int j=0;
  258.         int s,y=0;
  259.         int n=0,q=0;
  260.         int modsqrt=0;
  261.         int flag=0;
  262.         if (4 * a * a * a + 27 * b * b != 0)
  263.         {
  264.                 for(i=0;i<=p-1;i++)
  265.                 {
  266.                         flag=0;
  267.                         n=1;
  268.                         y=0;
  269.                         s= i * i * i + a * i + b;
  270.                         while(s<0)
  271.                         {
  272.                                 s+=p;
  273.                         }
  274.                         s=mod_p(s);
  275.                         modsqrt=int_sqrt(s);
  276.                         if(modsqrt!=-1)
  277.                         {
  278.                                 flag=1;
  279.                                 y=modsqrt;
  280.                         }else{
  281.                                 while(n<=p-1)
  282.                                 {
  283.                                         q=s+n*p;
  284.                                         modsqrt=int_sqrt(q);
  285.                                         if(modsqrt!=-1)
  286.                                         {
  287.                                                 y=modsqrt;
  288.                                                 flag=1;
  289.                                                 break;
  290.                                         }
  291.                                                 flag=0;
  292.                                                 n++;
  293.                                 }
  294.                         }
  295.                         if(flag==1)
  296.                         {
  297.                                 eccPoint.p[j].point_x=i;
  298.                                 eccPoint.p[j].point_y=y;
  299.                                 j++;
  300.                                 if(y!=0)
  301.                                 {
  302.                                         eccPoint.p[j].point_x=i;
  303.                                         eccPoint.p[j].point_y=(p-y) % p;
  304.                                         j++;
  305.                                 }                               
  306.                         }
  307.                 }
  308.                 eccPoint.len=j;
  309.                 print();
  310.         }       
  311. }
  312. int mod_p(int s)
  313. {
  314.         int i;
  315.         int result;
  316.         i = s / p;
  317.         result = s - i * p;
  318.         if (result >= 0)
  319.         {
  320.                 return result;
  321.         }
  322.         else
  323.         {
  324.                 return result + p;
  325.         }
  326. }

  327. int int_sqrt(int s)
  328. {
  329.         int temp;
  330.         temp=(int)sqrt(s);
  331.         if(temp*temp==s)
  332.         {
  333.                 return temp;
  334.         }else{
  335.                 return -1;
  336.         }
  337. }
  338. void print()
  339. {
  340.         int i;
  341.         int len=eccPoint.len;
  342.         printf("\n该椭圆曲线上共有%d个点(包含无穷远点)\n",len+1);
  343.         for(i=0;i<len;i++)
  344.         {
  345.                 if(i % 8==0)
  346.                 {
  347.                         printf("\n");
  348.                 }
  349.                 printf("(%2d,%2d)\t",eccPoint.p[i].point_x,eccPoint.p[i].point_y);
  350.         }
  351.         printf("\n");
  352. }
复制代码
回复

使用道具 举报

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

本版积分规则

教学服务系统

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

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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