AES Encryption in Golang and Decryption in Java
The Golang code provided encrypts data using the AES algorithm with a 128-bit key. To decrypt this data, we can use a similar Java decoder to ensure compatibility between the two languages.
Java Decoder
<code class="java">String decode(String base64Text, byte[] key) throws InvalidAlgorithmParameterException,NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { byte[] inputArr = Base64.getUrlDecoder().decode(base64Text); SecretKeySpec skSpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding"); int blockSize = cipher.getBlockSize(); IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(inputArr, blockSize)); byte[] dataToDecrypt = Arrays.copyOfRange(inputArr, blockSize, inputArr.length); cipher.init(Cipher.DECRYPT_MODE, skSpec, iv); byte[] result = cipher.doFinal(dataToDecrypt); return new String(result, StandardCharsets.UTF_8); }</code>
Scala Decoder
<code class="scala">def decode(input:String, key:String) = { val cipher = Cipher.getInstance("AES/CFB/NoPadding") val blockSize = cipher.getBlockSize() val keyBytes = key.getBytes() val inputArr = Base64.getUrlDecoder().decode(input) val skSpec = new SecretKeySpec(keyBytes, "AES") val iv = new IvParameterSpec(inputArr.slice(0, blockSize).toArray) val dataToDecrypt = inputArr.slice(blockSize, inputArr.size) cipher.init(Cipher.DECRYPT_MODE, skSpec, iv) new String(cipher.doFinal(dataToDecrypt.toArray)) }</code>
Usage
To decrypt the encrypted text, use the provided Java or Scala decoder. For instance, if the encrypted text is "c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0=" and the key is "0123456789abcdef", the decrypted text would be "test text 123".
The above is the detailed content of How can I decrypt AES-encrypted data in Java and Scala, given that the data was encrypted in Golang with a 128-bit key?. For more information, please follow other related articles on the PHP Chinese website!