你好java实现AES加密
可以使用Java内置的Cipher类来实现AES加密。
以下是一个简单的示例代码:
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class AesEncryption {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
private static final String CHARSET = "UTF-8";
private static final String KEY = "my-secret-key-123";
public static void main(String[] args) {
try {
String plainText = "Hello, world!";
String encryptedText = encrypt(plainText);
System.out.println("Encrypted text: " + encryptedText);
String decryptedText = decrypt(encryptedText);
System.out.println("Decrypted text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encrypt(String plainText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
在上面的代码中,我们使用了AES算法和ECB模式进行加密,并使用PKCS5Padding填充方式。我们还定义了一个密钥KEY,用于加密和解密。
在encrypt()方法中,我们先获取一个Cipher实例,然后使用SecretKeySpec类创建一个密钥对象。接下来,我们使用init()方法初始化Cipher对象,并指定加密模式为ENCRYPT_MODE。最后,我们使用doFinal()方法对明文进行加密,并将加密结果转换为Base64编码的字符串返回。
在decrypt()方法中,我们先获取一个Cipher实例,然后使用SecretKeySpec类创建一个密钥对象。接下来,我们使用init()方法初始化Cipher对象,并指定加密模式为DECRYPT_MODE。然后,我们使用Base64类将加密后的字符串转换为字节数组,并使用doFinal()方法对密文进行解密。最后,我们将解密后的字节数组转换为字符串返回
原文地址: http://www.cveoy.top/t/topic/envA 著作权归作者所有。请勿转载和采集!