1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| import org.apache.commons.codec.binary.Base64; import java.nio.charset.Charset; import java.security.*; import java.util.Scanner; import javax.crypto.*;
public class Aes { static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; static final String ALGORITHM = "AES"; public static SecretKey generateKey() throws NoSuchAlgorithmException { KeyGenerator secretGenerator = KeyGenerator.getInstance(ALGORITHM); SecureRandom secureRandom = new SecureRandom(); secretGenerator.init(256, secureRandom); SecretKey secretKey = secretGenerator.generateKey();
return secretKey; } public static byte[] genIV() throws NoSuchAlgorithmException { SecureRandom secureRandom = new SecureRandom(); byte[] iv = new byte[16]; secureRandom.nextBytes(iv);
return iv; } static Charset charset = Charset.forName("UTF-8"); public static byte[] encrypt(String content, SecretKey secretKey, byte[] iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { return aes(content.getBytes(charset), Cipher.ENCRYPT_MODE, secretKey, iv); } public static String decrypt(byte[] contentArray, SecretKey secretKey, byte[] iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { byte[] result = aes(contentArray, Cipher.DECRYPT_MODE, secretKey, iv); return new String(result, charset); } private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { Cipher cipher = Cipher.getInstance(TRANSFORMATION); IvParameterSpec IVParamSpec = new IvParameterSpec(iv); cipher.init(mode, secretKey, IVParamSpec); byte[] result = cipher.doFinal(contentArray); return result; } public static void main(String[] args) { Scanner s = new Scanner(System.in); String content = s.next(); try { SecretKey secretKey = generateKey(); byte[] iv = genIV(); byte[] encryptResult = encrypt(content, secretKey, iv); System.out.println("encryption:" + Base64.encodeBase64String(encryptResult)); String decryptResult = decrypt(encryptResult, secretKey, iv); System.out.println("decryption:" + decryptResult); } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) { e.printStackTrace(); } } }
|