问题中提供的 AES 的 Golang 加密函数使用高级加密标准(AES)算法对字符串进行加密,以 Base64 编码生成密文。为了用Java解密这个密文,我们需要一个合适的解密函数。
<code class="java">import java.util.Base64; import javax.crypto.*; import javax.crypto.spec.*; public class AESDecryption { 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); } public static void main(String[] args) { // Encryption result from the Go function. String base64Text = "c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0="; // The encryption key (same as in Go). byte[] key = "0123456789abcdef".getBytes(); try { // Decrypt the ciphertext. String decrypted = decode(base64Text, key); // Print the decrypted text. System.out.println(decrypted); } catch (Exception e) { e.printStackTrace(); } } }</code>
<code class="scala">import java.nio.charset.StandardCharsets import javax.crypto._ import javax.crypto.spec.{IvParameterSpec, SecretKeySpec} import java.util.Base64 object AESDecryption { 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), StandardCharsets.UTF_8) } def main(args: Array[String]): Unit = { // Encryption result from the Go function. val base64Text = "c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0=" // The encryption key (same as in Go). val key = "0123456789abcdef" // Decrypt the ciphertext. val decrypted = decode(base64Text, key) // Print the decrypted text. println(decrypted) } }</code>
Java和Scala解密函数以密文和密钥作为输入,使用 AES/CFB/NoPadding 算法解密密文,并将解密后的明文作为字符串返回。
以上是考虑到 Golang 加密,如何在 Java 和 Scala 中解密 AES 加密文本?的详细内容。更多信息请关注PHP中文网其他相关文章!