zl程序教程

您现在的位置是:首页 >  后端

当前栏目

用java进行base64加密

JAVA加密 进行 base64
2023-09-27 14:22:49 时间

首先定义一组密钥,加密和解密使用同一组密钥

private final String key = "hahahahahaha";

也可以随机生成密钥

/**

* 生成随机密钥

* @param keySize 密钥大小推荐128 256

* @return

* @throws NoSuchAlgorithmException

*/

public static String generateSecret(int keySize) throws NoSuchAlgorithmException {

KeyGenerator generator = KeyGenerator.getInstance("AES");

generator.init(keySize, new SecureRandom());

SecretKey key = generator.generateKey();

return byteToHexString(key.getEncoded());

}

加密

/**

* 加密

* @param strToEncrypt 待加密字符串

* @param secret 密钥

* @return 密文

* @throws UnsupportedEncodingException

* @throws NoSuchAlgorithmException

* @throws NoSuchPaddingException

* @throws InvalidKeyException

* @throws BadPaddingException

* @throws IllegalBlockSizeException

*/

public static String encrypt(String strToEncrypt, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

SecretKeySpec secretKey = getKey(secret);

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));

}

解密

/**

* 解密

* @param strToDecrypt 待解密字符串

* @param secret 密钥

* @return 明文

* @throws UnsupportedEncodingException

* @throws NoSuchAlgorithmException

* @throws NoSuchPaddingException

* @throws InvalidKeyException

* @throws BadPaddingException

* @throws IllegalBlockSizeException

*/

public static String decrypt(String strToDecrypt, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

SecretKeySpec secretKey = getKey(secret);

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

cipher.init(Cipher.DECRYPT_MODE, secretKey);

return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));

}