问题:
我已在 Go 中使用 AES 成功加密文本。然而,我在用 Java 解密加密文本时面临着挑战。您能否提供有关了解 Java 解密流程和工作 Java 解码器的帮助?
答案:
Java 解码器:
<code class="java">import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.IvParameterSpec; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKeySpec; public class AesDecrypter { public static String decode(String base64Text, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, 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 解码器:
<code class="scala">import java.nio.charset.StandardCharsets import javax.crypto._ import java.security.spec.IvParameterSpec import java.security.spec.SecretKeySpec import java.util.Base64 object AesDecrypter { def decode(input:String, key:String): 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>
演示:
出于演示目的,让我们对字符串“test text 123”进行编码用Go编写的加密函数并用Java(或Scala)编写的解密函数对其进行解码:
// Go encoder key := []byte("0123456789abcdef") text := "test text 123" encryptedText := encrypt(key, text) println(encryptedText) // prints c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0= // Java decoder byte[] keyBytes = "0123456789abcdef".getBytes(); String decodedText = AesDecrypter.decode(encryptedText, keyBytes); System.out.println(decodedText); // prints test text 123 // Scala decoder val decodedText = AesDecrypter.decode(encryptedText, "0123456789abcdef") println(decodedText) // prints test text 123
以上是在 Go 中加密时如何在 Java 中解密 AES 加密文本?的详细内容。更多信息请关注PHP中文网其他相关文章!