对称加密算法(DES、DESede、AES)

说明:

对称加密指加密与解密所使用的密钥为同一个,密钥生成后需要保存起来(一般保存在服务器,使用时从服务器端获取),用于在加密与解密时使用。

DES算法:
algorithm:DES
cipher:DES/ECB/PKCS5Padding

DESede算法(三重DES):
algorithm:DESede
cipher:DESede/ECB/PKCS5Padding

AES算法:
algorithm:AES
cipher:AES/ECB/PKCS5Padding


使用:

public class DESedeUtil {
	private static final String algorithm = "AES"; // 可以是DES、DESede(三重DES)、AES
	private static final String cipher = "AES/ECB/PKCS5Padding"; // 可以是DES/ECB/PKCS5Padding、DESede/ECB/PKCS5Padding、AES/ECB/PKCS5Padding

	public static void main(String[] args) {
		String key = generateKey(); // 产生密钥,需要存起来下次使用
		System.out.println("密钥为: " + key);

		String password = "123456";
		String desPwd = encrypt(key, password);
		System.out.println("加密后为: " + desPwd);
		System.out.println("原密码为: " + decrypt(key, desPwd));
	}

	/**
	 * 产生密钥
	 */
	public static String generateKey() {
		try {
			SecureRandom sr = new SecureRandom();
			KeyGenerator kg = KeyGenerator.getInstance(algorithm);
			kg.init(sr);
			// 产生密钥对象
			SecretKey secretKey = kg.generateKey();
			// 对密钥字节数组进行Base64处理
			return Base64.encode(secretKey.getEncoded());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 加密
	 * 
	 * @param key 密钥
	 * @param password 明文密码
	 * @return 返回加密后的密码
	 */
	public static String encrypt(String key, String password) {
		try {
			SecretKey deskey = new SecretKeySpec(Base64.decode(key), algorithm);
			Cipher c1 = Cipher.getInstance(cipher);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			byte[] biff = c1.doFinal(password.getBytes());
			return Base64.encode(biff);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param key 密钥
	 * @param password 加密过的密码
	 * @return 返回解密后的密码
	 */
	public static String decrypt(String key, String password) {
		try {
			SecretKey deskey = new SecretKeySpec(Base64.decode(key), algorithm);
			Cipher c1 = Cipher.getInstance(cipher);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return new String(c1.doFinal(Base64.decode(password)));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}

}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值