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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
package aescipher;
import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec;
public class Encryption { public static enum Mode { ENCRYPT_MODE, DECRYPT_MODE; } public static final String CIPHER = "AES/CBC/PKCS5Padding"; protected Cipher cipher; protected Mode mode; protected byte[] iv; protected IvParameterSpec ivSpec; protected byte[] key; public Encryption(Mode cipherMode, byte[] key, byte[] iv) { try { this.key = key; cipher = Cipher.getInstance(CIPHER); ivSpec = new IvParameterSpec(iv); SecretKeySpec aesKey = new SecretKeySpec(key, "AES"); this.mode = cipherMode; if (cipherMode == Mode.ENCRYPT_MODE) { cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec); } else { cipher.init(Cipher.DECRYPT_MODE, aesKey, ivSpec); } } catch (InvalidKeyException ex) { Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidAlgorithmParameterException ex) { Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex); } this.iv = iv; } public byte[] crypt(byte[] in) { try { updateIV(); System.out.print("New IV: "); printBytes(this.cipher.getIV()); return cipher.doFinal(in); } catch (IllegalBlockSizeException ex) { Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex); } catch (BadPaddingException ex) { Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex); } return null; } public void printBytes(byte[] b) { System.out.print("("); for (int i = 0; i < b.length; i++) { System.out.print("0x" + Integer.toHexString(b[i])); if (i < b.length - 1) { System.out.print(", "); } } System.out.println(")"); } public void updateIV() { for (int i = 0; i < this.iv.length; i++) { if (i < iv.length/2) { iv[i] ^= iv[i + 1]; if (iv[i] > 127) { iv[i] = 0x0A; } iv[i] ^= iv[i + 3]; if (iv[i] > 127) { iv[i] = 0x0D; } } else { iv[i] ^= iv[i - 3]; if (iv[i] > 127) { iv[i] = 0x0C; } iv[i] ^= iv[i - 2]; if (iv[i] > 127) { iv[i] = 0x1D; } } } } }
|