问题中提供的AES的Golang加密函数使用高级加密标准(AES)算法对字符串进行加密,以 Base64 编码生成密文。为了在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();
}
}
}
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)
}
}
Java和Scala解密函数均以密文和密钥为输入,使用AES/CFB/NoPadding算法对密文进行解密,并将解密后的明文以字符串形式返回。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3