关于AES的使用

private static String charset = "UTF-8";
		
		private static final String KEY_ALGORITHM = "AES/ECB/PKCS5Padding";
		
		private static final String AES = "AES";

		private static final byte[] KEY_BYTE_ARR = { (byte) 0x1d, (byte) 0x51, (byte) 0xa7, (byte) 0xc5, (byte) 0x27, (byte) 0x3b,
				(byte) 0x39, (byte) 0xe0, (byte) 0xfa, (byte) 0x72, (byte) 0xd0, (byte) 0x29, (byte) 0x83, (byte) 0x65,
				(byte) 0x9d, (byte) 0x74 };
		
		/**
		 * AES加密
		 * @param encryptContent 加密文本
		 * @param key 密钥
		 * @return 返回经过base64编码的文本
		 */
		public static String encrypt(String encryptContent, String key) {
			
			try {
				
				Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
				
				cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(editKey(key), AES));
				
				byte[] bytes = cipher.doFinal(encryptContent.getBytes(charset));
				
				return Base64.encodeBase64String(bytes);
			} catch(Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		
		/**
		 * AES解密
		 * @param decryptContent Base64 编码的密文
		 * @param key 密钥
		 * @return 返回原文文本
		 */
		public static String decrypt(String decryptContent,String key) {
			try {
				Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
				
				cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(editKey(key),AES));
				
				byte[] bytes = Base64.decodeBase64(decryptContent);
				
				bytes = cipher.doFinal(bytes);
				
				return new String(bytes, charset);
				
			} catch(Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		
		/**
		 * 用于填充key填补出现的异常
		 * @param key
		 * @return
		 */
		private static byte[] editKey(String key) {		
			
			byte[] key64 = key.getBytes();
			
			byte[] buff = new byte[KEY_BYTE_ARR.length];
			
			if (key64.length < KEY_BYTE_ARR.length) {
				for (int i = 0; i < KEY_BYTE_ARR.length; i++) {
					if (key64.length - 1 >= i) {
						buff[i] = key64[i];
					}else{
						buff[i] = KEY_BYTE_ARR[i];
					}
				}
			}
			return buff;
		}

直接记录下来以便下次使用



你可能感兴趣的:(签名与加密)