java - 如何在java中使用RSA key 加密解密

标签 java openssl rsa

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

我生成 key

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

我在 unix 中使用 key (我需要在 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 不正确...但我不知道该放什么

最佳答案

解决方法:

感谢@Sanjeev,使用 bouncy caSTLe API,我能够使用 openssl 生成的 key 进行加密/解密

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();
    }
}

关于java - 如何在java中使用RSA key 加密解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10517930/

相关文章:

java - Java中如何读取多种语言的文件?

ios - 使用Objective C在iOS中使用公钥加密或签名字符串

windows - 如何导出从 CNG API 生成的 RSA key ?

algorithm - RSA 密码系统 - 检索 m

java - RSA 加密 : Difference between Java and Android

Java算法查询

java - 可变对象的安全发布

java - `ByteBuffer.allocateDirect` 和 Xmx

CentOS Openssl 安装失败

windows - 是否有适用于 Windows 的 OpenSSL?