AES解密測試
This commit is contained in:
@@ -1,31 +1,53 @@
|
||||
package com.yunbao.common.utils;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class AesUtils {
|
||||
|
||||
public static String decrypt(String encrypted) {
|
||||
/**
|
||||
* 使用AES/ECB/PKCS5Padding模式解密数据
|
||||
*
|
||||
* @param encryptedData 加密后的字节数组(Base64解码后的结果,如果原始数据是Base64编码的话)
|
||||
* @param keyBytes AES密钥(16/24/32字节长,对应AES-128/192/256)
|
||||
* @return 解密后的明文字节数组,如果解密失败则返回null
|
||||
*/
|
||||
public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes) {
|
||||
try {
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec("76b60dd0a5d7cafdqqew".getBytes(), "AES");
|
||||
Cipher cipher = Cipher.getInstance("AES");
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
|
||||
byte[] original = cipher.doFinal(hexToByteArray(encrypted));
|
||||
return new String(original);
|
||||
// 创建密钥规格
|
||||
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES-128-ECB");
|
||||
|
||||
// 获取Cipher实例并初始化为解密模式
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, keySpec);
|
||||
// 执行解密
|
||||
byte[] decryptedBytes = cipher.doFinal(encryptedData);
|
||||
// 返回解密后的字节数组
|
||||
return decryptedBytes;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
return null; // 解密失败时返回null
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] hexToByteArray(String hex) {
|
||||
if (hex == null || hex.length() == 0) {
|
||||
return null;
|
||||
/**
|
||||
* 如果需要将解密后的字节数组转换为字符串(注意:这可能会导致数据丢失或乱码)
|
||||
*
|
||||
* @param encryptedData 加密后的字节数组(或Base64解码后的结果)
|
||||
* @param keyBytes AES密钥
|
||||
* @param charset 用于将解密后的字节数组转换为字符串的字符集
|
||||
* @return 解密后的字符串,如果解密失败则返回null
|
||||
*/
|
||||
public static String decryptToString(byte[] encryptedData, byte[] keyBytes, String charset) {
|
||||
byte[] decryptedBytes = decrypt(encryptedData, keyBytes);
|
||||
if (decryptedBytes != null) {
|
||||
// 尝试将字节数组转换为字符串(使用指定的字符集)
|
||||
try {
|
||||
return new String(decryptedBytes, charset);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
byte[] ba = new byte[hex.length() / 2];
|
||||
for (int i = 0; i < ba.length; i++) {
|
||||
ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
|
||||
}
|
||||
return ba;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -648,7 +648,7 @@
|
||||
<string name="welcome_pdlive">歡迎來到PDLIVE</string>
|
||||
<string name="newcomer">恭喜你獲得了新人獎勵</string>
|
||||
|
||||
<string name="FILE_PROVIDER">com.newpdlive.sy.fileprovider</string>
|
||||
<string name="FILE_PROVIDER">com.pdsylive.yo.fileprovider</string>
|
||||
<string name="ren">人</string>
|
||||
<string name="ge">個</string>
|
||||
<string name="count">數量</string>
|
||||
|
||||
Reference in New Issue
Block a user