問題中提供的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中文網其他相關文章!