meowlib/server/identity.go

73 lines
2.0 KiB
Go
Raw Normal View History

2022-09-06 17:07:35 +02:00
package server
2022-09-06 09:30:45 +02:00
import (
"encoding/json"
2022-09-06 17:07:35 +02:00
"fmt"
2022-09-06 09:30:45 +02:00
"io/ioutil"
"forge.redroom.link/yves/meowlib"
"github.com/ProtonMail/gopenpgp/v2/helper"
)
const key = "3pw0c8#6ZG8{75b5;3?fe80$2"
type Identity struct {
2022-09-06 17:07:35 +02:00
ServerName string `json:"servername,omitempty"`
ServerDesc string `json:"serverdesc,omitempty"`
ServerKp meowlib.KeyPair `json:"server_kp,omitempty"`
Status string `json:"status,omitempty"`
2022-09-06 09:30:45 +02:00
// KnownServers ServerList `json:"known_servers,omitempty"`
}
2022-09-06 17:07:35 +02:00
func CreateIdentity(ServerName string, ServerDesc string) *Identity {
2022-09-06 09:30:45 +02:00
var id Identity
2022-09-06 17:07:35 +02:00
id.ServerName = ServerName
id.ServerDesc = ServerDesc
id.ServerKp = meowlib.NewKeyPair()
2022-09-06 09:30:45 +02:00
return &id
}
2022-09-06 17:07:35 +02:00
func LoadIdentity(File string) (*Identity, error) {
2022-09-06 09:30:45 +02:00
var id Identity
2022-09-06 17:07:35 +02:00
indata, err := ioutil.ReadFile(File)
2022-09-06 09:30:45 +02:00
if err != nil {
return nil, err
}
pass, err := helper.DecryptMessageWithPassword([]byte(key), string(indata))
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(pass), &id)
return &id, err
}
func (id *Identity) Save(file string) error {
b, _ := json.Marshal(id)
armor, err := helper.EncryptMessageWithPassword([]byte(key), string(b))
if err != nil {
return err
}
err = ioutil.WriteFile(file, []byte(armor), 0644)
return err
}
2022-09-06 17:07:35 +02:00
// AsymEncryptMessage prepares a message to send to a specific client contact
func (id *Identity) AsymEncryptMessage(ClientPublicKey string, Message []byte) (EncryptedMsg []byte, Signature []byte, err error) {
2022-09-18 21:17:28 +02:00
EncryptedMsg, Signature, err = meowlib.AsymEncryptAndSign(ClientPublicKey, id.ServerKp.Private, Message)
2022-09-06 17:07:35 +02:00
if err != nil {
fmt.Println(err.Error())
return nil, nil, err
}
return EncryptedMsg, Signature, err
}
// AsymDecryptMessage reads a message from a specific client contact
func (id *Identity) AsymDecryptMessage(ClientPublicKey string, Message []byte, Signature []byte) (DecryptedMsg []byte, err error) {
2022-09-18 21:17:28 +02:00
DecryptedMsg, err = meowlib.AsymDecryptAndCheck(id.ServerKp.Private, ClientPublicKey, Message, Signature)
2022-09-06 17:07:35 +02:00
if err != nil {
fmt.Println(err.Error())
return nil, err
}
return DecryptedMsg, err
}