Skip to content

Instantly share code, notes, and snippets.

@Haehnchen
Created May 14, 2017 15:43
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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);
@lekeCoder
Copy link

Thanks for these solutions. In Android,
Change this line byte[] bytes = Base64.decodeBase64(input); to byte[] bytes = Base64.decode(input,Base64.DEFAULT);

to get it to work

@rohit267
Copy link

I used your method to encrypt a pdf, everything is fine but the pdf is not opening.
https://stackoverflow.com/questions/60761300/pdf-encrypted-with-php-openssl-and-decrypted-in-java-android-studio-not-opening

@lekeCoder
Copy link

@rohit267 l am not sure if this encryption is used for file encryption.

@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