加密和解密是區塊鏈數據傳輸中不可缺少的技術點,現代密碼學包括對稱性加密和非對稱性加密兩個概念,區塊鏈系統裏面一般常用到的是非對稱加密。這裏把相關知識記錄一下。
(一)對稱加密(Symmetric Cryptography)
對稱加密是最快速、最簡單的一種加密方式,加密(encryption)與解密(decryption)用的是同樣的密鑰(secret key)。對稱加密有很多種算法,由於它效率很高,所以被廣泛使用在很多加密協議的核心當中。
對稱加密通常使用的是相對較小的密鑰,一般小於256 bit。因爲密鑰越大,加密越強,但加密與解密的過程越慢。如果你只用1 bit來做這個密鑰,那們可以先試着用0來解密,不行的話就再用1解;但如果你的密鑰有1 MB大,們可能永遠也無法破解,但加密和解密的過程要花費很長的時間。密鑰的大小既要照顧到安全性,也要照顧到效率,是一個trade-off。
所謂對稱加密算法即:加密和解密使用相同密鑰的算法。常見的有DES、3DES、AES、PBE等加密算法,這幾種算法安全性依次是逐漸增強的。
DES加密
DES是一種對稱加密算法,是一種非常簡便的加密算法,但是密鑰長度比較短。DES加密算法出自IBM的研究,後來被美國政府正式採用,之後開始廣泛流傳,但是近些年使用越來越少,因爲DES使用56位密鑰,以現代計算能力,24小時內即可被破解。
雖然如此,在某些簡單應用中,我們還是可以使用DES加密算法.
簡單的DES加密算法JAVA實現:
public class DESUtil {
private static final String KEY_ALGORITHM = "DES";
private static final String DEFAULT_CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";//默認的加密算法
/**
* DES 加密操作
*
* @param content 待加密內容
* @param key 加密密鑰
* @return 返回Base64轉碼後的加密數據
*/
public static String encrypt(String content, String key) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 創建密碼器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// 初始化爲加密模式的密碼器
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64.encodeBase64String(result);//通過Base64轉碼返回
} catch (Exception ex) {
Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* DES 解密操作
*
* @param content
* @param key
* @return
*/
public static String decrypt(String content, String key) {
try {
//實例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//使用密鑰初始化,設置爲解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
//執行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "utf-8");
} catch (Exception ex) {
Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* 生成加密祕鑰
*
* @return
*/
private static SecretKeySpec getSecretKey(final String key) {
//返回生成指定算法密鑰生成器的 KeyGenerator 對象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//DES 要求密鑰長度爲 56
kg.init(56, new SecureRandom(key.getBytes()));
//生成一個密鑰
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 轉換爲DES專用密鑰
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static void main(String[] args) {
String content = "hello,您好";
String key = "sde@5f98H*^hsff%dfs$r344&df8543*er";
System.out.println("content:" + content);
String s1 = DESUtil.encrypt(content, key);
System.out.println("s1:" + s1);
System.out.println("s2:"+ DESUtil.decrypt(s1, key));
}
}
3DES加密
3DES是一種對稱加密算法,在 DES 的基礎上,使用三重數據加密算法,對數據進行加密,它相當於是對每個數據塊應用三次 DES 加密算法。由於計算機運算能力的增強,原版 DES 密碼的密鑰長度變得容易被暴力破解;3DES 即是設計用來提供一種相對簡單的方法,即通過增加 DES 的密鑰長度來避免類似的***,而不是設計一種全新的塊密碼算法這樣來說,破解的概率就小了很多。缺點由於使用了三重數據加密算法,可能會比較耗性能。簡單的3DES加密算法實現:
(略)
(二)非對稱加密
非對稱加密算法需要兩個密鑰:公開密鑰(publickey)和私有密鑰(privatekey)。公開密鑰與私有密鑰是一對,如果用公開密鑰對數據進行加密,只有用對應的私有密鑰才能解密;如果用私有密鑰對數據進行加密,那麼只有用對應的公開密鑰才能解密。一般公鑰是公開的,私鑰是自己保存。因爲加密和解密使用的是兩個不同的密鑰,所以這種算法叫作非對稱加密算法。安全性相對對稱加密來說更高,是一種高級加密方式。
RSA加密
RSA是一種非對稱加密算法.RSA有兩個密鑰,一個是公開的,稱爲公開密鑰;一個是私密的,稱爲私密密鑰。公開密鑰是對大衆公開的,私密密鑰是服務器私有的,兩者不能互推得出。用公開密鑰對數據進行加密,私密密鑰可解密;私密密鑰對數據加密,公開密鑰可解密。速度較對稱加密慢。
簡單的RSA加密算法JAVA實現:
/**
- <p>
- RSA公鑰/私鑰/簽名工具包
- </p>
- <p>
- 字符串格式的密鑰在未在特殊說明情況下都爲BASE64編碼格式<br/>
- 由於非對稱加密速度極其緩慢,一般文件不使用它來加密而是使用對稱加密,<br/>
- 非對稱加密算法可以用來對對稱加密的密鑰加密,這樣保證密鑰的安全也就保證了數據的效率和安全
- </p>
-
*/
public class RSAUtils {/**
- 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/**
- 簽名算法
*/
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
- 獲取公鑰的key
*/
private static final String PUBLIC_KEY = "RSAPublicKey";
/**
- 獲取私鑰的key
*/
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**
- RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
- RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
- <p>
- 生成密鑰對(公鑰和私鑰)
- </p>
- @return
- @throws Exception
*/
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
- <p>
- 用私鑰對信息生成數字簽名
- </p>
- @param data 已加密數據
- @param privateKey 私鑰(BASE64編碼)
- @return
- @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64Utils.encode(signature.sign());
}
/**
- <p>
- 校驗數字簽名
- </p>
- @param data 已加密數據
- @param publicKey 公鑰(BASE64編碼)
- @param sign 數字簽名
- @return
- @throws Exception
-
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64Utils.decode(sign));
}
/**
- <P>
- 私鑰解密
- </p>
- @param encryptedData 已加密數據
- @param privateKey 私鑰(BASE64編碼)
- @return
- @throws Exception
/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
- <p>
- 公鑰解密
- </p>
- @param encryptedData 已加密數據
- @param publicKey 公鑰(BASE64編碼)
- @return
- @throws Exception
/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
- <p>
- 公鑰加密
- </p>
- @param data 源數據
- @param publicKey 公鑰(BASE64編碼)
- @return
- @throws Exception
/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 對數據加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
- <p>
- 私鑰加密
- </p>
- @param data 源數據
- @param privateKey 私鑰(BASE64編碼)
- @return
- @throws Exception
/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
- <p>
- 獲取私鑰
- </p>
- @param keyMap 密鑰對
- @return
- @throws Exception
*/
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64Utils.encode(key.getEncoded());
}
/**
- <p>
- 獲取公鑰
- </p>
- @param keyMap 密鑰對
- @return
- @throws Exception
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64Utils.encode(key.getEncoded());
}
- 加密算法RSA
}
/**
- <p>
- RSA公鑰/私鑰/簽名工具包
- </p>
- <p>
- 字符串格式的密鑰在未在特殊說明情況下都爲BASE64編碼格式<br/>
- 由於非對稱加密速度極其緩慢,一般文件不使用它來加密而是使用對稱加密,<br/>
- 非對稱加密算法可以用來對對稱加密的密鑰加密,這樣保證密鑰的安全也就保證了數據的安全
- </p>
-
*/
public class RSAUtils {/**
- 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/**
- 簽名算法
*/
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
- 獲取公鑰的key
*/
private static final String PUBLIC_KEY = "RSAPublicKey";
/**
- 獲取私鑰的key
*/
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**
- RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
- RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
- <p>
- 生成密鑰對(公鑰和私鑰)
- </p>
- @return
- @throws Exception
*/
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
- <p>
- 用私鑰對信息生成數字簽名
- </p>
- @param data 已加密數據
- @param privateKey 私鑰(BASE64編碼)
- @return
- @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64Utils.encode(signature.sign());
}
/**
- <p>
- 校驗數字簽名
- </p>
- @param data 已加密數據
- @param publicKey 公鑰(BASE64編碼)
- @param sign 數字簽名
- @return
- @throws Exception
-
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64Utils.decode(sign));
}
/**
- <P>
- 私鑰解密
- </p>
- @param encryptedData 已加密數據
- @param privateKey 私鑰(BASE64編碼)
- @return
- @throws Exception
/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
- <p>
- 公鑰解密
- </p>
- @param encryptedData 已加密數據
- @param publicKey 公鑰(BASE64編碼)
- @return
- @throws Exception
/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
- <p>
- 公鑰加密
- </p>
- @param data 源數據
- @param publicKey 公鑰(BASE64編碼)
- @return
- @throws Exception
/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 對數據加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
- <p>
- 私鑰加密
- </p>
- @param data 源數據
- @param privateKey 私鑰(BASE64編碼)
- @return
- @throws Exception
/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
- <p>
- 獲取私鑰
- </p>
- @param keyMap 密鑰對
- @return
- @throws Exception
*/
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64Utils.encode(key.getEncoded());
}
/**
- <p>
- 獲取公鑰
- </p>
- @param keyMap 密鑰對
- @return
- @throws Exception
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64Utils.encode(key.getEncoded());
}
- 加密算法RSA
}
public class Base64Utils {
/**
* 文件讀取緩衝區大小
*/
private static final int CACHE_SIZE = 1024;
/**
* <p>
* BASE64字符串解碼爲二進制數據
* </p>
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
/**
* <p>
* 二進制數據編碼爲BASE64字符串
* </p>
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
return new String(Base64.encode(bytes));
}
/**
* <p>
* 將文件編碼爲BASE64字符串
* </p>
* <p>
* 大文件慎用,可能會導致內存溢出
* </p>
*
* @param filePath
* 文件絕對路徑
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/**
* <p>
* BASE64字符串轉回文件
* </p>
*
* @param filePath
* 文件絕對路徑
* @param base64
* 編碼字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/**
* <p>
* 文件轉換爲二進制數組
* </p>
*
* @param filePath
* 文件路徑
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/**
* <p>
* 二進制數據寫文件
* </p>
*
* @param bytes
* 二進制數據
* @param filePath
* 文件生成目錄
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}