+-
java – 会话密钥的OpenSSL加密
我正在编写一种加密会话密钥的方法.它需要这样做,以便密钥可以由已成功测试的不同程序解密.解密程序不能改变.我遇到的问题是让我的加密工作方式与解密例程保持一致.

让我先给出解密程序.请记住,这不能改变:

public Boolean decryptSessionKey() {

    // first, base64 decode the session key
    String sslString = "openssl base64 -d -in enc_sesskey -out temp";

    try {
        Process p = Runtime.getRuntime().exec(sslString);
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    // now we can decrypt it
    try {
        sslString = "openssl rsautl -in temp -inkey privkey.pem -decrypt";
        Process p = Runtime.getRuntime().exec(sslString);   
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        try {
            String s;
            while ((s = stdInput.readLine()) != null) {           
                decrypted_session_password = s;
                writeToFile(decrypted_sesskey, s);
            }
            return true;

        } catch (Exception e) {
            return false;
        }
    } catch (IOException e1) {
        return false;
    } catch (Exception e) {
        return false;
    }
}

这是我正在编写的加密例程.我产生base64编码的文本,但它最终不能解密.值得注意的是,我已经验证了解密例程正确地获取了加密例程的结果(两者之间没有握手问题).

public Boolean encryptSessionKey(Cert receiver_cert) {

    String sslString = 
        "openssl rsautl base64 -in sesskey -out temp -inkey cert.pem -encrypt -certin";

    // run this openssl encryption. Note that it will not yet be base64 encoded
    try {
        Process p = Runtime.getRuntime().exec(sslString);
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    // now we base64-encode the encrypted file
    sslString = "openssl base64 -in temp -out enc_sesskey"; 

    try {
        Process p = Runtime.getRuntime().exec(sslString);   
    } catch (IOException e1) {return false;
    } catch (Exception e) {return false;
    }

    return true;
}

我真的被卡住了.任何帮助表示赞赏.谢谢.

最佳答案
使用PKCS填充和从证书获取的公钥进行RSA加密:

openssl rsautl -encrypt -in sesskey -inkey cert.pem -certin -out temp
openssl base64 -e -in temp -out enc_sesskey

使用PKCS填充和私钥进行RSA解密:

openssl base64 -d -in enc_sesskey -out temp
openssl rsautl -decrypt -in temp -inkey privkey.pem -out sesskey2

测试并确认为OK,因为“sesskey”文件的内容与“sesskey2”文件的内容相同.

点击查看更多相关文章

转载注明原文:java – 会话密钥的OpenSSL加密 - 乐贴网