Matrix/utils/encryptionService.go

75 lines
1.6 KiB
Go
Raw Normal View History

2020-10-04 12:22:52 +00:00
package utils
import (
2020-10-11 21:11:30 +00:00
"crypto/ed25519"
2020-10-04 12:22:52 +00:00
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"log"
2020-10-11 21:11:30 +00:00
2020-10-12 14:16:28 +00:00
"git.nutfactory.org/hoernschen/Matrix/config"
2020-10-04 12:22:52 +00:00
)
func CreateToken() (err error, token string) {
b := make([]byte, 8)
_, err = rand.Read(b)
if err != nil {
log.Fatal(err)
return
}
2020-10-11 21:11:30 +00:00
token = fmt.Sprintf("%x", b)
2020-10-04 12:22:52 +00:00
return
}
func CreateUUID() (err error, uuid string) {
b := make([]byte, 16)
_, err = rand.Read(b)
if err != nil {
log.Fatal(err)
return
}
2020-10-11 21:11:30 +00:00
uuid = fmt.Sprintf("%x_%x_%x_%x_%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
2020-10-04 12:22:52 +00:00
return
}
func Hash(s []byte) (err error, hashString string) {
h := sha256.New()
_, err = h.Write(s)
if nil != err {
return
}
hash := h.Sum(nil)
hashString = base64.StdEncoding.EncodeToString(hash)
return
}
2020-10-11 21:11:30 +00:00
func GenerateKeyPair() (publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey, err error) {
publicKey, privateKey, err = ed25519.GenerateKey(nil)
return
}
2020-10-17 10:07:39 +00:00
func Sign(message []byte) string {
signatureBytes := ed25519.Sign(config.PrivateKey, message)
return base64.RawStdEncoding.EncodeToString(signatureBytes)
2020-10-11 21:11:30 +00:00
}
func SignContent(content []byte) (signatures map[string]map[string]string) {
signatures = make(map[string]map[string]string)
signatures[config.Homeserver] = make(map[string]string)
2020-10-17 10:07:39 +00:00
if !config.Signing {
return
}
signatures[config.Homeserver][config.KeyId] = Sign(content)
2020-10-11 21:11:30 +00:00
return
}
2020-10-17 10:07:39 +00:00
func VerifySignature(publicKey []byte, message []byte, signature string) bool {
signatureBytes, err := base64.RawStdEncoding.DecodeString(signature)
if err != nil {
return false
}
ed25519.Verify(config.PublicKey, message, signatureBytes)
return true
2020-10-11 21:11:30 +00:00
}