利用Java cipher 对aes+base64 加密与解密


	//aes加密+base64加密
	public static String encryptPKCS5(String source, String key) throws Exception {
		byte[] sourceBytes = source.getBytes(StandardCharsets.UTF_8);
		byte[] keyBytes = key.getBytes();
		//Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(1, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(key.substring(0, 16).getBytes()));
		byte[] decrypted = cipher.doFinal(sourceBytes);
		return Base64.encodeBase64String(decrypted);
	}


	//base64解密+aes解密
	public static String dncryptPKCS5(String source, String key) throws Exception {
		byte[] sourceBytes = Base64.decodeBase64(source);
		//byte[] sourceBytes = source.getBytes(StandardCharsets.UTF_8);
		byte[] keyBytes = key.getBytes();
		//Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(2, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(key.substring(0, 16).getBytes()));

		byte[] decrypted = cipher.doFinal(sourceBytes);

		return new String(decrypted);
	}

 

你可能感兴趣的:(利用Java cipher 对aes+base64 加密与解密)