問題中提供的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