首先,步骤描述:
- 加密:
①随机生成32位的aseKey;
②通过aseKey生成加密的cipher,这里初始化 ENCRYPT_MODE 解密刚好相反,初始化DECRYPT_MODE
③通过加密cipher即可进行加密,Cipher.doFinal(content.getBytes(“UTF-8”))
④加密完成 - 解密:
①通过公钥加密aseKey,私钥解密aseKey,获取最初的32位随机数的key,最终来用其进行加解密。
②通过aseKey,初始化生成解密cipher,这里初始化 Cipher.DECRYPT_MODE,
③根据解密cipher进行解密,deCipher.doFinal(java.util.Base64.getDecoder().decode(str));
public class ExampleUnitTest {
private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvXe+pNk/oqMRL5wdjG5CWPxAK0lNoHqanS2NsGyej2SgO6yD6MtUFmrhdNnhe0rlGE9U5zrEEHwjiLPVE+SQ9atmMo0GTZwsI9drBkm0vSYjYIv5c7Uy5c0HZCcjCxGvQDPU6MmhtA4f4GUOD0XWYhqWO+U0spkh8uZGVq7CIXQIDAQAB";
private static final String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK9d76k2T+ioxEvnB2MbkJY/EArSU2gepqdLY2wbJ6PZKA7rIPoy1QWauF02eF7SuUYT1TnOsQQfCOIs9UT5JD1q2YyjQZNnCwj12sGSbS9JiNgi/lztTLlzQdkJyMLEa9AM9ToyaG0Dh/gZQ4PRdZiGpY75TSymSHy5kZWrsIhdAgMBAAECgYEAoVW1eCJMb8pcFUxtgmNIqMFJu/r12vNf9Mcpp7pvxJCzBs6Qnz4Gtso51R+Yq/wHkY4Le8xJFHaM0K/10ce36vUvcSE3ehM8JW2zH92s2t68wXP04p+qZhEWimFOXscLdnk6faw3RmB6kyXeR856weIzPMgcErSyTZPspphNw8ECQQDqn6/TwHPgywsnzjM3Z1Bg99/T86mqa0HIHIQadELnjpXWkj5V5HehTOYuMC//vKG07PDWHFGzBZ3KJThjlPGNAkEAv1gn6xZvMkGIvJd3xJ7WLSKsLRkvVWN++3JSP3OuZXry50BJV6f9wfsguefhUw4zHsEtd0ckmM9hXF95zCv2EQJBAJ/TkA8LduSW7E59ZN5E/rhPoqXbwqRY1ELhSgxLTpg2xVOZ4+TW8bdrjxG/ubLYaL+6+ISiXfU5yjc+C5+qgrECQQCXDmdlJi7ew/HIwOMibCq1Mzwt1kYR6RxkMVpREWhKYQfGHHBKLSsdqr2pRjASO5GL5AGauqVfpcg8/nrO/p2hAkBzXMDdP85oYCc9AUQoeGtRsThuURmQxoxBlzf+Zf1s7SiKkFivi4rqsLHhtsKVbU6/Vzt4JFxWBa4cG/m4W6ET";
/**
* 通过随机生成的字符串,生成密钥
* @param length
* @return
*/
private static String getRandomString(int length){
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<length;i++){
int number=random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
/**
* 生成公钥和私钥
*/
@Test
public void generateKey() throws Exception {
int keyLength = 1024;
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(keyLength);
KeyPair pair = kpg.genKeyPair();
byte[] publicKey = pair.getPublic().getEncoded();
byte[] privateKey = pair.getPrivate().getEncoded();
System.out.println("publicKey:" + Base64.getEncoder().encodeToString(publicKey));
System.out.println("privateKey:" + Base64.getEncoder().encodeToString(privateKey));
}
/**
* 密钥通过公钥进行加解密测试
*/
@Test
public void aseKeyEncodeAndDecode() throws Exception {
byte[] publicKey = Base64.getDecoder().decode(PUBLIC_KEY);
byte[] privateKey = Base64.getDecoder().decode(PRIVATE_KEY);
String aseKey = "zVNbGqMQGWfK8xquXBnhpFUjnFdhsG6t";
byte[] decodeBytes = encryptByPublicKey(aseKey.getBytes("UTF-8"), publicKey);
System.out.println("RSA decodeBytes:" + toHex(decodeBytes));
String decodeData = Base64.getEncoder().encodeToString(decodeBytes);
System.out.println("RSA decodeData:" + decodeData);
byte[] sourceBytes = decryptByPrivateKey(Base64.getDecoder().decode(decodeData), privateKey);
System.out.println("RSA sourceData:" + new String(sourceBytes));
}
/**
* 测试aes的加解密
*/
@Test
public void cipherWithEncryptAndDecrypt() throws Exception {
String aseKey = getRandomString(32);
String decodeData;
byte[] sourceBytes;
byte[] decodeBytes;
Cipher cipher = generateAESCipher(aseKey);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
String content = "helloworld!!!ld!!!!!_" + i + "\n";
decodeBytes = cipher.doFinal(content.getBytes("UTF-8"));
decodeData = Base64.getEncoder().encodeToString(decodeBytes);
System.out.println("AES decodeData:" + decodeData);
list.add(decodeData);
}
cipher = decryptCipher(aseKey);
for (int i = 0; i < list.size(); i++) {
decodeData = list.get(i);
sourceBytes = cipher.doFinal(Base64.getDecoder().decode(decodeData));
System.out.println("AES sourceData:" + new String(sourceBytes));
}
}
/**
* RSA算法
*/
public static final String RSA = "RSA";
/**加密方式,android的*/
/**加密方式,标准jdk的*/
/**
* 使用公钥加密
*/
public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
// 得到公钥对象
System.out.println("data=>" + toHex(data));
System.out.println("publicKey=>" + toHex(publicKey));
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
// 加密数据
Cipher cp = Cipher.getInstance(RSA);
cp.init(Cipher.ENCRYPT_MODE, pubKey);
return cp.doFinal(data);
}
/**
* 使用私钥解密
*/
public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
// 得到私钥对象
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
KeyFactory kf = KeyFactory.getInstance(RSA);
PrivateKey keyPrivate = kf.generatePrivate(keySpec);
// 解密数据
Cipher cp = Cipher.getInstance(RSA);
cp.init(Cipher.DECRYPT_MODE, keyPrivate);
byte[] arr = cp.doFinal(encrypted);
return arr;
}
/**
* 魔法数转换 没用上
*/
public static String toHex(byte[] buf) {
if (buf == null) {
return "";
}
String HEX = "0123456789ABCDEF";
StringBuffer sb = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
byte b = buf[i];
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
return sb.toString();
}
/**
* 获取加密的cipher
*/
private static Cipher generateAESCipher(String password) throws Exception {
byte[] rawKey = MessageDigest.getInstance("MD5").digest(password.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return cipher;
}
/**
* 获取解密的cipher
*/
private static Cipher decryptCipher(String password)
throws Exception {
byte[] rawKey = MessageDigest.getInstance("MD5").digest(password.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
return cipher;
}
//
@Test
public void decodeLogFile() throws Exception{
String filePath = "src/test/java/com/exampl/reborn/Log-05-19 18-13-14.log";
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
String s = br.readLine();
if (s != null && s.startsWith("DecodeAESKey:")) {
byte[] enBytes = Base64.getDecoder().decode(s.substring("DecodeAESKey:".length()));
byte[] aesKey = decryptByPrivateKey(enBytes, Base64.getDecoder().decode(PRIVATE_KEY));
System.out.println("aesKey=>" + new String(aesKey, "UTF-8"));
Cipher deCipher = decryptCipher(new String(aesKey, "UTF-8"));
String dFilePath = filePath.replace(".log", "_d.log");
BufferedOutputStream opt = new BufferedOutputStream(new FileOutputStream(dFilePath));
while ((s = br.readLine()) != null) {
byte[] bytes = deCipher.doFinal(Base64.getDecoder().decode(s));
opt.write(bytes);
opt.write('\n');
}
opt.flush();
opt.close();
}
br.close();
}
}