gmessages/libgm/crypto/cryptor.go

102 lines
2.2 KiB
Go
Raw Normal View History

2023-06-30 09:54:08 +00:00
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"errors"
"io"
"google.golang.org/protobuf/reflect/protoreflect"
"go.mau.fi/mautrix-gmessages/libgm/binary"
)
type Cryptor struct {
2023-06-30 13:26:46 +00:00
AESCTR256Key []byte
SHA256Key []byte
2023-06-30 09:54:08 +00:00
}
2023-06-30 13:26:46 +00:00
func NewCryptor(aesKey []byte, shaKey []byte) *Cryptor {
if aesKey != nil && shaKey != nil {
2023-06-30 09:54:08 +00:00
return &Cryptor{
2023-06-30 13:26:46 +00:00
AESCTR256Key: aesKey,
SHA256Key: shaKey,
2023-06-30 09:54:08 +00:00
}
}
2023-06-30 13:26:46 +00:00
aesKey, shaKey = GenerateKeys()
2023-06-30 09:54:08 +00:00
return &Cryptor{
2023-06-30 13:26:46 +00:00
AESCTR256Key: aesKey,
SHA256Key: shaKey,
2023-06-30 09:54:08 +00:00
}
}
func (c *Cryptor) Encrypt(plaintext []byte) ([]byte, error) {
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
2023-06-30 13:26:46 +00:00
block, err := aes.NewCipher(c.AESCTR256Key)
2023-06-30 09:54:08 +00:00
if err != nil {
return nil, err
}
ciphertext := make([]byte, len(plaintext))
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(ciphertext, plaintext)
ciphertext = append(ciphertext, iv...)
2023-06-30 13:26:46 +00:00
mac := hmac.New(sha256.New, c.SHA256Key)
2023-06-30 09:54:08 +00:00
mac.Write(ciphertext)
hmac := mac.Sum(nil)
ciphertext = append(ciphertext, hmac...)
return ciphertext, nil
}
func (c *Cryptor) Decrypt(encryptedData []byte) ([]byte, error) {
if len(encryptedData) < 48 {
return nil, errors.New("input data is too short")
}
hmacSignature := encryptedData[len(encryptedData)-32:]
encryptedDataWithoutHMAC := encryptedData[:len(encryptedData)-32]
2023-06-30 13:26:46 +00:00
mac := hmac.New(sha256.New, c.SHA256Key)
2023-06-30 09:54:08 +00:00
mac.Write(encryptedDataWithoutHMAC)
expectedHMAC := mac.Sum(nil)
if !hmac.Equal(hmacSignature, expectedHMAC) {
return nil, errors.New("HMAC mismatch")
}
iv := encryptedDataWithoutHMAC[len(encryptedDataWithoutHMAC)-16:]
encryptedDataWithoutHMAC = encryptedDataWithoutHMAC[:len(encryptedDataWithoutHMAC)-16]
2023-06-30 13:26:46 +00:00
block, err := aes.NewCipher(c.AESCTR256Key)
2023-06-30 09:54:08 +00:00
if err != nil {
return nil, err
}
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(encryptedDataWithoutHMAC, encryptedDataWithoutHMAC)
return encryptedDataWithoutHMAC, nil
}
func (c *Cryptor) DecryptAndDecodeData(encryptedData []byte, message protoreflect.ProtoMessage) error {
decryptedData, err := c.Decrypt(encryptedData)
if err != nil {
return err
}
err = binary.DecodeProtoMessage(decryptedData, message)
if err != nil {
return err
}
return nil
}