Matrix/entities/device/keyController.go
2020-10-11 23:11:30 +02:00

76 lines
1.9 KiB
Go

package device
import (
"encoding/json"
"fmt"
"net/http"
"nutfactory.org/Matrix/config"
"nutfactory.org/Matrix/utils"
)
func InitServerSigningKey() (err error) {
publicKey, privateKey, err := utils.GenerateKeyPair()
if err != nil {
return
}
config.PublicKey = publicKey
config.PrivateKey = privateKey
config.KeyId = "ed25519:1"
return
}
func GetServerSigningKeyHandler(w http.ResponseWriter, r *http.Request) {
if config.PublicKey == nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Server Signing Key Missing"}); err != nil {
panic(err)
}
return
}
response := serverKeys{
ServerName: config.Homeserver,
VerifyKeys: make(map[string]verifyKey),
}
response.VerifyKeys[config.KeyId] = verifyKey{Key: string(config.PublicKey)}
content, err := json.Marshal(response)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: fmt.Sprintf("Error creating Signatures: %s", err)}); err != nil {
panic(err)
}
return
}
response.Signatures = utils.SignContent(content)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(response); err != nil {
panic(err)
}
}
func getVerifyKey(server string, id string) (key []byte, err error) {
if val, ok := config.VerifyKeys[server][id]; ok {
key = val
} else {
httpString := "https"
requestUrl := fmt.Sprintf("%s://%s/_matrix/key/v2/server", httpString, server)
var res *http.Response
res, err = http.Get(requestUrl)
if err != nil {
return
}
serverKeyRes := serverKeys{}
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&serverKeyRes)
config.VerifyKeys[server] = make(map[string][]byte)
for keyId, verifyKey := range serverKeyRes.VerifyKeys {
config.VerifyKeys[server][keyId] = []byte(verifyKey.Key)
if id == keyId {
key = []byte(verifyKey.Key)
}
}
}
return
}