AES加密 - 密码,盐未解决?

时间:2009-11-19 07:22:30

标签: java encryption aes

我收到错误“密码,盐未解析”。有什么建议吗?

package org.temp2.cod1;
import java.security.*;
import java.security.spec.KeySpec;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;

public class Code2 {

public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password, salt, 1024, 256);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));


    }
}

1 个答案:

答案 0 :(得分:1)

声明并初始化saltpassword变量。

例如,如果您在启动时将密码和salt(作为16位十六进制数)作为程序的前两个参数传递,它可能如下所示:

char[] password = args[0].toCharArray();
byte[] salt = new byte[8];
for (int i = 0; i < 8; ++i) {
  salt[i] = (byte) Integer.parseInt(args[1].substring(i * 2, i * 2 + 2), 16);
}

密码学本身非常困难。试图熟悉它同时使用一种新语言只会使问题复杂化。