67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
package infrastructure
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"oc-peer/conf"
|
|
"os"
|
|
|
|
"github.com/libp2p/go-libp2p/core/crypto"
|
|
"github.com/libp2p/go-libp2p/core/pnet"
|
|
)
|
|
|
|
func sign(priv crypto.PrivKey, data []byte) ([]byte, error) {
|
|
return priv.Sign(data)
|
|
}
|
|
|
|
func verify(pub crypto.PubKey, data, sig []byte) (bool, error) {
|
|
return pub.Verify(data, sig)
|
|
}
|
|
|
|
func LoadKeyFromFile(isPublic bool) (crypto.PrivKey, error) {
|
|
path := conf.GetConfig().PrivateKeyPath
|
|
if isPublic {
|
|
path = conf.GetConfig().PublicKeyPath
|
|
}
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Try to unmarshal as libp2p private key (supports ed25519, rsa, etc.)
|
|
priv, err := crypto.UnmarshalPrivateKey(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return priv, nil
|
|
}
|
|
|
|
func VerifyPubWithPriv() bool {
|
|
priv, err := LoadKeyFromFile(false)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return false
|
|
}
|
|
pub, err := LoadKeyFromFile(true)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return false
|
|
}
|
|
return priv.GetPublic().Equals(pub)
|
|
}
|
|
|
|
func LoadPSKFromFile() (pnet.PSK, error) {
|
|
path := conf.GetConfig().PSKPath
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Try to unmarshal as libp2p private key (supports ed25519, rsa, etc.)
|
|
psk, err := pnet.DecodeV1PSK(bytes.NewReader(data))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return psk, nil
|
|
}
|