60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package contact
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"io"
|
|
"strings"
|
|
)
|
|
|
|
var ErrChannelKeyUnavailable = errors.New("联系人通道加密密钥未配置或格式错误")
|
|
|
|
func ParseChannelKey(value string) ([]byte, error) {
|
|
key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
|
|
if err != nil || len(key) != 32 {
|
|
return nil, ErrChannelKeyUnavailable
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
func encryptAddress(key []byte, value string) ([]byte, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, ErrChannelKeyUnavailable
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
return gcm.Seal(nonce, nonce, []byte(value), nil), nil
|
|
}
|
|
|
|
func decryptAddress(key, encoded []byte) (string, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", ErrChannelKeyUnavailable
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(encoded) < gcm.NonceSize() {
|
|
return "", errors.New("通道密文已损坏")
|
|
}
|
|
plain, err := gcm.Open(nil, encoded[:gcm.NonceSize()], encoded[gcm.NonceSize():], nil)
|
|
return string(plain), err
|
|
}
|
|
|
|
func fingerprint(value string) string {
|
|
sum := sha256.Sum256([]byte(value))
|
|
return base64.RawURLEncoding.EncodeToString(sum[:])
|
|
}
|