【Java加密解密】AES加密算法

AES加密和解密JDK和BC代码
// JDK AES算法实现
	private static void jdkAES() {
		try {
			// 生成密钥
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			keyGenerator.getProvider();
			System.out.println(keyGenerator.getProvider());
			keyGenerator.init(new SecureRandom());
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] bytesKey = secretKey.getEncoded();

			// key转换
			SecretKeySpec key = new SecretKeySpec(bytesKey, "AES");

			// 加密
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			String src = "加密的字符串";
			byte[] result = cipher.doFinal(src.getBytes());
			System.out.println("result aes encrypt:"
					+ Hex.encodeHexString(result));

			// 解密
			cipher.init(Cipher.DECRYPT_MODE, key);
			result = cipher.doFinal(result);
			System.out.println("result aes decrypt:" + new String(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// bc的AES实现
	private static void bcAES() {
		try {

			Security.addProvider(new BouncyCastleProvider());

			// 生成密钥
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES", "BC");
			keyGenerator.getProvider();
			System.out.println(keyGenerator.getProvider());
			keyGenerator.init(new SecureRandom());//AES算法,长度超过128位,受到美国法律限制,需要替换授权
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] bytesKey = secretKey.getEncoded();

			// key转换
			SecretKeySpec key = new SecretKeySpec(bytesKey, "AES");

			// 加密
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			String src = "加密的字符串";
			byte[] result = cipher.doFinal(src.getBytes());
			System.out.println("result aes encrypt:"
					+ Hex.encodeHexString(result));

			// 解密
			cipher.init(Cipher.DECRYPT_MODE, key);
			result = cipher.doFinal(result);
			System.out.println("result aes decrypt:" + new String(result));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

BC实现的时候 如果超过128,会报错。这是美国法律的规定。

解决方法网上有 可以替换jar来搞定。


你可能感兴趣的:(【Java加密解密】AES加密算法)