加密算法---RSA 非对称加密原理及使用
生活随笔
收集整理的這篇文章主要介紹了
加密算法---RSA 非对称加密原理及使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
加密算法---RSA 非對稱加密原理及使用
- 一 非對稱加密原理介紹
- 二 加密解密測試
- 2.1 加密解密工具類
- 2.2 測試
一 非對稱加密原理介紹
非對稱加密算法中,有兩個密鑰:公鑰和私鑰。它們是一對,如果用公鑰進行加密,只有用對應的私鑰才能解密;如果用私鑰進行加密,只有用對應的公鑰才能解密。
????非對稱加密算法實現機密信息的交換過程為:甲方生成一對密鑰并將其中一個作為公鑰向其他方公開;得到該公鑰的乙方使用該密鑰對機密信息進行加密后發送給甲方;甲方再用自己的另一個專用密鑰對加密后的信息進行解密。
????最有名的非對稱加密算法當屬 RSA 了,本文將對 RSA 算法的加/解密過程進行詳細剖析。
????非對稱加密擁有兩把密鑰。
????
RSA —— 經典的非對稱加密算法
二 加密解密測試
2.1 加密解密工具類
import lombok.extern.slf4j.Slf4j;import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.HashMap; import java.util.Map;@Slf4j public class EncryptUtils {/*** sha 加密** @param str* @return*/public static String sha(String str) {String sha256Str = "";try {MessageDigest sha256Deget = MessageDigest.getInstance("SHA-256");byte[] sha256Encode = sha256Deget.digest(str.getBytes());sha256Str = ByteToHexStr(sha256Encode);} catch (Exception e) {log.info("FRLOG:SHA256加密異常::", e.getMessage());}return sha256Str;}/*** byte數組轉16進制字符串** @param bytes* @return*/private static String ByteToHexStr(byte[] bytes) {String hexStr = "";for (int i = 0; i < bytes.length; i++) {int temp = bytes[i] & 0xff;String tempHex = Integer.toHexString(temp);if (tempHex.length() < 2) {hexStr += "0" + tempHex;} else {hexStr += tempHex;}}return hexStr;} /**--------------------------對稱加密aes----------------------------------*//*** aes 加密** @param str* @param privateKey* @return*/public static String aesEncrypt(String str, String privateKey) {try {// 生成密鑰對象SecretKey secKey = generateAesKey(privateKey.getBytes());// 獲取 AES 密碼器Cipher cipher = Cipher.getInstance("AES");// 初始化密碼器(加密模型)cipher.init(Cipher.ENCRYPT_MODE, secKey);// 加密數據, 返回密文byte[] cipherBytes = cipher.doFinal(str.getBytes()); // return new BASE64Encoder().encodeBuffer(cipherBytes);return Base64.getEncoder().encodeToString(cipherBytes);} catch (Throwable e) {log.info("aes 加密異常", e.getMessage());}return null;}/*** aes 解密** @param str* @param privateKey* @return*/public static String aesDecrypt(String str, String privateKey) {try {// 生成密鑰對象SecretKey secKey = generateAesKey(privateKey.getBytes());// 獲取 AES 密碼器Cipher cipher = Cipher.getInstance("AES");// 初始化密碼器(加密模型)cipher.init(Cipher.DECRYPT_MODE, secKey);byte[] decode = Base64.getDecoder().decode(str);// 加密數據, 返回密文byte[] cipherBytes = cipher.doFinal(decode);return new String(cipherBytes);} catch (Throwable e) {log.info("aes 解密異常 ", e.getMessage());}return null;}/*** 生成密鑰對象*/private static SecretKey generateAesKey(byte[] key) throws Exception {// 創建安全隨機數生成器SecureRandom random = SecureRandom.getInstance("SHA1PRNG");// 設置 密鑰key的字節數組 作為安全隨機數生成器的種子random.setSeed(key);// 創建 AES算法生成器KeyGenerator gen = KeyGenerator.getInstance("AES");// 初始化算法生成器gen.init(128, random);// 生成 AES密鑰對象, 也可以直接創建密鑰對象: return new SecretKeySpec(key, ALGORITHM);return gen.generateKey();} /**-------------------------- base64加密 ----------------------------------*//*** base64加密** @param key* @return*/public static String base64Encode(byte[] key) {String result = Base64.getEncoder().encodeToString(key);return result;}/*** base64解密** @param key* @return*/public static byte[] base64DecodeB(String key) {byte[] result = null;result = Base64.getDecoder().decode(key);return result;}/*** 是否被base64加密過** @param str* @return*/public static boolean isBase64(String str) {if (str == null || str.trim().length() == 0) {return false;} else {if (str.length() % 4 != 0) {return false;}char[] strChars = str.toCharArray();for (char c : strChars) {if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=') {continue;} else {return false;}}return true;}} /**-------------------------- 對稱加密des ----------------------------------*//*** des加密** @param datasource* @param password* @return*/public static String desEncrypt(String datasource, String password) {try {SecureRandom random = new SecureRandom();DESKeySpec desKey = new DESKeySpec(password.getBytes());// 創建一個密匙工廠,然后用它把DESKeySpec轉換成SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey securekey = keyFactory.generateSecret(desKey);// Cipher對象實際完成加密操作Cipher cipher = Cipher.getInstance("DES");// 用密匙初始化Cipher對象cipher.init(Cipher.ENCRYPT_MODE, securekey, random);// 現在,獲取數據并加密// 正式執行加密操作return base64Encode(cipher.doFinal(datasource.getBytes()));} catch (Throwable e) {log.info("des 加密異常", e.getMessage());}return null;}/*** des 解密** @param src* @param password* @return* @throws Exception*/public static String desDecrypt(String src, String password) {try {// DES算法要求有一個可信任的隨機數源SecureRandom random = new SecureRandom();// 創建一個DESKeySpec對象DESKeySpec desKey = new DESKeySpec(password.getBytes("UTF-8"));// 創建一個密匙工廠SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 將DESKeySpec對象轉換成SecretKey對象SecretKey securekey = keyFactory.generateSecret(desKey);// Cipher對象實際完成解密操作Cipher cipher = Cipher.getInstance("DES");// 用密匙初始化Cipher對象cipher.init(Cipher.DECRYPT_MODE, securekey, random);// 真正開始解密操作return new String(cipher.doFinal(base64DecodeB(src)));} catch (Throwable e) {log.info("des 解密異常", e.getMessage());}return null;} /**-------------------------- 非對稱加密RSA ----------------------------------*//*** 隨機生成RSA密鑰對** @return privateKey, publicKey* @throws NoSuchAlgorithmException*/public static Map<String, String> genRSAKeyPair() throws NoSuchAlgorithmException {// KeyPairGenerator類用于生成公鑰和私鑰對,基于RSA算法生成對象KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");// 初始化密鑰對生成器,密鑰大小為96-1024位keyPairGen.initialize(1024, new SecureRandom());// 生成一個密鑰對,保存在keyPair中KeyPair keyPair = keyPairGen.generateKeyPair();// 得到私鑰RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();// 得到公鑰RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();String publicKeyString = base64Encode(publicKey.getEncoded());// 得到私鑰字符串String privateKeyString = base64Encode(privateKey.getEncoded());// 將公鑰和私鑰保存到MapMap<String, String> result = new HashMap<String, String>();result.put("publicKey", publicKeyString.replaceAll("\n", "").replace("\r", "").trim());result.put("privateKey", privateKeyString.replaceAll("\n", "").replace("\r", "").trim());return result;}/*** rsa 加密** @param str* @param publicKey* @return* @throws Exception*/public static String rsaEncrypt(String str, String publicKey) throws Exception {//base64編碼的公鑰byte[] decoded = base64DecodeB(publicKey);RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));//RSA加密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, pubKey);String outStr = base64Encode(cipher.doFinal(str.getBytes("UTF-8")));return outStr;}/*** rsa解密** @param str* @param privateKey* @return* @throws Exception*/public static String rsaDecrypt(String str, String privateKey) throws Exception {//64位解碼加密后的字符串byte[] inputByte = base64DecodeB(str);//base64編碼的私鑰byte[] decoded = base64DecodeB(privateKey);RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));//RSA解密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, priKey);String outStr = new String(cipher.doFinal(inputByte));return outStr;}}2.2 測試
1、生成公鑰私鑰
2、用公鑰加密、私鑰解密
總結
以上是生活随笔為你收集整理的加密算法---RSA 非对称加密原理及使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云呐|RFID资产管理系统技术使消防设备
- 下一篇: python renamer模块_Pyt