AES(高级加密标准)是一种常用的对称加密算法,Java 提供了多种方式来进行 AES 解密。以下是两种常见的方式,包括依赖的 Maven 和 Gradle 坐标以及示例代码:
步骤流程:
Cipher
对象,指定解密模式(如 ECB、CBC 等)、密钥和初始化向量(如果适用)。Cipher
对象解密密文。Maven 依赖坐标:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
Gradle 依赖坐标:
implementation 'commons-codec:commons-codec:1.15'
示例代码:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AESDecryptExample {
public static void main(String[] args) throws Exception {
String encryptedText = "ENCRYPTED_TEXT_HERE"; // 用实际的加密文本替换
String secretKey = "SECRET_KEY_HERE"; // 用实际的密钥替换
byte[] decodedKey = Base64.decodeBase64(secretKey);
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] encryptedBytes = Base64.decodeBase64(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);
System.out.println("解密后的文本: " + decryptedText);
}
}
步骤流程:
Cipher
对象,指定解密模式、密钥和初始化向量(如果适用)。Cipher
对象解密密文。Maven 依赖坐标:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.68</version>
</dependency>
Gradle 依赖坐标:
implementation 'org.bouncycastle:bcprov-jdk15on:1.68'
示例代码:
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import java.security.Security;
import java.security.Key;
import java.security.spec.X509EncodedKeySpec;
import java.security.KeyFactory;
public class AESDecryptWithBouncyCastle {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String encryptedText = "ENCRYPTED_TEXT_HERE"; // 用实际的加密文本替换
String secretKey = "SECRET_KEY_HERE"; // 用实际的密钥替换
byte[] encryptedBytes = Base64.decode(encryptedText);
KeyFactory keyFactory = KeyFactory.getInstance("AES", "BC");
Key key = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(secretKey)));
Cipher cipher = Cipher.getInstance("AES", "BC");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);
System.out.println("解密后的文本: " + decryptedText);
}
}
请注意,这些示例假定你已经有了 AES 密钥和加密的文本。替换示例代码中的 "SECRET_KEY_HERE"
和 "ENCRYPTED_TEXT_HERE"
为你的实际密钥和加密文本。此外,这些示例也假定你已经导入了相应的依赖项。