Skip to content

Golang Example Code ​

Covers the core scenarios of the two types of "data security" keys:

  • Data symmetric encryption key (AES-256-GCM): userSignature generation, sessionKey decryption
  • Data signature public/private key (RSASSA-PSS): business data signature verification (e.g., gameSignature)

General Notes ​

  • The AES part of the example is split into two layers:
    • AES-256-GCM utility package (aesutil): a general-purpose symmetric encryption/decryption implementation, consistent with the internal encryption/decryption mechanism of the SUD SDK, and directly reusable in any AES-256-GCM scenario;
    • Business wrapper: builds on the utility package to perform Payload construction and field validation, covering userSignature generation and sessionKey decryption respectively.
  • The AES byte layout is uniformly: iv(12) || ciphertext+tag, then Base64-encoded as a whole (where tag is automatically appended to the end of the ciphertext by gcm.Seal, with a length of 16 bytes).
  • The RSA part (§3 Business data signature verification) provides an independent rsautil utility package, whose PSS parameters are fully consistent with the SUD OpenPaaS server-side signing mechanism.
  • The example contains only the core logic; production environments need to add logging, exception fallbacks, monitoring alerts, and other engineering measures.
  • In the business examples, replace the import paths your-module/aesutil and your-module/rsautil with your actual Go module name.

Environment Dependencies ​

  • Go 1.15+ (no additional dependencies required; based on the standard library crypto/aes, crypto/rsa, crypto/x509, encoding/pem).

General AES-256-GCM Utility ​

go
// file: aesutil/aesutil.go
package aesutil

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "fmt"
    "io"
)

const (
    IVLength  = 12
    TagLength = 16
)

func Encrypt(plaintext, keyBase64 string) (string, error) {
    key, err := base64.StdEncoding.DecodeString(keyBase64)
    if err != nil {
        return "", fmt.Errorf("key decoding failed: %w", err)
    }
    iv, err := generateIV()
    if err != nil {
        return "", err
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        return "", fmt.Errorf("failed to create AES cipher block: %w", err)
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return "", fmt.Errorf("failed to create GCM: %w", err)
    }

    cipherBytes := gcm.Seal(nil, iv, []byte(plaintext), nil)
    // Consistent with Java/JCE: iv || ciphertext+tag
    return base64.StdEncoding.EncodeToString(append(iv, cipherBytes...)), nil
}

func Decrypt(encryptedBase64, keyBase64 string) ([]byte, error) {
    key, err := base64.StdEncoding.DecodeString(keyBase64)
    if err != nil {
        return nil, fmt.Errorf("key decoding failed: %w", err)
    }
    data, err := base64.StdEncoding.DecodeString(encryptedBase64)
    if err != nil {
        return nil, fmt.Errorf("ciphertext decoding failed: %w", err)
    }
    iv := data[:IVLength]
    cipherBytes := data[IVLength:]

    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, fmt.Errorf("failed to create AES cipher block: %w", err)
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, fmt.Errorf("failed to create GCM: %w", err)
    }

    return gcm.Open(nil, iv, cipherBytes, nil)
}

func generateIV() ([]byte, error) {
    iv := make([]byte, IVLength)
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        return nil, fmt.Errorf("failed to generate IV: %w", err)
    }
    return iv, nil
}

1. userSignature Generation ​

Build the authentication Payload based on aesutil and encrypt it:

go
// file: usersignature/usersignature.go
package main

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

    "your-module/aesutil"
)

const signatureVersion = "1"

type signaturePayload struct {
    Version   string `json:"version"`
    UserID    string `json:"user_id"`
    ExpiresAt int64  `json:"expires_at"`
}

func GenerateUserSignature(userID string, expiresAt int64, base64Key string) (string, error) {
    if userID == "" {
        return "", fmt.Errorf("user_id must not be empty")
    }
    if expiresAt <= time.Now().Unix() {
        return "", fmt.Errorf("expires_at must be a Unix timestamp (seconds) greater than the current time")
    }

    payload, err := json.Marshal(signaturePayload{
        Version:   signatureVersion,
        UserID:    userID,
        ExpiresAt: expiresAt,
    })
    if err != nil {
        return "", fmt.Errorf("payload serialization failed: %w", err)
    }

    return aesutil.Encrypt(string(payload), base64Key)
}

func main() {
    base64Key := "Your Base64-encoded 32-byte AES key"
    userID := "user_123456"
    expiresAt := time.Now().Unix() + 24*3600
    sig, err := GenerateUserSignature(userID, expiresAt, base64Key)
    if err != nil {
        fmt.Printf("Generation failed: %v\n", err)
        return
    }
    fmt.Println("userSignature:", sig)
}

2. sessionKey Decryption ​

Decrypt based on aesutil and validate the payload fields:

go
// file: sessionkey/sessionkey.go
package main

import (
    "encoding/json"
    "fmt"

    "your-module/aesutil"
)

type SessionPayload struct {
    UserID     string `json:"user_id"`
    SessionKey string `json:"session_key"`
}

func DecryptSessionKey(encryptedSessionKey, base64Key, expectedUserID string) (*SessionPayload, error) {
    plaintextBytes, err := aesutil.Decrypt(encryptedSessionKey, base64Key)
    if err != nil {
        return nil, err
    }

    var payload SessionPayload
    if err := json.Unmarshal(plaintextBytes, &payload); err != nil {
        return nil, fmt.Errorf("payload parsing failed: %w", err)
    }
    if payload.UserID == "" || payload.SessionKey == "" {
        return nil, fmt.Errorf("payload missing required fields user_id / session_key")
    }
    if expectedUserID != "" && payload.UserID != expectedUserID {
        return nil, fmt.Errorf("user_id mismatch: expected %s, actual %s", expectedUserID, payload.UserID)
    }
    return &payload, nil
}

func main() {
    encryptedSessionKey := "Base64-encoded encrypted_session_key"
    base64Key := "Your Base64-encoded 32-byte AES key"
    expectedUserID := "user_123456"
    payload, err := DecryptSessionKey(encryptedSessionKey, base64Key, expectedUserID)
    if err != nil {
        fmt.Printf("Decryption failed: %v\n", err)
        return
    }
    fmt.Printf("user_id: %s, session_key: %s\n", payload.UserID, payload.SessionKey)
}

3. Business Data Signature Verification ​

Based on the "data signature public/private key", perform RSASSA-PSS signature verification on the business data payload delivered by SUD OpenPaaS (such as gameSignature). The PSS parameters are SHA-256 / MGF1-SHA-256 / salt=32 / trailer=1 (the Go standard library defaults to trailer=1), and the signature value is Base64-encoded.

3.1 General RSA Signing/Verification Utility ​

go
// file: rsautil/rsautil.go
package rsautil

import (
    "crypto"
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "crypto/x509"
    "encoding/base64"
    "encoding/pem"
    "fmt"
)

var pssOpts = &rsa.PSSOptions{
    SaltLength: 32,
    Hash:       crypto.SHA256,
}

// Sign uses the application private key to sign the content and returns a Base64 string.
func Sign(content, privateKeyPEM string) (string, error) {
    privateKey, err := parsePrivateKey(privateKeyPEM)
    if err != nil {
        return "", err
    }
    digest := sha256.Sum256([]byte(content))
    sig, err := rsa.SignPSS(rand.Reader, privateKey, crypto.SHA256, digest[:], pssOpts)
    if err != nil {
        return "", fmt.Errorf("RSASSA-PSS signing failed: %w", err)
    }
    return base64.StdEncoding.EncodeToString(sig), nil
}

// Verify uses the public key delivered by SUD OpenPaaS to verify the signature.
func Verify(content, signValueBase64, publicKeyPEM string) (bool, error) {
    publicKey, err := parsePublicKey(publicKeyPEM)
    if err != nil {
        return false, err
    }
    sig, err := base64.StdEncoding.DecodeString(signValueBase64)
    if err != nil {
        return false, fmt.Errorf("signature Base64 decoding failed: %w", err)
    }
    digest := sha256.Sum256([]byte(content))
    if err := rsa.VerifyPSS(publicKey, crypto.SHA256, digest[:], sig, pssOpts); err != nil {
        return false, nil
    }
    return true, nil
}

func parsePrivateKey(pemStr string) (*rsa.PrivateKey, error) {
    block, _ := pem.Decode([]byte(pemStr))
    if block == nil {
        return nil, fmt.Errorf("private key PEM decoding failed")
    }
    if key, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
        rsaKey, ok := key.(*rsa.PrivateKey)
        if !ok {
            return nil, fmt.Errorf("PKCS#8 private key is not of RSA type")
        }
        return rsaKey, nil
    }
    return x509.ParsePKCS1PrivateKey(block.Bytes)
}

func parsePublicKey(pemStr string) (*rsa.PublicKey, error) {
    block, _ := pem.Decode([]byte(pemStr))
    if block == nil {
        return nil, fmt.Errorf("public key PEM decoding failed")
    }
    key, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    rsaKey, ok := key.(*rsa.PublicKey)
    if !ok {
        return nil, fmt.Errorf("public key is not of RSA type")
    }
    return rsaKey, nil
}

3.2 Invocation Example ​

go
// file: verifydata/main.go
package main

import (
    "fmt"

    "your-module/rsautil"
)

func main() {
    // publicKeyPEM: the application public key obtained from the SUD OpenPaaS admin console (PEM string)
    // content:      the "content to be verified" concatenated per the corresponding business documentation (e.g., gameSignature)
    // signature:    the signature value carried in the business data payload (Base64)
    publicKeyPEM := "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
    content := "content to be verified"
    signature := "the Base64 signature value carried in the business data"

    ok, err := rsautil.Verify(content, signature, publicKeyPEM)
    if err != nil {
        fmt.Printf("Signature verification error: %v\n", err)
        return
    }
    if !ok {
        fmt.Println("Data signature verification failed; do not trust this business data content")
        return
    }
    fmt.Println("Data signature verification passed")
}