猿问

如何使用 IAIK JCE 在 Java 中使用 PKCS#5 格式的 PBE 加密 RSA 私钥?

我创建了一个 RSA 密钥对。现在,我正在尝试使用 DES 算法加密私钥,将其格式化为 PKCS#5 并将其打印在控制台上。不幸的是,生成的私钥不起作用。当我尝试使用它时,输入正确的密码后,ssh 客户端返回密码无效:


加载密钥“test.key”:用于解密私钥的密码不正确


可以请有人告诉我我错在哪里吗?


这是代码:


private byte[] iv;


public void generate() throws Exception {

    RSAKeyPairGenerator generator = new RSAKeyPairGenerator();

    generator.initialize(2048);

    KeyPair keyPair = generator.generateKeyPair();


    String passphrase = "passphrase";

    byte[] encryptedData = encrypt(keyPair.getPrivate().getEncoded(), passphrase);

    System.out.println(getPrivateKeyPem(Base64.encodeBase64String(encryptedData)));

}


private byte[] encrypt(byte[] data, String passphrase) throws Exception {

    String algorithm = "PBEWithMD5AndDES";

    salt = new byte[8];

    int iterations = 1024;


    // Create a key from the supplied passphrase.

    KeySpec ks = new PBEKeySpec(passphrase.toCharArray());

    SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);

    SecretKey key = skf.generateSecret(ks);


    // Create the salt from eight bytes of the digest of P || M.

    MessageDigest md = MessageDigest.getInstance("MD5");

    md.update(passphrase.getBytes());

    md.update(data);

    byte[] digest = md.digest();

    System.arraycopy(digest, 0, salt, 0, 8);

    AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iterations);


    Cipher cipher = Cipher.getInstance(AlgorithmID.pbeWithSHAAnd3_KeyTripleDES_CBC.getJcaStandardName());

    cipher.init(Cipher.ENCRYPT_MODE, key, aps);

    iv = cipher.getIV();

    byte[] output = cipher.doFinal(data);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    out.write(salt);

    out.write(output);

    out.close();

    return out.toByteArray();

}


阿晨1998
浏览 159回答 2
2回答

森栏

先生我认为在调用 encrypt 之前,出于安全原因,您需要再解密两次。也可以用胡椒盐和胡椒代替盐。不要将算法与 aes256 混合。
随时随地看视频慕课网APP

相关分类

Java
我要回答