Gin + GORM + pure-Go SQLite. Users/auth (JWT), API key management with quotas, proxy gateway with weighted channel failover and health checks, usage/billing ledger, cross-protocol conversion (Anthropic Messages / OpenAI Chat Completions / OpenAI Responses), and channel/model admin API. Channels declare native API formats and auto-convert the rest. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
65 lines
1.6 KiB
Go
65 lines
1.6 KiB
Go
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
// Encrypt seals a secret with AES-GCM. The master key can be any string;
|
|
// it is hashed to a fixed-size AES key.
|
|
func Encrypt(plaintext, masterKey string) (string, error) {
|
|
key := sha256.Sum256([]byte(masterKey))
|
|
block, err := aes.NewCipher(key[:])
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return "", err
|
|
}
|
|
sealed := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
|
return base64.StdEncoding.EncodeToString(sealed), nil
|
|
}
|
|
|
|
// Decrypt opens a ciphertext produced by Encrypt.
|
|
func Decrypt(ciphertext, masterKey string) (string, error) {
|
|
key := sha256.Sum256([]byte(masterKey))
|
|
data, err := base64.StdEncoding.DecodeString(ciphertext)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
block, err := aes.NewCipher(key[:])
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(data) < gcm.NonceSize() {
|
|
return "", errors.New("ciphertext too short")
|
|
}
|
|
nonce, sealed := data[:gcm.NonceSize()], data[gcm.NonceSize():]
|
|
plain, err := gcm.Open(nil, nonce, sealed, nil)
|
|
if err != nil {
|
|
return "", fmt.Errorf("decrypt failed (bad master key?): %w", err)
|
|
}
|
|
return string(plain), nil
|
|
}
|
|
|
|
// HashSHA256 returns the hex SHA-256 of a string (used for API key lookup).
|
|
func HashSHA256(s string) string {
|
|
sum := sha256.Sum256([]byte(s))
|
|
return fmt.Sprintf("%x", sum)
|
|
}
|