byte[] encrypt(byte[] plainText, String keySeed, byte[] iv) { if (plainText == null || iv == null) return null; try { SecretKey key = getSecretKey(keySeed); IvParameterSpec ivParm = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, key, ivParm); byte[] cipherText = cipher.doFinal(plainText); return cipherText; } catch (NoSuchAlgorithmException ex) { } catch (NoSuchPaddingException ex) { } catch (InvalidKeyException ex) { } catch (BadPaddingException ex) { } catch (IllegalBlockSizeException ex) { } catch (InvalidAlgorithmParameterException ex) { } return null; }
Decryption:
byte[] decrypt(byte[] cipherText, String keySeed, byte[] iv) { if (cipherText == null || iv == null) return null; try { SecretKey key = getSecretKey(keySeed); IvParameterSpec ivParm = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, key, ivParm); byte[] plaintext = cipher.doFinal(cipherText); return plaintext; } catch (NoSuchAlgorithmException ex) { } catch (NoSuchPaddingException ex) { } catch (InvalidKeyException ex) { } catch (BadPaddingException ex) { } catch (IllegalBlockSizeException ex) { } catch (InvalidAlgorithmParameterException ex) { } return null; }
Helper methods:
byte[] generateIv() { SecureRandom random = new SecureRandom(); byte bytes[] = new byte[16]; random.nextBytes(bytes); return bytes; }
SecretKey getSecretKey(String keySeed) throws NoSuchAlgorithmException { byte[] keySeedBytes = keySeed.getBytes(); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(keySeedBytes); byte[] dgBytes = md.digest(); // generate a 32 bytes key SecretKey key = new SecretKeySpec(dgBytes, 0, dgBytes.length, "AES"); return key; }
Test code:
void test() { byte[] b = new byte[] { 1, 2, 3, 10, 20, 30, 100}; String key = "mykey"; byte[] iv = generateIv(); byte[] enb = encrypt(b, key, iv); byte[] deb = decrypt(enb, key, iv); System.out.println(Arrays.equals(b, deb)); }
Output:
true
No comments:
Post a Comment