如何在java中生成非对称加密中的密钥对?

时间:2015-01-20 13:03:58

标签: java public-key-encryption encryption-asymmetric

我正在尝试使用Java中的非对称加密生成密钥对,但我收到invalid key exception错误,并显示No installed provider supports this key: sun.security.rsa.RSAPrivateCrtKeyImpl

private static byte[] encrypt(byte[] inpBytes, PrivateKey prvk,
      String xform) throws Exception {
    Cipher cipher = Cipher.getInstance(xform);
    cipher.init(Cipher.ENCRYPT_MODE, prvk);
    return cipher.doFinal(inpBytes);
}

@Override
public byte[] uploadFile(byte[] data, String name, String file, int size)
      throws RemoteException {
    // TODO Auto-generated method stub
    byte[] keyss=null;
    try {
        OutputStream out =
          new FileOutputStream(new File("C:\\Users\\Amaresh\\Documents\\Cloud\\"
          + name + "\\" + file));
        String xform = "DES/CTR/NoPadding";
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); // Original
        kpg.initialize(1024); // 512 is the keysize.//try 1024 biit
        KeyPair kp = kpg.genKeyPair();
        PublicKey pubk = kp.getPublic();
        PrivateKey prvk = kp.getPrivate();
        keyss = pubk.getEncoded();
        byte[] encBytes = encrypt(data, prvk, xform);
        System.out.println("Keypair generated");
        out.write(encBytes, 0, encBytes.length);
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return keyss;
}

我只想做非对称加密,我用私钥加密数据并存储公钥来解密它。我是一个初学者,我很抱歉我的错误。

2 个答案:

答案 0 :(得分:3)

您正在正确生成密钥。

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keys = kpg.generateKeyPair();

问题在于:

byte[] encBytes = encrypt(data, prvk, xform);

最有可能的原因是你传递了字符串“DES / CTR / NoPadding”。您无法使用带有RSA密钥对的DES进行加密。

答案 1 :(得分:1)

DES密码不支持RSA密钥。 DES是对称密码算法,而RSA是不对称的。对称密码需要使用相同的密钥进行加密和解密,而非对称密码则使用公钥/私钥对。

您有两种方法可以使加密工作:

  1. 您可以使用当前的对称密码并创建对称密钥(可能使用KeyGenerator

  2. 您可以将密码实例更改为像"RSA"这样的不对称实例。

    String xform = "RSA";
    
  3. 注意:
    您要做的不是加密,而是使用公钥进行加密签名 此外,您不应该通过非对称模式加密完整文件,而只应使用对称密钥来对称加密和解密数据。请参阅http://en.wikipedia.org/wiki/Public-key_cryptography#Computational_cost

相关问题