教学服务系统

 找回密码
 立即注册
搜索
查看: 992|回复: 1

信息计算2019级1班18号冯雨

[复制链接]

11

主题

17

帖子

83

积分

注册会员

Rank: 2

积分
83
发表于 2022-6-3 00:46:32 | 显示全部楼层 |阅读模式
                                                                                                             RSA加密、解密和签名
RSA加密是一种非对称加密。可以在不直接传递密钥的情况下,完成解密。这能够确保信息的安全性,避免了直接传递密钥所造成的被破解的风险。是由一对密钥来进行加解密的过程,分别称为公钥和私钥。两者之间有数学相关,该加密算法的原理就是对一极大整数做因数分解的困难性来保证安全性。通常个人保存私钥,公钥是公开的(可能同时多人持有)。
  1. import javax.crypto.Cipher;
  2. import java.security.KeyFactory;
  3. import java.security.KeyPair;
  4. import java.security.KeyPairGenerator;
  5. import java.security.NoSuchAlgorithmException;
  6. import java.security.PrivateKey;
  7. import java.security.PublicKey;
  8. import java.security.SecureRandom;
  9. import java.security.Signature;
  10. import java.security.interfaces.RSAPrivateKey;
  11. import java.security.interfaces.RSAPublicKey;
  12. import java.security.spec.PKCS8EncodedKeySpec;
  13. import java.security.spec.X509EncodedKeySpec;
  14. import java.util.Base64;
  15. import java.util.HashMap;
  16. import java.util.Map;

  17. public class test14 {
  18.         private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥
  19.         public static void main(String[] args) throws Exception {
  20.                 //生成公钥和私钥
  21.                 genKeyPair();
  22.                 //加密字符串
  23.                 String message = "df723820";
  24.                 System.out.println("随机生成的公钥为:" + keyMap.get(0));
  25.                 System.out.println("随机生成的私钥为:" + keyMap.get(1));
  26.                 String messageEn = encrypt(message,keyMap.get(0));
  27.                 System.out.println(message + "\t加密后的字符串为:" + messageEn);
  28.                 String messageDe = decrypt(messageEn,keyMap.get(1));
  29.                 System.out.println("还原后的字符串为:" + messageDe);
  30.                 System.err.println("私钥签名——公钥验证签名");
  31.         String sign = RSAUtils.sign(encodedData, privateKey);
  32.         System.err.println("签名:\r" + sign);
  33.         }

  34.         /**
  35.          * 随机生成密钥对
  36.          * @throws NoSuchAlgorithmException
  37.          */  
  38.         public static void genKeyPair() throws NoSuchAlgorithmException {  
  39.                 // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象  
  40.                 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
  41.                 // 初始化密钥对生成器,密钥大小为96-1024位  
  42.                 keyPairGen.initialize(1024,new SecureRandom());  
  43.                 // 生成一个密钥对,保存在keyPair中  
  44.                 KeyPair keyPair = keyPairGen.generateKeyPair();  
  45.                 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥  
  46.                 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥  
  47.                 String publicKeyString = new String(Base64.getEncoder().encode(publicKey.getEncoded()));  
  48.                 // 得到私钥字符串  
  49.                 String privateKeyString = new String(Base64.getEncoder().encode((privateKey.getEncoded())));  
  50.                 // 将公钥和私钥保存到Map
  51.                 keyMap.put(0,publicKeyString);  //0表示公钥
  52.                 keyMap.put(1,privateKeyString);  //1表示私钥
  53.         }  
  54.         /**
  55.          * RSA公钥加密
  56.          *  
  57.          * @param str
  58.          *            加密字符串
  59.          * @param publicKey
  60.          *            公钥
  61.          * @return 密文
  62.          * @throws Exception
  63.          *             加密过程中的异常信息
  64.          */  
  65.         public static String encrypt( String str, String publicKey ) throws Exception{
  66.                 //base64编码的公钥
  67.                 byte[] decoded = Base64.getDecoder().decode(publicKey);
  68.                 RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
  69.                 //RSA加密
  70.                 Cipher cipher = Cipher.getInstance("RSA");
  71.                 cipher.init(Cipher.ENCRYPT_MODE, pubKey);
  72.                 String outStr = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
  73.                 return outStr;
  74.         }

  75.         /**
  76.          * RSA私钥解密
  77.          *  
  78.          * @param str
  79.          *            加密字符串
  80.          * @param privateKey
  81.          *            私钥
  82.          * @return 铭文
  83.          * @throws Exception
  84.          *             解密过程中的异常信息
  85.          */  
  86.         public static String decrypt(String str, String privateKey) throws Exception{
  87.                 //64位解码加密后的字符串
  88.                 byte[] inputByte = Base64.getDecoder().decode(str.getBytes("UTF-8"));
  89.                 //base64编码的私钥
  90.                 byte[] decoded = Base64.getDecoder().decode(privateKey);  
  91.        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));  
  92.                 //RSA解密
  93.                 Cipher cipher = Cipher.getInstance("RSA");
  94.                 cipher.init(Cipher.DECRYPT_MODE, priKey);
  95.                 String outStr = new String(cipher.doFinal(inputByte));
  96.                 return outStr;
  97.         }
  98.           public static final String KEY_ALGORITHM = "RSA";
  99.          /**
  100.      * 签名算法
  101.      */
  102.     public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
  103.     /**
  104.      * <p>
  105.      * 用私钥对信息生成数字签名
  106.      * </p>
  107.      *
  108.      * @param data 已加密数据
  109.      * @param privateKey 私钥(BASE64编码)
  110.      *
  111.      * @return
  112.      * @throws Exception
  113.      */
  114.     public static String sign(byte[] data, String privateKey) throws Exception {
  115.         byte[] keyBytes = Base641.decode(privateKey);
  116.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  117.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  118.         PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
  119.         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  120.         signature.initSign(privateK);
  121.         signature.update(data);
  122.         return Base641.encode(signature.sign());
  123.     }

  124.     /**
  125.      * <p>
  126.      * 校验数字签名
  127.      * </p>
  128.      *
  129.      * @param data 已加密数据
  130.      * @param publicKey 公钥(BASE64编码)
  131.      * @param sign 数字签名
  132.      *
  133.      * @return
  134.      * @throws Exception
  135.      *
  136.      */
  137.     public static boolean verify(byte[] data, String publicKey, String sign)
  138.             throws Exception {
  139.         byte[] keyBytes = Base641.decode(publicKey);
  140.         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
  141.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  142.         PublicKey publicK = keyFactory.generatePublic(keySpec);
  143.         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  144.         signature.initVerify(publicK);
  145.         signature.update(data);
  146.         return signature.verify(Base641.decode(sign));
  147.     }

  148. }
复制代码


回复

使用道具 举报

11

主题

17

帖子

83

积分

注册会员

Rank: 2

积分
83
 楼主| 发表于 2022-6-3 01:05:07 | 显示全部楼层
                                                                                                                           
  1. import java.math.BigInteger;  
  2. import java.security.Key;  
  3. import java.security.KeyFactory;  
  4. import java.security.interfaces.ECPrivateKey;  
  5. import java.security.interfaces.ECPublicKey;  
  6. import java.security.spec.ECFieldF2m;  
  7. import java.security.spec.ECParameterSpec;  
  8. import java.security.spec.ECPoint;  
  9. import java.security.spec.ECPrivateKeySpec;  
  10. import java.security.spec.ECPublicKeySpec;  
  11. import java.security.spec.EllipticCurve;  
  12. import java.security.spec.PKCS8EncodedKeySpec;  
  13. import java.security.spec.X509EncodedKeySpec;  
  14. import java.util.HashMap;  
  15. import java.util.Map;  
  16.   
  17. import javax.crypto.Cipher;  
  18. import javax.crypto.NullCipher;  
  19.   
  20. import sun.security.ec.ECKeyFactory;  
  21. import sun.security.ec.ECPrivateKeyImpl;  
  22. import sun.security.ec.ECPublicKeyImpl;  
  23.   

  24. public abstract class test13 extends Coder {  
  25.   
  26.     public static final String ALGORITHM = "EC";  
  27.     private static final String PUBLIC_KEY = "ECCPublicKey";  
  28.     private static final String PRIVATE_KEY = "ECCPrivateKey";  
  29.   
  30.     /**
  31.      * 解密<br>
  32.      * 用私钥解密
  33.      *  
  34.      * @param data
  35.      * @param key
  36.      * @return
  37.      * @throws Exception
  38.      */  
  39.     public static byte[] decrypt(byte[] data, String key) throws Exception {  
  40.         // 对密钥解密  
  41.         byte[] keyBytes = decryptBASE64(key);  
  42.   
  43.         // 取得私钥  
  44.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);  
  45.         KeyFactory keyFactory = ECKeyFactory.INSTANCE;  
  46.   
  47.         ECPrivateKey priKey = (ECPrivateKey) keyFactory  
  48.                 .generatePrivate(pkcs8KeySpec);  
  49.   
  50.         ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(priKey.getS(),  
  51.                 priKey.getParams());  
  52.   
  53.         // 对数据解密  
  54.         // TODO Chipher不支持EC算法 未能实现  
  55.         Cipher cipher = new NullCipher();  
  56.         // Cipher.getInstance(ALGORITHM, keyFactory.getProvider());  
  57.         cipher.init(Cipher.DECRYPT_MODE, priKey, ecPrivateKeySpec.getParams());  
  58.   
  59.         return cipher.doFinal(data);  
  60.     }  
  61.   
  62.     /**
  63.      * 加密<br>
  64.      * 用公钥加密
  65.      *  
  66.      * @param data
  67.      * @param privateKey
  68.      * @return
  69.      * @throws Exception
  70.      */  
  71.     public static byte[] encrypt(byte[] data, String privateKey)  
  72.             throws Exception {  
  73.         // 对公钥解密  
  74.         byte[] keyBytes = decryptBASE64(privateKey);  
  75.   
  76.         // 取得公钥  
  77.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);  
  78.         KeyFactory keyFactory = ECKeyFactory.INSTANCE;  
  79.   
  80.         ECPublicKey pubKey = (ECPublicKey) keyFactory  
  81.                 .generatePublic(x509KeySpec);  
  82.   
  83.         ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(pubKey.getW(),  
  84.                 pubKey.getParams());  
  85.   
  86.         // 对数据加密  
  87.         // TODO Chipher不支持EC算法 未能实现  
  88.         Cipher cipher = new NullCipher();  
  89.         // Cipher.getInstance(ALGORITHM, keyFactory.getProvider());  
  90.         cipher.init(Cipher.ENCRYPT_MODE, pubKey, ecPublicKeySpec.getParams());  
  91.   
  92.         return cipher.doFinal(data);  
  93.     }  
  94.   
  95.     /**
  96.      * 取得私钥
  97.      *  
  98.      * @param keyMap
  99.      * @return
  100.      * @throws Exception
  101.      */  
  102.     public static String getPrivateKey(Map<String, Object> keyMap)  
  103.             throws Exception {  
  104.         Key key = (Key) keyMap.get(PRIVATE_KEY);  
  105.   
  106.         return encryptBASE64(key.getEncoded());  
  107.     }  
  108.   
  109.     /**
  110.      * 取得公钥
  111.      *  
  112.      * @param keyMap
  113.      * @return
  114.      * @throws Exception
  115.      */  
  116.     public static String getPublicKey(Map<String, Object> keyMap)  
  117.             throws Exception {  
  118.         Key key = (Key) keyMap.get(PUBLIC_KEY);  
  119.   
  120.         return encryptBASE64(key.getEncoded());  
  121.     }  
  122.   
  123.     /**
  124.      * 初始化密钥
  125.      *  
  126.      * @return
  127.      * @throws Exception
  128.      */  
  129.     public static Map<String, Object> initKey() throws Exception {  
  130.         BigInteger x1 = new BigInteger(  
  131.                 "2fe13c0537bbc11acaa07d793de4e6d5e5c94eee8", 16);  
  132.         BigInteger x2 = new BigInteger(  
  133.                 "289070fb05d38ff58321f2e800536d538ccdaa3d9", 16);  
  134.   
  135.         ECPoint g = new ECPoint(x1, x2);  
  136.   
  137.         // the order of generator  
  138.         BigInteger n = new BigInteger(  
  139.                 "584600654932361167281474175359844834832911063", 10);  
  140.         // the cofactor  
  141.         int h = 2;  
  142.         int m = 163;  
  143.         int[] ks = { 7, 6, 3 };  
  144.         ECFieldF2m ecField = new ECFieldF2m(m, ks);  
  145.         // y^2+xy=x^3+x^2+1  
  146.         BigInteger a = new BigInteger("1", 2);  
  147.         BigInteger b = new BigInteger("1", 2);  
  148.   
  149.         EllipticCurve ellipticCurve = new EllipticCurve(ecField, a, b);  
  150.   
  151.         ECParameterSpec ecParameterSpec = new ECParameterSpec(ellipticCurve, g,  
  152.                 n, h);  
  153.         // 公钥  
  154.         ECPublicKey publicKey = new ECPublicKeyImpl(g, ecParameterSpec);  
  155.   
  156.         BigInteger s = new BigInteger(  
  157.                 "123400654932361167281474175359844834832914063", 10);  
  158.         // 私钥  
  159.         ECPrivateKey privateKey = new ECPrivateKeyImpl(s, ecParameterSpec);  
  160.   
  161.         Map<String, Object> keyMap = new HashMap<String, Object>(2);  
  162.   
  163.         keyMap.put(PUBLIC_KEY, publicKey);  
  164.         keyMap.put(PRIVATE_KEY, privateKey);  
  165.   
  166.         return keyMap;  
  167.     }  
  168.   
  169. }  
复制代码

ECC椭圆曲线加解密
回复

使用道具 举报

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

本版积分规则

教学服务系统

GMT+8, 2025-4-30 02:03 , Processed in 0.015517 second(s), 26 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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