-
-
Save fuadarradhi/87dc9d5d96ed1d5ee1d3a6e7a7a68d0d to your computer and use it in GitHub Desktop.
PHP encrypt and JAVA decrypt with openssl and AES-128-CBC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment