今天在做微信支付商户平台的提交申请单API时,发现这个接口的contact_info参数数据需要加密,按照平台的接口文档完善了EncryptOAEP和DecryptOAEP这个两个函数的程序代码。
一共有四个函数分别是EncryptOAEP、DecryptOAEP、ParsePKIXPublicKey、ParsePKCS1PrivateKey。
EncryptOAEP
// 加密
func EncryptOAEP(text string)string {
rsaPublicKey := ParsePKIXPublicKey()
secretMessage := []byte(text)
rng := rand.Reader
cipherdata, err := rsa.EncryptOAEP(sha1.New(), rng, rsaPublicKey, secretMessage, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)
return ""
}
ciphertext := base64.StdEncoding.EncodeToString(cipherdata)
fmt.Printf("Ciphertext: %x\n", ciphertext)
return ciphertext
}
DecryptOAEP
// 解密
func DecryptOAEP(ciphertext string) string {
rsaPrivateKey := ParsePKCS1PrivateKey()
cipherdata, _ := base64.StdEncoding.DecodeString(ciphertext)
rng := rand.Reader
plaintext, err := rsa.DecryptOAEP(sha1.New(), rng, rsaPrivateKey, cipherdata, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Error from decryption: %s\n", err)
return ""
}
fmt.Printf("Plaintext: %s\n", string(plaintext))
return string(plaintext)
}
ParsePKIXPublicKey
func ParsePKIXPublicKey() rsa.PublicKey {
publicKey, err := ioutil.ReadFile("static/cert/apiclient_cert.pem")
if err != nil {
fmt.Println(err)
return nil
}
block, _ := pem.Decode(publicKey)
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
fmt.Println(err)
return nil
}return pubInterface.(rsa.PublicKey)
}
ParsePKCS1PrivateKey
// 解析私钥
func ParsePKCS1PrivateKey() *rsa.PrivateKey {
privateKey, err := ioutil.ReadFile("static/cert/apiclient_key.pem")
if err != nil {
fmt.Println(err)
return nil
}
block, _ := pem.Decode(privateKey)
privateInterface, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
fmt.Println(err)
return nil
}
return privateInterface
}
有疑问加站长微信联系(非本文作者)