猿问

为什么 golang 的 RSA 签名结果和 OpenSSL 命令的结果不一样?

最近在一个项目中遇到了RSA签名。希望有经验的兄弟帮帮忙。


我使用的 OpenSSL(版本 1.0.2u)命令:


echo -n -e "test\n"|openssl dgst -sha256 -sign ./apiclient_key.pem| openssl base64 -A


结果如下


pyoBMuN8UqRGLVR7YcQ11yn+dQ9rSU/fB7obQhs27eotvd51q+E8BqxB6AYQDTnlqAQnOiR1rnuxPjlGkAOaPxpCqfhS5VGblh3HuNNHiycdKKa5mM1XyaWROiL7YpyYHRUcblkICW4XEN8v5wyFHxQ+TZfBN8fdqmlLdSczZ66YnIUgaWjBkdC1UH9GqMOQkySaQbgxjh4WhWvVE4umlKz+lAj9OLBhqI/ZXcs6gPFIpyNl8hlMPi6QOxFDSPZmQZl9G7mzx4E0lBoCY5XJtm5VwG3IYTryKZvSF0/GjVyR6QA3/sY25WCPL6f/y0biovk+mJ2KvPvPX26hK4DYug==

我的签名相关的golang代码:


// get private key

bPrivateKey, err := ioutil.ReadFile("./apiclient_key.pem")

if err != nil || bPrivateKey == nil {

    log.Println(err)

    return

}

block, _ := pem.Decode(bPrivateKey)

if block == nil {

    return

}

pKeyInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes)

if err != nil {

    log.Println(err)

    return

}

pKey, ok := pKeyInterface.(*rsa.PrivateKey)

if !ok {

    return

}

// sign

strForSign = "test\n"

shaForSign := sha256.New()

shaForSign.Write([]byte(strForSign))

hashedForSign := shaForSign.Sum(nil)

rawSignature, err := rsa.SignPKCS1v15(rand.Reader, pKey, crypto.SHA256, hashedForSign)

if err != nil {

    log.Println(err)

    return

}

signature := base64.StdEncoding.EncodeToString(rawSignature)

log.Println(signature)

结果如下


NcW5pBmUfHqVNus1PTDjGOilazWkcyxquGc/Ldu5IAjg/gAIQOKBGp7rs8thec/THhWKjZOJtZ1Xvv85vc+bG5bB4IuCZp+wkUMgDC3kFuTPjtLEBBnlhshZ1nS0Haq5BuS6aWAF9sIz6Ulq9dLMjaOAACijwEltdOdkRo8Z5V01CZMOPM3FI0dVvTGOvXxsMvLjw3XPAxNpajXhxTTGZB5jElDkTb61U/cZ9tM+iVpd7Oo+vxvgCsrx2VhV4gURrxndj3V6Nc2iNV2bByrgw8XK1htzkqLqZpWo8JF8i5LdMrfaMukn6aikhWKFOo2icatjowiSQAAXrj9EnnrbQA==

慕神8447489
浏览 155回答 1
1回答

30秒到达战场

$ echo -n -e "test\n" | openssl dgst -sha256 -sign ./apiclient_key.pem | openssl base64 -ANcW5pBmUfHqVNus1PTDjGOilazWkcyxquGc/Ldu5IAjg/gAIQOKBGp7rs8thec/THhWKjZOJtZ1Xvv85vc+bG5bB4IuCZp+wkUMgDC3kFuTPjtLEBBnlhshZ1nS0Haq5BuS6aWAF9sIz6Ulq9dLMjaOAACijwEltdOdkRo8Z5V01CZMOPM3FI0dVvTGOvXxsMvLjw3XPAxNpajXhxTTGZB5jElDkTb61U/cZ9tM+iVpd7Oo+vxvgCsrx2VhV4gURrxndj3V6Nc2iNV2bByrgw8XK1htzkqLqZpWo8JF8i5LdMrfaMukn6aikhWKFOo2icatjowiSQAAXrj9EnnrbQA==%  我会仔细检查你是如何在 shell 中运行 openssl 命令的。任何到 stdout 的无关输出都会改变签名。我从 1.0.2n-fips 和 openssl-3.0.0-alpha6 以及在本地运行您的 Go 代码获得了“NcW..”签名。
随时随地看视频慕课网APP

相关分类

Go
我要回答