Java密码设置特定的随机数不起作用

时间:2018-11-12 19:56:55

标签: java authentication encryption cryptography nonce

我需要加密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版本怎么了?

1 个答案:

答案 0 :(得分:0)

我找到了解决这个难题的方法,幸运的是,我可以将php代码转换为Java等效语言:

public static ar.edu.ues21.menu.util.EncryptedData encrypt2(String key, String data) throws Exception {
    ar.edu.ues21.menu.util.EncryptedData result =  null;
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RijndaelEngine(128)), new ZeroBytePadding());

    byte[] iv = new byte[16];        
    SecureRandom.getInstance("SHA1PRNG").nextBytes(iv);

    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key.getBytes("UTF-8")), iv);        
    cipher.init(true, ivAndKey);

    byte[] input = data.getBytes("UTF-8");
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];

    int cipherLength = cipher.processBytes(input, 0, input.length, cipherText, 0);
    cipher.doFinal(cipherText, cipherLength);

    result = new ar.edu.ues21.menu.util.EncryptedData(Base64.encodeBase64String(iv), Base64.encodeBase64String(cipherText));
    return result;
}

但是我很幸运,真正的问题是目标API没有有关令牌生成所需加密类型的任何文档。