1. 程式人生 > 程式設計 >Java實現AES/CBC/PKCS7Padding加解密的方法

Java實現AES/CBC/PKCS7Padding加解密的方法

最近專案需要選擇一套對稱加密演算法,來滿足前後端之間的加解密操作。初步打算前端使用crypto-js來實現,後端使用java本身的加密演算法實現,但遇到了一個問題:java本身只支援NoPadding和PKCS5Padding,而crypto-js提供的padding方式沒有PKCS5Padding,所以不得以,前後端最終使用PKCS7Padding來實現功能.因此只能通過引入第三方jar包的方式讓jave支援pkcs7padding

引入依賴

<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk16</artifactId>
			<version>1.46</version>
		</dependency>

完整程式碼

package com.hzjd.miniapp.util;

import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.sun.istack.internal.NotNull;

public class AESUtil {
	private static final String CHARSET_NAME = "UTF-8";
	private static final String AES_NAME = "AES";
	// 加密模式
	public static final String ALGORITHM = "AES/CBC/PKCS7Padding";
	// 金鑰
	public static final String KEY = "1954682168745975";
	// 偏移量
	public static final String IV = "1954682168745975";
	static {
		Security.addProvider(new BouncyCastleProvider());
	}

	/**
	 * 加密
	 *
	 * @param content
	 * @param key
	 * @return
	 */
	public String encrypt(@NotNull String content) {
		byte[] result = null;
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(CHARSET_NAME),AES_NAME);
			AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE,keySpec,paramSpec);
			result = cipher.doFinal(content.getBytes(CHARSET_NAME));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Base64.encodeBase64String(result);
	}

	/**
	 * 解密
	 *
	 * @param content
	 * @param key
	 * @return
	 */
	public String decrypt(@NotNull String content) {
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(CHARSET_NAME),AES_NAME);
			AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());
			cipher.init(Cipher.DECRYPT_MODE,paramSpec);
			return new String(cipher.doFinal(Base64.decodeBase64(content)),CHARSET_NAME);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return StringUtils.EMPTY;
	}

	public static void main(String[] args) {
		AESUtil aes = new AESUtil();
		String contents = "121456465";
		String encrypt = aes.encrypt(contents);
		System.out.println("加密後:" + encrypt);
		String decrypt = aes.decrypt(encrypt);
		System.out.println("解密後:" + decrypt);
	}
}

總結

到此這篇關於Java實現AES/CBC/PKCS7Padding加解密的方法的文章就介紹到這了,更多相關Java實現AES/CBC/PKCS7Padding加解密內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!