生活随笔
收集整理的這篇文章主要介紹了
SpringBoot+VUE 前端加密算法 RSA+DES
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前言
為了提高用戶登陸的安全性,公司準備整理一份相對安全的登陸模式。
想法
主流加密算法
主流加密算法
-
(一)對稱加密AES ,其特點是:算法簡單,加密速度快;
-
(二)非對稱加密方式,代表是RSA加密算法,其特點–采用的一對秘鑰機制(即加解密秘鑰不同),公鑰加密、私鑰解密,管理簡單,缺點是解密速度慢。
最終方式
具體過程是先由接收方創(chuàng)建RSA密鑰對,接收方通過Internet發(fā)送RSA公鑰到發(fā)送方,同時保存RSA私鑰。而發(fā)送方創(chuàng)建AES密鑰。并用該 AES密鑰加密待傳送的明文數(shù)據(jù),同時用接受的RSA公鑰加密AES密鑰,最后把用RSA公鑰加密后的AES密鑰同密文一起通過Internet傳輸發(fā)送 到接收方。當接收方收到這個被加密的AES密鑰和密文后,首先調用接收方保存的RSA私鑰,并用該私鑰解密加密的AES密鑰,得到AES密鑰。最后用該 AES密鑰解密密文得到明文。
基本流程
請求:
服務器端(server)生成密鑰對server給client自己的公鑰client生成AES密鑰(aesKey)client使用自己的RSA私鑰(privateKey)對請求明文數(shù)據(jù)(params)進行數(shù)字簽名將簽名加入到請求參數(shù)中,然后轉換為json格式client使用aesKey對json數(shù)據(jù)進行加密得到密文(data)client使用sever的RSA公鑰對aesKey進行加密(encryptkey)分別將data和encryptkey作為參數(shù)傳輸給服務器端
服務器端進行請求響應時將上面流程反過來即可
使用
安裝crypto-js
npm install crypto
-js
npm install jsencrypt
AES加密工具類
import CryptoJS from
'crypto-js'
import { JSEncrypt } from
'jsencrypt'
export function
createAesKey() {const expect
= 16let str
= Math.random().toString(36).substr(2)while (str
.length
< expect
) {str
+= Math.random().toString(36).substr(2)}str
= str
.substr(0, 16)return str
}
export function
AESencrypt(word
, keyStr
) {keyStr
= keyStr
? keyStr
: 'abcdefgabcdefg12';var key
= CryptoJS.enc
.Utf8
.parse(keyStr
); var srcs
= CryptoJS.enc
.Utf8
.parse(word
);var encrypted
= CryptoJS.DES
.encrypt(srcs
, key
, {mode
: CryptoJS.mode
.ECB
,padding
: CryptoJS.pad
.Pkcs7
});return encrypted
.ciphertext
.toString();
}
export function
RSAencrypt(pas
,publickey
) {let jse
= new JSEncrypt();jse
.setPublicKey(publickey
);return jse
.encrypt(pas
)}
服務端
RSA工具類
import org.apache.commons.codec.binary.Base64;import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;public class RSAUtil {public static final String KEY_ALGORITHM
= "RSA";public static final String SIGNATURE_ALGORITHM
= "MD5withRSA";private static final String PUBLIC_KEY
= "RSAPublicKey";private static final String PRIVATE_KEY
= "RSAPrivateKey";public static byte[] decryptBASE64(String key
) {return Base64.decodeBase64(key
);}public static String encryptBASE64(byte[] bytes
) {return Base64.encodeBase64String(bytes
);}public static String sign(byte[] data
, String privateKey
) throws Exception {byte[] keyBytes
= decryptBASE64(privateKey
);PKCS8EncodedKeySpec pkcs8KeySpec
= new PKCS8EncodedKeySpec(keyBytes
);KeyFactory keyFactory
= KeyFactory.getInstance(KEY_ALGORITHM
);PrivateKey priKey
= keyFactory
.generatePrivate(pkcs8KeySpec
);Signature signature
= Signature.getInstance(SIGNATURE_ALGORITHM
);signature
.initSign(priKey
);signature
.update(data
);return encryptBASE64(signature
.sign());}public static PrivateKey strToPrivateKey(String privateKey
) throws Exception {byte[] keyBytes
= decryptBASE64(privateKey
);PKCS8EncodedKeySpec pkcs8KeySpec
= new PKCS8EncodedKeySpec(keyBytes
);KeyFactory keyFactory
= KeyFactory.getInstance(KEY_ALGORITHM
);return keyFactory
.generatePrivate(pkcs8KeySpec
);}public static boolean verify(byte[] data
, String publicKey
, String sign
)throws Exception {byte[] keyBytes
= decryptBASE64(publicKey
);X509EncodedKeySpec keySpec
= new X509EncodedKeySpec(keyBytes
);KeyFactory keyFactory
= KeyFactory.getInstance(KEY_ALGORITHM
);PublicKey pubKey
= keyFactory
.generatePublic(keySpec
);Signature signature
= Signature.getInstance(SIGNATURE_ALGORITHM
);signature
.initVerify(pubKey
);signature
.update(data
);return signature
.verify(decryptBASE64(sign
));}public static byte[] decryptByPrivateKey(byte[] data
, String key
) throws Exception{byte[] keyBytes
= decryptBASE64(key
);PKCS8EncodedKeySpec pkcs8KeySpec
= new PKCS8EncodedKeySpec(keyBytes
);KeyFactory keyFactory
= KeyFactory.getInstance(KEY_ALGORITHM
);Key privateKey
= keyFactory
.generatePrivate(pkcs8KeySpec
);Cipher cipher
= Cipher.getInstance(keyFactory
.getAlgorithm());cipher
.init(Cipher.DECRYPT_MODE
, privateKey
);return cipher
.doFinal(data
);}public static byte[] decryptByPrivateKey(String data
, String key
)throws Exception {return decryptByPrivateKey(decryptBASE64(data
),key
);}public static byte[] decryptByPublicKey(byte[] data
, String key
)throws Exception {byte[] keyBytes
= decryptBASE64(key
);X509EncodedKeySpec x509KeySpec
= new X509EncodedKeySpec(keyBytes
);KeyFactory keyFactory
= KeyFactory.getInstance(KEY_ALGORITHM
);Key publicKey
= keyFactory
.generatePublic(x509KeySpec
);Cipher cipher
= Cipher.getInstance(keyFactory
.getAlgorithm());cipher
.init(Cipher.DECRYPT_MODE
, publicKey
);return cipher
.doFinal(data
);}public static byte[] encryptByPublicKey(String data
, String key
)throws Exception {byte[] keyBytes
= decryptBASE64(key
);X509EncodedKeySpec x509KeySpec
= new X509EncodedKeySpec(keyBytes
);KeyFactory keyFactory
= KeyFactory.getInstance(KEY_ALGORITHM
);Key publicKey
= keyFactory
.generatePublic(x509KeySpec
);Cipher cipher
= Cipher.getInstance(keyFactory
.getAlgorithm());cipher
.init(Cipher.ENCRYPT_MODE
, publicKey
);return cipher
.doFinal(data
.getBytes());}public static byte[] encryptByPrivateKey(byte[] data
, String key
)throws Exception {byte[] keyBytes
= decryptBASE64(key
);PKCS8EncodedKeySpec pkcs8KeySpec
= new PKCS8EncodedKeySpec(keyBytes
);KeyFactory keyFactory
= KeyFactory.getInstance(KEY_ALGORITHM
);Key privateKey
= keyFactory
.generatePrivate(pkcs8KeySpec
);Cipher cipher
= Cipher.getInstance(keyFactory
.getAlgorithm());cipher
.init(Cipher.ENCRYPT_MODE
, privateKey
);return cipher
.doFinal(data
);}public static String getPrivateKey(Map<String, Key> keyMap
)throws Exception {Key key
= (Key) keyMap
.get(PRIVATE_KEY
);return encryptBASE64(key
.getEncoded());}public static String getPublicKey(Map<String, Key> keyMap
)throws Exception {Key key
= keyMap
.get(PUBLIC_KEY
);return encryptBASE64(key
.getEncoded());}public static Map<String, Key> initKey() throws NoSuchAlgorithmException {KeyPairGenerator keyPairGen
= KeyPairGenerator.getInstance(KEY_ALGORITHM
);keyPairGen
.initialize(1024);KeyPair keyPair
= keyPairGen
.generateKeyPair();Map<String, Key> keyMap
= new HashMap(2);keyMap
.put(PUBLIC_KEY
, keyPair
.getPublic());keyMap
.put(PRIVATE_KEY
, keyPair
.getPrivate());return keyMap
;}
}
DES工具類
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Locale;public class DESUtil {public static String decryptedDES(String content
,String key
) {try {Cipher cipher
= Cipher.getInstance("DES/ECB/PKCS5Padding");cipher
.init(Cipher.DECRYPT_MODE
, generateKey(key
));byte[] buf
= cipher
.doFinal(hexStr2Bytes(content
));return new String(buf
, "utf-8");} catch (Throwable e
) {e
.printStackTrace();}return null;}private static SecretKey generateKey(String secretKey
)throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {SecretKeyFactory keyFactory
= SecretKeyFactory.getInstance("DES");DESKeySpec keySpec
= new DESKeySpec(secretKey
.getBytes());keyFactory
.generateSecret(keySpec
);return keyFactory
.generateSecret(keySpec
);}public static byte[] hexStr2Bytes(String src
) {src
= src
.trim().replace(" ", "").toUpperCase(Locale.US
);int m
= 0, n
= 0;int iLen
= src
.length() / 2;byte[] ret
= new byte[iLen
];for (int i
= 0; i
< iLen
; i
++) {m
= i
* 2 + 1;n
= m
+ 1;ret
[i
] = (byte) (Integer.decode("0x" + src
.substring(i
* 2, m
) + src
.substring(m
, n
)) & 0xFF);}return ret
;}
}
解密算法
前端入?yún)?br /> encryptedWords DES加密后的報文
encryptedKey RSA算法加密過的DES密鑰
import com.bull3d.core.tool.utils.RedisUtil;
import com.bull3d.system.user.cache.CacheNames;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class DecryptUtil {private RedisUtil redisUtil
;public String decrypt(String encryptedWords
, String encryptedKey
){String privateKey
= String.valueOf(redisUtil
.get(CacheNames.SRA_KRY_PRIVATE
));if (null == privateKey
){return "";}try {String decrypt
= new String(RSAUtil.decryptByPrivateKey(encryptedKey
,privateKey
));return DESUtil.decryptedDES(encryptedWords
,decrypt
);} catch (Exception e
) {e
.printStackTrace();return "";}}
}
前端獲取RSA密鑰,我其實在服務端設計密鑰對放在redis服務器中。過期時間為1天,如果過期則從新生成。
@ApiOperation(value
= "獲取RSA秘鑰")@GetMapping("/auth/rsa-key")public R<String> rsaKey(){String key
= authService
.getRsaKey();return R.data(key
);}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎
總結
以上是生活随笔為你收集整理的SpringBoot+VUE 前端加密算法 RSA+DES的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。