对称加密解密

Cipher本身可以加解密byte[],而且可以设定key和algorithm,安全性高。但是不能直接用于文本。因为UTF-8是可变长度的编码,有的字符需要用多个字节来表示,转换之后会出现byte[]数组长度、内容不一致的情况。

Base64也是对称加解密的,可以解决byte[]转文本的问题,但是无法设置key和algorithm,安全性差一些。

Cipher和Base64一起使用,可以有效的处理安全性和文本转换的问题。

private static final String key = "1234567890123456";
private static final String algorithm= "AES";
  //加密
	public static String encrypt(String str) {
		try {
			SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
			Cipher cipher = Cipher.getInstance(algorithm);
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte[] bytes = cipher.doFinal(str.getBytes());
			String encryptedText = Base64.getEncoder().encodeToString(bytes);
			//System.out.println("Encrypted Text: " + encryptedText);
			return encryptedText;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
  // 解密
	public static String decrypt(String str) {
		try {
			SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
			Cipher cipher = Cipher.getInstance(algorithm);
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(str));
			String decryptedText = new String(bytes);
			//System.out.println("Decrypted Text: " + decryptedText);
			return decryptedText;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值