問題:
我已在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 中加密時如何在 Java 中解密 AES 加密文字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!