java 如何编写返回文本的模拟

bgtovc5b  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(136)

我不知道如何在Java中执行此操作:

$text = "YOU IN";
// get the password key via: `base64_encode(openssl_random_pseudo_bytes(32)) = gGwdF6FDd68C/ANEqlqgOrsLqqC11u2JYn7NEJP10DA` = and further:
$keyPass = base64_decode("gGwdF6FDd68C/ANEqlqgOrsLqqC11u2JYn7NEJP10DA=");
$rndBytes = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); // 0PLpHMRYGwDBgcBsbeI3Qw==
$encText = openssl_encrypt($text, 'aes-256-cbc', $keyPass, 0, $rndBytes); // n+hHeLU4eI9r23ckxOwBOA==

这样您也可以毫无问题地返回此文本:

echo openssl_decrypt(
    base64_decode("n+hHeLU4eI9r23ckxOwBOA=="),
    'aes-256-cbc',
    base64_decode("gGwdF6FDd68C/ANEqlqgOrsLqqC11u2JYn7NEJP10DA="),
    OPENSSL_RAW_DATA,
    base64_decode("0PLpHMRYGwDBgcBsbeI3Qw==")
); // YOU IN

在Java中如何实现这一点?
Java的任务是返回,而不是加密.
也就是说,得到的$encText总是不同的,而任何一个都适合openssl_decrypt
试着这样做:

final Decoder decoder = Base64.getDecoder();
final byte[] encBytes = decoder.decode("n+hHeLU4eI9r23ckxOwBOA=="),
             keyPass = decoder.decode("gGwdF6FDd68C/ANEqlqgOrsLqqC11u2JYn7NEJP10DA="),
             rndBytes = decoder.decode("0PLpHMRYGwDBgcBsbeI3Qw==");
final String algo = "AES";
final SecretKeySpec secretKey = new SecretKeySpec(keyPass, algo);
final Cipher cipher = Cipher.getInstance(algo);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
final byte[] decBytes = cipher.doFinal(encBytes);
System.out.println(new String(decBytes));
//
// Return hieroglyphs:
//
// ��*�#�\��i�9���:�_�`�-U��

我不知道如何找到这个aes-256-cbc ...如果你尝试改变行:

cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(rndBytes));

崩溃并出现错误:
InvalidAlgorithmParameterException: ECB mode cannot use IV

68bkxrlz

68bkxrlz1#

好啊!明白了!谢谢你。

final Decoder decoder = Base64.getDecoder();
final byte[] encBytes = decoder.decode("n+hHeLU4eI9r23ckxOwBOA=="),
             keyPass = decoder.decode("gGwdF6FDd68C/ANEqlqgOrsLqqC11u2JYn7NEJP10DA="),
             rndBytes = decoder.decode("0PLpHMRYGwDBgcBsbeI3Qw==");
final String algo = "AES";
final SecretKeySpec secretKey = new SecretKeySpec(keyPass, algo);
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(rndBytes));
final byte[] decBytes = cipher.doFinal(encBytes);
System.out.println(new String(decBytes, StandardCharsets.UTF_8)); // YOU IN

相关问题