【问题标题】:How to encrypt decrypt with RSA keys in java如何在java中使用RSA密钥加密解密
【发布时间】:2012-05-09 14:14:53
【问题描述】:

我需要用 openssl 生成的 rsaprivatekey.pem 和 rsapublickey.pem 密钥替换从 Unix 到 java 代码的加密和解密步骤

我生成密钥

openssl  genrsa  -out /tmp/rsaprivatekey.pem  -des3 1024
openssl rsa -in /tmp/rsaprivatekey.pem -pubout -out /tmp/rsapublickey.pem

我在 unix 中使用键(我需要在 java 中使用)

echo "Text to encript"| openssl rsautl -encrypt -inkey /tmp/rsapublickey.pem -pubin -out out.enc
openssl rsautl -decrypt -inkey /tmp/rsaprivatekey.pem -in out.enc

这是我的尝试

public static void main(String[] args) {


    Base64 base64 = new Base64();

    String TextStream = "this is the input text";
    byte[] Cipher;
    System.out.println("input:\n" + TextStream);
    Cipher = encrypt(TextStream);
    System.out.println("cipher:\n" + base64.encodeAsString(Cipher));
    System.out.println("decrypt:\n" + decrypt(Cipher));
}

private static byte[] encrypt(String Buffer) {
    try {

        Cipher rsa;
        rsa = Cipher.getInstance("RSA");
        rsa.init(Cipher.ENCRYPT_MODE, getPrivateKey(PRIVATE_PATH));
        return rsa.doFinal(Buffer.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}


private static String decrypt(byte[] buffer) {
    try {
        Cipher rsa;
        rsa = Cipher.getInstance("RSA");
        rsa.init(Cipher.DECRYPT_MODE, getPrivateKey(PUBLIC_PATH));
        byte[] utf8 = rsa.doFinal(buffer);
        return new String(utf8, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public static PrivateKey getPrivateKey(String filename) throws Exception {
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) f.length()];
    dis.readFully(keyBytes);
    dis.close();

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
}

public static PublicKey getPublicKey(String filename) throws Exception {
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) f.length()];
    dis.readFully(keyBytes);
    dis.close();

    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
}

但它不起作用,PKCS8EncodedKeySpec/X509EncodedKeySpec 不正确...但我不知道该放什么

【问题讨论】:

标签: java openssl rsa


【解决方案1】:

解决方案:

感谢@Sanjeev,使用充气城堡 API,我能够使用 openssl 生成的密钥进行加密/解密

public static void main(String[] args) throws IOException {

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = readKeyPair(new File(PRIVATE_PATH), "pass"); 
    // if the private key is not encripted, pass can be anything.
    Key publickey = readPublicKey(new File(PUBLIC_PATH), "pass"); 
    Base64 base64 = new Base64();
    String text = "this is the input text";
    byte[] encripted;
    System.out.println("input:\n" + text);
    encripted = encrypt(keyPair.getPublic(), text);
    System.out.println("cipher:\n" + base64.encodeAsString(encripted));
    System.out.println("decrypt:\n" + decrypt(keyPair.getPrivate(), encripted));        
}

private static byte[] encrypt(Key pubkey, String text) {
    try {
        Cipher rsa;
        rsa = Cipher.getInstance("RSA");
        rsa.init(Cipher.ENCRYPT_MODE, pubkey);
        return rsa.doFinal(text.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}


private static String decrypt(Key decryptionKey, byte[] buffer) {
    try {
        Cipher rsa;
        rsa = Cipher.getInstance("RSA");
        rsa.init(Cipher.DECRYPT_MODE, decryptionKey);
        byte[] utf8 = rsa.doFinal(buffer);
        return new String(utf8, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

private static KeyPair readKeyPair(File privateKey, String keyPassword) throws IOException {
    FileReader fileReader = new FileReader(privateKey);
    PEMReader r = new PEMReader(fileReader, new DefaultPasswordFinder(keyPassword.toCharArray()));
    try {
        return (KeyPair) r.readObject();
    } catch (IOException ex) {
        throw ex;
    } finally {
        r.close();
        fileReader.close();
    }
}

private static Key readPublicKey(File privateKey, String keyPassword) throws IOException {
    FileReader fileReader = new FileReader(privateKey);
    PEMReader r = new PEMReader(fileReader, new DefaultPasswordFinder(keyPassword.toCharArray()));
    try {
        return (RSAPublicKey) r.readObject();
    } catch (IOException ex) {
        throw ex;
    } finally {
        r.close();
        fileReader.close();
    }
}

【讨论】:

  • 不应该是“UTF-8”吗?
  • 嗨@caeycae,我正在关注你的帖子,我也遇到了麻烦。哪个 JAR/Library 包含 DefaultPasswordFinder?
  • 您是否找到了解决方案,我们必须为 DefaultPasswordFinder 包含哪个 jar 文件?
  • 私有静态类 DefaultPasswordFinder 实现 PasswordFinder { private final char[] password; DefaultPasswordFinder(char[] 密码) { this.password = 密码; } @Override public char[] getPassword() { 返回密码; } }
【解决方案2】:

我认为您在读取 ​​PEM 文件时遇到了问题。 JPA 不直接支持 PEM 格式。您有两个选择,或者将它们转换为 DER 编码文件(您可以使用 openSSL 来执行此操作),或者您可以使用 bouncy castle API 来读取(或写入)PEM 文件。您感兴趣的课程称为 PEMReader(也可能是 PEMWriter)。 Here is the Javadoc 在 bouncycastle 网站上。

【讨论】:

  • 上面的Javadoc链接坏了,当前链接是here。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
  • 2012-04-07
  • 2013-01-02
  • 1970-01-01
  • 2018-09-10
相关资源
最近更新 更多