Golang中的AES加密和Java中的解密
Java中解密AES加密文字
要解密Golang函數產生的AES加密文本,需要Java實作。下面的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();
}
}
}
這段Java程式碼應該成功解密Golang函數產生的加密文字並傳回原始明文。
Scala版本
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)
}
}
此 Scala 程式碼也會解密 AES 加密文字並列印明文。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3