Golang 中的 AES 加密和 Java 中的解密
Java 中解密 AES 加密文本
要解密Golang函数生成的AES加密文本,需要Java实现。下面的 Java 代码演示了解密过程:
<code class="java">public class AESDecryption { public static String decode(String base64Text, byte[] key) throws Exception { 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) { try { String encryptedText = "c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0="; byte[] key = "0123456789abcdef".getBytes(); String decryptedText = decode(encryptedText, key); System.out.println("Decrypted text: " + decryptedText); } catch (Exception e) { e.printStackTrace(); } } }</code>
这段 Java 代码应该成功解密 Golang 函数生成的加密文本并返回原始明文。
Scala 版本
Scala 版本的解密代码如下:
<code class="scala">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)) } def main(args: Array[String]): Unit = { val encryptedText = "c1bpFhxn74yzHQs-vgLcW6E5yL8zJfgceEQgYl0=" val key = "0123456789abcdef" val decryptedText = decode(encryptedText, key) println("Decrypted text: " + decryptedText) } }</code>
此 Scala 代码还将解密 AES 加密文本并打印明文。
以上是如何使用Java和Scala解密Golang中生成的AES加密文本?的详细内容。更多信息请关注PHP中文网其他相关文章!