How can I decrypt AES-encrypted data in Java and Scala, given that the data was encrypted in Golang with a 128-bit key?

Linda Hamilton
Release: 2024-10-27 04:05:29
Original
525 people have browsed it

How can I decrypt AES-encrypted data in Java and Scala, given that the data was encrypted in Golang with a 128-bit key?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!