HarmonyOS 鸿蒙Next IAP kit对返回结果验签,可以提供go版本的示例代码吗
HarmonyOS 鸿蒙Next IAP kit对返回结果验签,可以提供go版本的示例代码吗
更多关于HarmonyOS 鸿蒙Next IAP kit对返回结果验签,可以提供go版本的示例代码吗的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
IAP kit对返回结果验签,目前只有java、Python、Php三种语言的示例,暂时没有go语言的示例
下边是php7.2版本的jwt验签demo,可以参考一下,
<?php
// 三方依赖:lcobucci/jwt、phpseclib/phpseclib、ext-curl,请根据php版本选择合适的三方依赖版本
/*
- “php”: “^5.6 || ^7.0”
- “lcobucci/jwt”: “3.4.*”
- “phpseclib/phpseclib”: “3.0”
- “ext-curl”: “*”
- “ext-openssl”: “*”
- */
use Lcobucci<span class=“hljs-title”>JWT<span class=“hljs-title”>Parser;
use Lcobucci<span class=“hljs-title”>JWT<span class=“hljs-title”>Signer<span class=“hljs-title”>Ecdsa<span class=“hljs-title”>Sha256;
use Lcobucci<span class=“hljs-title”>JWT<span class=“hljs-title”>Signer<span class=“hljs-title”>Key;
use Lcobucci<span class=“hljs-title”>JWT<span class=“hljs-title”>Validation<span class=“hljs-title”>Constraint<span class=“hljs-title”>SignedWith;
use Lcobucci<span class=“hljs-title”>JWT<span class=“hljs-title”>Validation<span class=“hljs-title”>Validator;
use phpseclib3<span class=“hljs-title”>File<span class=“hljs-title”>X509;
require ‘vendor/autoload.php’;
$jws = “待验证的jws字符串”;
// 叶子证书OID
const OID = ‘1.3.6.1.4.1.2011.2.415.1.1’;
// 下载的根证书路径
const CA_CERT_FILE_PATH = ‘下载的根证书路径’;
// 1.解析JWS,获取到Header、 Payload和Signature。
$parser = new Parser();
try {
$token = $parser->parse($jws);
list($leafCertPEM, $middleCertPEM, $rootCertPEM) = array_map(‘formatPEM’, $token->headers()->get(“x5c”));
} catch (Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
// 2.按照①叶子证书、②中间证书、③根证书的顺序,进行证书链认证。
try {
verifyX509Chain($leafCertPEM, $middleCertPEM, $rootCertPEM);
} catch (Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
// 3.校验叶子证书的OID
try {
verifyOID($leafCertPEM, OID);
} catch (Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
// 4.通过Header指定的算法和PublicKey验证Payload数据是否被篡改。
try {
verifySign($token, $leafCertPEM);
} catch (Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
// 5.验证成功,获取payload
var_dump($token->claims()->all());
/**
- @throws Exception
*/
function formatPEM($der)
{
// 将base64编码的der证书转为pem格式
$pem_content = chunk_split($der, 64, “”);
return “-----BEGIN CERTIFICATE-----” . PHP_EOL . $pem_content . PHP_EOL . “-----END CERTIFICATE-----”;
}
/**
- @throws Exception
*/
function verifyX509Chain($leafCertPEM, $middleCertPEM, $rootCertPEM)
{
// 证书链校验
verifyX509ChainV1($leafCertPEM, $middleCertPEM, $rootCertPEM);
// CRL校验
$x509PEMs = array($leafCertPEM, $middleCertPEM);
verifyCRL4X509Chain($x509PEMs);
}
/**
- 结合根CA,验证x509证书链的有效性
- @throws Exception
*/
function verifyX509ChainV1($leafCertPEM, $middleCertPEM, $rootCertPEM)
{
$INTERMEDIATE_CERT_FILE_PATH = ‘中间证书文件路径’;
$ROOT_CERT_FILE_PATH = ‘根证书文件路径’;
// 转为resource
$leafCert_resource = openssl_x509_read($leafCertPEM);
$middleCert_resource = openssl_x509_read($middleCertPEM);
$rootCert_resource = openssl_x509_read($rootCertPEM);
// 写出到文件
file_put_contents($INTERMEDIATE_CERT_FILE_PATH, $middleCertPEM);
file_put_contents($ROOT_CERT_FILE_PATH, $rootCertPEM);
$purpose = X509_PURPOSE_ANY;
// 验证叶子证书
if (!openssl_x509_checkpurpose($leafCert_resource, $purpose, [$INTERMEDIATE_CERT_FILE_PATH, $ROOT_CERT_FILE_PATH, CA_CERT_FILE_PATH])) {
throw new Exception(‘leaf certificate verification failed.’);
}
// 验证中间证书
if (!openssl_x509_checkpurpose($middleCert_resource, $purpose, [$ROOT_CERT_FILE_PATH])) {
throw new Exception(‘intermediate certificate validation failed’);
}
// 验证root证书
if (!openssl_x509_checkpurpose($rootCert_resource, $purpose, [CA_CERT_FILE_PATH])) {
throw new Exception(‘root certificate verification failed’);
}
}
/**
- @throws Exception
*/
function verifyCRL4X509Chain($x509PEMs)
{
foreach ($x509PEMs as $x509PEM) {
try {
// 转为x509对象
$cert = new X509();
$cert->loadX509($x509PEM);
// 获取扩展中的crl的url
$crlExt = $cert->getExtension(“id-ce-cRLDistributionPoints”);
$crl_url = $crlExt[0][“distributionPoint”][“fullName”][0][“uniformResourceIdentifier”];
// 使用curl请求吊销列表
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_TIMEOUT => 3,
CURLOPT_URL => $crl_url,
CURLOPT_HTTPGET => true,
CURLOPT_RETURNTRANSFER => true,
));
$resp = curl_exec($curl);
curl_close($curl);
// 需根据实际情况处理false分支
if (!$resp) continue;
// 获取吊销证书列表
$crl = new X509();
$crl_certs = $crl->loadCRL($resp);
// 需根据实际情况处理false分支
if (!$crl_certs) continue;
$crl_certs = $crl_certs[“tbsCertList”][“revokedCertificates”];
// 查找吊销列表中是否包含当前证书
$closure = function () {
return $this->currentCert;
};
$current_cert = $closure->call($cert);
foreach ($crl_certs as $crl_cert) {
$crl_sn = $crl_cert[‘userCertificate’]->toString();
$current_sn = $current_cert[“tbsCertificate”][“serialNumber”]->toString();
if ($crl_sn === $current_sn) {
throw new Exception(‘the certificate has been revoked’);
}
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
}
/**
- @throws Exception
*/
function verifyOID($cer, $OID)
{
$extensions = openssl_x509_parse($cer, false)[‘extensions’];
if (!array_key_exists($OID, $extensions)) {
throw new Exception(‘failed to verify the certificate OID.’);
}
}
/**
- @throws Exception
*/
function verifySign($token, $leafCertPEM)
{
// 初始化一个验证器
$validator = new Validator();
$signer = new Sha256();
$key = new Key($leafCertPEM);
if (!$validator->validate($token, new SignedWith($signer, $key))) {
throw new Exception(‘failed to verify the signature.’);
}
}
更多关于HarmonyOS 鸿蒙Next IAP kit对返回结果验签,可以提供go版本的示例代码吗的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
当然,以下是一个HarmonyOS鸿蒙Next IAP kit对返回结果验签的Go版本示例代码:
package main
import (
"crypto/sha256"
"crypto/rsa"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"encoding/base64"
"fmt"
"strings"
)
func verifySignature(data, signature, publicKeyPEM string) (bool, error) {
block, _ := pem.Decode([]byte(publicKeyPEM))
if block == nil || block.Type != "RSA PUBLIC KEY" {
return false, fmt.Errorf("failed to decode PEM block containing public key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return false, err
}
rsaPub, ok := pub.(*rsa.PublicKey)
if !ok {
return false, fmt.Errorf("not a valid RSA public key")
}
decodedSig, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return false, err
}
hash := sha256.Sum256([]byte(data))
return rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, hash[:], decodedSig) == nil, nil
}
func main() {
data := "your_data"
signature := "your_signature"
publicKeyPEM := "your_public_key_pem"
valid, err := verifySignature(data, signature, publicKeyPEM)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Signature valid:", valid)
}
}
请注意,以上代码假设你已经有了data(数据)、signature(签名)和publicKeyPEM(公钥PEM格式字符串)。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html