java AES解密ECB模式ZeroPadding填充

AES是分組加密的,16字節一組加密,最後可能會不足16字節的,所以需要padding補充到16字節。

ZeroPadding它是使用“0”作爲填充數據的填充方式,但是java提供了NoPadding.

NoPadding意思是不做填充,也滿足不了,那就自己手動改下吧。

package com.util;

import org.apache.commons.codec.binary.Base64;

import java.util.Arrays;

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

/**
 * ZeroPadding填充
 * 
 * @author libaibai
 * @version 1.0 
 */
public class AesUtils {

	// private static final String KEY_ALGORITHM = "AES";
	private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/NoPadding";// 默認的加密算法

	/**
	 * AES 加密操作
	 *
	 * @param content 待加密內容
	 * @param password 加密密碼
	 * @return 
	 */
	public static byte[] encrypt(String content, String password) {
		try {
			Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 創建密碼器
			int blockSize = cipher.getBlockSize();
			byte[] byteContent = content.getBytes();
			int plaintextLength = byteContent.length;
			if (plaintextLength % blockSize != 0) {
				plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
			}
			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(byteContent, 0, plaintext, 0, byteContent.length);
			cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化爲加密模式的密碼器
			//return cipher.doFinal(plaintext);// 加密
                        return Base64.encodeBase64String(cipher.doFinal(plaintext)).getBytes();//
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	/**
	 * AES 解密操作
	 *
	 * @param content
	 * @param password
	 * @return
	 */
	public static String decrypt(String content, String password) {
		try {
			// 實例化
			Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));// 初始化爲加密模式的密碼器
			// 執行操作
			byte[] result = cipher.doFinal(Base64.decodeBase64(content));// 解密
			return new String(result, "utf-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	/**
	 * 生成加密祕鑰
	 *
	 * @return
	 */
	private static SecretKeySpec getSecretKey(final String password) {
		int len = password.getBytes().length;
		if (len % 16 != 0) {
			len = len + (16 - (len % 16));
		}
		byte[] newpass = new byte[len];
		System.arraycopy(password.getBytes(), 0, newpass, 0, password.getBytes().length);
		SecretKeySpec keySpec = new SecretKeySpec(newpass, "AES");
		return keySpec;
	}

	public static void main(String[] args) {
		String str = "hK1yEuGwGuOXo/argbmMhHUyFC7C7QHDMrOGNCVhXrLTMSCMhE6BUt1ACSBJ4Pf9bWE46+c2np2j6elUbpcN6w==";
		String key = "1234567890abcdef";
		System.out.println(Arrays.toString(decrypt(str, key).getBytes()));
	}
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章