0%

Go_后端、前端加密套装

Go_后端、前端加密套装

Go 后端加密增强:


func marshalResponse(response JsonResponse) []byte {
jsonData, _ := json.Marshal(response)

// 使用AES加密 (需安装 crypto/aes, crypto/cipher)
encrypted := encryptAES(jsonData, "your-32-byte-secret-key-1234567890abc")
return []byte(base64.StdEncoding.EncodeToString(encrypted))
}

func encryptAES(data []byte, key string) []byte {
block, _ := aes.NewCipher([]byte(key))
gcm, _ := cipher.NewGCM(block)
nonce := make([]byte, gcm.NonceSize())
rand.Read(nonce)
return gcm.Seal(nonce, nonce, data, nil)
}

Python 解密增强:

from Cryptodome.Cipher import AES
import base64

def decode_encrypted(encrypted_str, key):
encrypted_data = base64.b64decode(encrypted_str)
nonce = encrypted_data[:12]
ciphertext = encrypted_data[12:]
cipher = AES.new(key.encode(), AES.MODE_GCM, nonce=nonce)
return json.loads(cipher.decrypt(ciphertext).decode('utf-8'))

JavaScript 解密增强:

async function decryptResponse(encryptedStr, key) {
const encryptedData = Uint8Array.from(atob(encryptedStr), c => c.charCodeAt(0));
const iv = encryptedData.slice(0, 12);
const ciphertext = encryptedData.slice(12);

const cryptoKey = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(key),
{ name: "AES-GCM" },
false,
["decrypt"]
);

const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv },
cryptoKey,
ciphertext
);

return JSON.parse(new TextDecoder().decode(decrypted));
}
  1. 增强方案
    • 添加 AES-GCM 加密
    • 需要前后端共享密钥
    • 适用于需要真正加密保护的场景