【发布时间】:2019-04-15 14:10:40
【问题描述】:
我需要加密 POST 请求中的参数(以交换身份验证令牌)。 到目前为止,PHP 做得很好,我可以做到并且请求成功。下面是 PHP 加密脚本(不能修改 PHP 代码)。
<?php
$shared_secret = "dummy_secret";
// Genere user Json
$userJson = json_encode(array(
"external_id" => "30123134", //Required
"email" => "jperez@gmail.com",
"name" => "Jose",
"lastname" => "Perez"
));
// Generate nonce (initialization vector)
$nonce = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC) ,MCRYPT_RAND);
// Encrypt user Json to generate the encrypted form
$encryptedForm =mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $shared_secret, $userJson, MCRYPT_MODE_CBC, $nonce);
// Encode the encrypted form and the nonce
$encryptedForm = base64_encode($encryptedForm);
$nonce = base64_encode($nonce);
$body = json_encode(array("encryptedform" => $encryptedForm, "nonce" => $nonce));
?>
现在我正在尝试对 Java 做同样的事情。不幸的是,我的实现一定有问题,因为 POST 请求返回 401(未经授权)。
public static EncryptedData encrypt(String plainText, String key) throws Exception {
// Generating IV.
byte[] iv = new byte[IV_SIZE];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
IvParameterSpec ivParameterSpec = new IvParameterSpec(random.getSeed(IV_SIZE));
// Encrypt.
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"), ivParameterSpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
// Base64 encoding.
String nonce = DatatypeConverter.printBase64Binary(ivParameterSpec.getIV());
String encryptedFrom = DatatypeConverter.printBase64Binary(encrypted);
EncryptedData data = new EncryptedData(nonce, encryptedFrom);
return data;
}
java版本出了什么问题?
【问题讨论】:
-
mcrypt 不支持 PKCS5 填充。尝试在您的 Java 代码中将其关闭。
-
它还将密钥填充到 16 个字节。
mcrypt糟透了,转换您的代码,永不回头。现在你可能最好将你的“秘密”扩展到 16 个字节。请注意,您应该尝试解密 PHP 生成的密文。使用随机 IV,您可以尝试直到宇宙结束以获得相同的密文。 -
Java 中生成的 nonce (IvParameterSpec) 是否遵循 PHP 中生成的 nonce 的相同准则?两者都可以交换吗?
-
CBC 不使用随机数,它使用 IV 位应该是攻击者无法预测的。是的,除了可能填充或裁剪 IV 值的 mcrypt 的通常 BS 之外,它的行为应该相同。再一次,mcrypt 很糟糕,并且很难做出兼容的实现。最好自己用零填充明文,例如BouncyCastle 的零填充也不兼容。
-
谢谢,终于找到了下面详述的解决方案。
标签: java authentication encryption cryptography nonce