AESの使用について

1991 ワード

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;
		}

次回の使用のために直接記録します