public String encrypt(String salt, String iv, String passphrase, String plaintext) { try { SecretKey key = generateKey(salt, passphrase); byte[] encrypted = doFinal(Cipher.ENCRYPT_MODE, key, iv, plaintext.getBytes("UTF-8")); return base64(encrypted); } catch (UnsupportedEncodingException e) { throw fail(e); } }
/** * decrypt the cryted API key * * @param cryptedApiKey * the crypted API key * @return the decrypted API key */ public static String decryptApikey(String cryptedApiKey) { return AES_UTIL.decrypt(SALT, IV, "", cryptedApiKey); }
/** * encrypt the API key * * @param apiKey * the API key * @return the encrypted API key */ public static String encryptApikey(String apiKey) { return AES_UTIL.encrypt(SALT, IV, "", apiKey); } }
public AesUtil(int keySize, int iterationCount) { this.keySize = keySize; this.iterationCount = iterationCount; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (Exception e) { throw fail(e); } }
protected static String random(int length) { byte[] salt = new byte[length]; new SecureRandom().nextBytes(salt); return hex(salt); }
private SecretKey generateKey(String salt, String passphrase) { try { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), hex(salt), iterationCount, keySize); return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); } catch (Exception e) { throw fail(e); } }
public String decrypt(String salt, String iv, String passphrase, String ciphertext) { try { SecretKey key = generateKey(salt, passphrase); byte[] decrypted = doFinal(Cipher.DECRYPT_MODE, key, iv, base64(ciphertext)); return new String(decrypted, "UTF-8"); } catch (UnsupportedEncodingException e) { throw fail(e); } }
private static String decryptField(String value, String key) { return AES_UTIL.decrypt(SALT, IV, key, value); }
private static String encryptField(String value, String key) { return AES_UTIL.encrypt(SALT, IV, key, value); }