Skip to content

Golang Example Code ​

1. Core Security Component (sud/security.go) ​

go
package sud

import (
    "crypto"
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "crypto/x509"
    "encoding/base64"
    "encoding/json"
    "encoding/pem"
    "errors"
    "fmt"
    "io"
)

const (
    gcmStandardNonceSize = 12
)

// EncryptedBody corresponds to the JSON structure of the HTTP request Body
type EncryptedBody struct {
    Iv      string `json:"iv"`
    Data    string `json:"data"`
    AuthTag string `json:"authtag"`
}

// EncryptRequest performs AES-256-GCM encryption of the request data
func EncryptRequest(urlPath, appId, keySn, symKeyBase64 string, reqData map[string]any, timestamp int64) (*EncryptedBody, error) {
    // Generate an anti-replay Nonce (16-byte random number, Base64 Raw encoded without padding '=')
    nonceBytes := make([]byte, 16)
    if _, err := io.ReadFull(rand.Reader, nonceBytes); err != nil {
        return nil, fmt.Errorf("generate nonce failed: %w", err)
    }
    nonce := base64.RawStdEncoding.EncodeToString(nonceBytes)

    // Fill in the security check fields
    reqData["_n"] = nonce
    reqData["_appid"] = appId
    reqData["_timestamp"] = timestamp

    plaintext, err := json.Marshal(reqData)
    if err != nil {
        return nil, fmt.Errorf("marshal request data failed: %w", err)
    }

    // Concatenate AAD: urlpath|appid|timestamp|sn
    aadStr := fmt.Sprintf("%s|%s|%d|%s", urlPath, appId, timestamp, keySn)
    aad := []byte(aadStr)

    realKey, err := base64.StdEncoding.DecodeString(symKeyBase64)
    if err != nil {
        return nil, fmt.Errorf("decode symmetric key failed: %w", err)
    }

    realIv := make([]byte, gcmStandardNonceSize)
    if _, err := io.ReadFull(rand.Reader, realIv); err != nil {
        return nil, fmt.Errorf("generate gcm iv failed: %w", err)
    }

    block, err := aes.NewCipher(realKey)
    if err != nil {
        return nil, err
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }

    // gcm.Seal automatically appends the AuthTag to the end of the ciphertext slice
    sealedData := gcm.Seal(nil, realIv, plaintext, aad)
    
    // Separate the ciphertext and the AuthTag
    tagSize := gcm.Overhead()
    ciphertext := sealedData[:len(sealedData)-tagSize]
    authTag := sealedData[len(sealedData)-tagSize:]

    return &EncryptedBody{
        Iv:      base64.StdEncoding.EncodeToString(realIv),
        Data:    base64.StdEncoding.EncodeToString(ciphertext),
        AuthTag: base64.StdEncoding.EncodeToString(authTag),
    }, nil
}

// SignRequest generates the RSA-PSS request signature
func SignRequest(urlPath, appId string, timestamp int64, reqDataJSON string, privateKeyPem string) (string, error) {
    // Concatenate strictly in order, without adding a trailing newline
    payload := fmt.Sprintf("%s\n%s\n%d\n%s", urlPath, appId, timestamp, reqDataJSON)
    hashed := sha256.Sum256([]byte(payload))

    block, _ := pem.Decode([]byte(privateKeyPem))
    if block == nil {
        return "", errors.New("parse private key failed: invalid PEM format")
    }

    // Parse the PKCS#8 format private key
    privInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes)
    if err != nil {
        return "", fmt.Errorf("parse PKCS#8 private key failed: %w", err)
    }

    privKey, ok := privInterface.(*rsa.PrivateKey)
    if !ok {
        return "", errors.New("parsed key is not an RSA private key")
    }

    // Configure PSS parameters; the salt length aligns with SHA256 (32 bytes)
    opts := &rsa.PSSOptions{
        SaltLength: rsa.PSSSaltLengthEqualsHash,
        Hash:       crypto.SHA256,
    }

    sigBytes, err := rsa.SignPSS(rand.Reader, privKey, crypto.SHA256, hashed[:], opts)
    if err != nil {
        return "", fmt.Errorf("sign PSS failed: %w", err)
    }

    return base64.StdEncoding.EncodeToString(sigBytes), nil
}

// VerifyResponse verifies the RSA-PSS signature of the platform response
func VerifyResponse(urlPath, expectedAppId, localCertSn, platformCertPem string,
    respAppId string, respTs int64, respSn, respSig, respDeprecatedSn, respDeprecatedSig, respDataJSON string) error {

    if expectedAppId != respAppId {
        return errors.New("security check failed: appid mismatch")
    }

    // Certificate serial number matching and smooth rotation support
    var signatureBase64 string
    if localCertSn == respSn {
        signatureBase64 = respSig
    } else if respDeprecatedSn != "" && localCertSn == respDeprecatedSn {
        signatureBase64 = respSig
        if respDeprecatedSig != "" {
            signatureBase64 = respDeprecatedSig
        }
    } else {
        return fmt.Errorf("verify failed: cert sn mismatch (local: %s, remote: %s)", localCertSn, respSn)
    }

    payload := fmt.Sprintf("%s\n%s\n%d\n%s", urlPath, respAppId, respTs, respDataJSON)
    hashed := sha256.Sum256([]byte(payload))

    block, _ := pem.Decode([]byte(platformCertPem))
    if block == nil {
        return errors.New("parse cert failed: invalid PEM format")
    }

    cert, err := x509.ParseCertificate(block.Bytes)
    if err != nil {
        return fmt.Errorf("parse x509 cert failed: %w", err)
    }

    pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
    if !ok {
        return errors.New("cert public key is not RSA")
    }

    sigBytes, err := base64.StdEncoding.DecodeString(signatureBase64)
    if err != nil {
        return fmt.Errorf("decode signature base64 failed: %w", err)
    }

    opts := &rsa.PSSOptions{
        SaltLength: rsa.PSSSaltLengthEqualsHash,
        Hash:       crypto.SHA256,
    }

    if err := rsa.VerifyPSS(pubKey, crypto.SHA256, hashed[:], sigBytes, opts); err != nil {
        return fmt.Errorf("verify PSS signature failed: %w", err)
    }

    return nil
}

// DecryptResponse performs AES-256-GCM response decryption and validates the security fields
func DecryptResponse(urlPath, appId string, respTs int64, keySn, symKeyBase64, respDataJSON string) (map[string]any, error) {
    var encBody EncryptedBody
    if err := json.Unmarshal([]byte(respDataJSON), &encBody); err != nil {
        return nil, fmt.Errorf("unmarshal encrypted body failed: %w", err)
    }

    aadStr := fmt.Sprintf("%s|%s|%d|%s", urlPath, appId, respTs, keySn)
    aad := []byte(aadStr)

    realKey, err := base64.StdEncoding.DecodeString(symKeyBase64)
    if err != nil {
        return nil, fmt.Errorf("decode symmetric key failed: %w", err)
    }

    ivBytes, _ := base64.StdEncoding.DecodeString(encBody.Iv)
    dataBytes, _ := base64.StdEncoding.DecodeString(encBody.Data)
    authTagBytes, _ := base64.StdEncoding.DecodeString(encBody.AuthTag)

    // Go convention: combine the ciphertext with the AuthTag
    combinedData := append(dataBytes, authTagBytes...)

    block, err := aes.NewCipher(realKey)
    if err != nil {
        return nil, err
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }

    // Decrypt and verify the AuthTag
    decryptedBytes, err := gcm.Open(nil, ivBytes, combinedData, aad)
    if err != nil {
        return nil, fmt.Errorf("gcm open failed (invalid authtag or tampered data): %w", err)
    }

    var realResp map[string]any
    if err := json.Unmarshal(decryptedBytes, &realResp); err != nil {
        return nil, fmt.Errorf("unmarshal decrypted plaintext failed: %w", err)
    }

    // Validate the anti-replay security fields (note: Go's loosely-typed JSON numbers are parsed as float64 by default)
    innerAppID, ok1 := realResp["_appid"].(string)
    innerTimestampFloat, ok2 := realResp["_timestamp"].(float64)

    if !ok1 || !ok2 || innerAppID != appId || int64(innerTimestampFloat) != respTs {
        return nil, errors.New("security field validation failed: internal _appid or _timestamp tampered")
    }

    return realResp, nil
}

2. Business Invocation Demo (main.go) ​

go
package main

import (
    "encoding/json"
    "fmt"
    "time"

    "your_project/sud" // Import the utility package above
)

func main() {
    // 1. Global application configuration
    const (
        appID           = "cp_10010"
        urlPath         = "https://api.sud.com/v1/game/login"
        symKeySn        = "key_v1"
        symKeyBase64    = "otUpngOjU+nVQaWJIC3D/yMLV17RKaP6t4Ot9tbnzLY="
        privateKeyPem   = "-----BEGIN PRIVATE KEY-----\nMIIEvQ... (application private key) ...W6w=\n-----END PRIVATE KEY-----"
        platformCertSn  = "sud_cert_v1"
        platformCertPem = "-----BEGIN CERTIFICATE-----\nMIID0j... (SUD platform public key certificate) ...Q==\n-----END CERTIFICATE-----"
    )

    fmt.Println("=== 1. Send request: encrypt and sign business data ===")
    
    // Construct the business request data
    reqTs := time.Now().Unix()
    bizReq := map[string]any{
        "appid":     appID,
        "sud_uid":   "user_889900",
        "scene":     0,
        "client_ip": "127.0.0.1",
    }

    // Step A: perform encryption
    encBody, err := sud.EncryptRequest(urlPath, appID, symKeySn, symKeyBase64, bizReq, reqTs)
    if err != nil {
        panic(fmt.Sprintf("Encryption failed: %v", err))
    }
    
    reqBodyJSON, _ := json.Marshal(encBody)
    reqBodyStr := string(reqBodyJSON)

    // Step B: generate the signature
    reqSig, err := sud.SignRequest(urlPath, appID, reqTs, reqBodyStr, privateKeyPem)
    if err != nil {
        panic(fmt.Sprintf("Signing failed: %v", err))
    }

    fmt.Printf("HTTP Header X-Sud-Timestamp: %d\n", reqTs)
    fmt.Printf("HTTP Header X-Sud-Signature: %s\n", reqSig)
    fmt.Printf("HTTP Body: %s\n", reqBodyStr)


    fmt.Println("\n=== 2. Receive response: verify signature and decrypt ciphertext ===")

    // Simulate the data obtained from the HTTP response interceptor
    respTs := reqTs
    respHeaderAppId := appID
    respHeaderSn := platformCertSn
    respHeaderSig := reqSig // Used only for demonstration here; in practice this should be the received signature
    respBodyStr := `{"iv":"r2WDQt56rEAmMuoR","data":"HExs66...","authtag":"z2BF..."}`

    // Step C: verify the signature
    err = sud.VerifyResponse(urlPath, appID, platformCertSn, platformCertPem, 
        respHeaderAppId, respTs, respHeaderSn, respHeaderSig, "", "", respBodyStr)
    
    if err != nil {
        fmt.Printf("Response signature verification failed, discarding the message: %v\n", err)
    } else {
        fmt.Println("Response signature verification succeeded!")
        
        // Step D: perform decryption
        realResp, err := sud.DecryptResponse(urlPath, appID, respTs, symKeySn, symKeyBase64, respBodyStr)
        if err != nil {
            fmt.Printf("Response decryption failed: %v\n", err)
        } else {
            respJSON, _ := json.MarshalIndent(realResp, "", "  ")
            fmt.Printf("Response decryption succeeded, business plaintext data:\n%s\n", string(respJSON))
        }
    }
}