如何使c openssl生成与JAVA SHA256withRSA / PSS签名相同的签名文本?

时间:2018-02-15 01:42:36

标签: java c openssl rsa signing

我正在进行rpc呼叫签名,为了使服务器接受我们的API调用,我们需要使用RSAPrivateKey来签署http mime头。服务器端代码用JAVA编写,使用“SHA256withRSA / PSS”验证签名。

我的问题是我从JAVA和c openssl代码获得了不同的签名哈希值。所以问题是,openssl是否可以生成与JAVA相同的签名哈希?

JAVA代码:

public static String getSignedString(PrivateKey privateKey, String text) throws Exception {
    Signature sig = Signature.getInstance("SHA256withRSA/PSS", "BC");
    sig.initSign(privateK);
    sig.update(text.getBytes(StandardCharsets.UTF_8));

    byte[] signed = sig.sign();

    String result = Base64.getEncoder().encodeToString(signed);
    System.out.println("signed : " + result);
    /// signed result works perfect.
}

c code:

bool RSASign(RSA* rsa, const unsigned char* Msg, size_t MsgLen,unsigned char** EncMsg,size_t* MsgLenEnc) {
EVP_MD_CTX* m_RSASignCtx = EVP_MD_CTX_create();
EVP_PKEY* priKey  = EVP_PKEY_new();
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(priKey, NULL);

EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING);  
// tried RSA_PKCS1_PADDING w/o success.
EVP_PKEY_assign_RSA(priKey, rsa);
if (EVP_DigestSignInit(m_RSASignCtx,&pctx, EVP_sha256(), NULL,priKey)<=0) {
    return false;
}
if (EVP_DigestSignUpdate(m_RSASignCtx, Msg, MsgLen) <= 0) {
    return false;
}
if (EVP_DigestSignFinal(m_RSASignCtx, NULL, MsgLenEnc) <=0) {
    return false;
}
*EncMsg = (unsigned char*)malloc(*MsgLenEnc);
if (EVP_DigestSignFinal(m_RSASignCtx, *EncMsg, MsgLenEnc) <= 0) {
    return false;
}
// here EncMsg is different from JAVA output, server validation failed. need to make it the same as JAVA output.
}

1 个答案:

答案 0 :(得分:0)

&#34; PSS&#34;在&#34; RSA-PSS&#34;代表 概率签名方案 - 它是一种随机算法。你不应该每次都得到相同的签名。