今天在做微信支付商戶平臺的提交申請單API時,發(fā)現(xiàn)這個接口的contact_info參數(shù)數(shù)據(jù)需要加密,按照平臺的接口文檔完善了EncryptOAEP和DecryptOAEP這個兩個函數(shù)的程序代碼。
一共有四個函數(shù)分別是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
}