Skip to content

Instantly share code, notes, and snippets.

@Haehnchen
Created May 14, 2017 15:43
Show Gist options
  • Save Haehnchen/3cb18c40fea2ab883ef1a7a8e25422dc to your computer and use it in GitHub Desktop.
Save Haehnchen/3cb18c40fea2ab883ef1a7a8e25422dc to your computer and use it in GitHub Desktop.
PHP encrypt and JAVA decrypt with openssl and AES-128-CBC
public static String decrypt(@NotNull String input, @NotNull String key){
byte[] bytes = Base64.decodeBase64(input);
if(bytes.length < 17) {
return null;
}
byte[] ivBytes = Arrays.copyOfRange(bytes, 0, 16);
byte[] contentBytes = Arrays.copyOfRange(bytes, 16, bytes.length);
try {
Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"),"AES");
IvParameterSpec iv = new IvParameterSpec(ivBytes,0, ciper.getBlockSize());
ciper.init(Cipher.DECRYPT_MODE, keySpec, iv);
return new String(ciper.doFinal(contentBytes));
} catch (
NoSuchAlgorithmException |
NoSuchPaddingException |
UnsupportedEncodingException |
InvalidAlgorithmParameterException |
InvalidKeyException |
IllegalBlockSizeException |
BadPaddingException ignored
) {
}
return null;
}
$iv = openssl_random_pseudo_bytes(16, $secure);
if (false === $secure || false === $iv) {
throw new \RuntimeException('iv generation failed');
}
$data = $iv . openssl_encrypt($data, 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA, $iv);
@rohit267
Copy link

sorry my fault, everything is working fine, had an issue with file permissions.

@sumeet-mibo
Copy link

Not compatible with android

@rohit267
Copy link

rohit267 commented Aug 20, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment