Files
oc-peer/infrastructure/crypto.go

67 lines
1.3 KiB
Go
Raw Normal View History

2026-01-15 13:35:11 +01:00
package infrastructure
import (
2026-01-27 15:49:57 +01:00
"bytes"
2026-01-15 13:35:11 +01:00
"fmt"
"oc-peer/conf"
"os"
"github.com/libp2p/go-libp2p/core/crypto"
2026-01-27 15:49:57 +01:00
"github.com/libp2p/go-libp2p/core/pnet"
2026-01-15 13:35:11 +01:00
)
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)
}
2026-01-26 11:23:04 +01:00
func LoadKeyFromFile(isPublic bool) (crypto.PrivKey, error) {
2026-01-15 13:35:11 +01:00
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 {
2026-01-26 11:23:04 +01:00
priv, err := LoadKeyFromFile(false)
2026-01-15 13:35:11 +01:00
if err != nil {
fmt.Println(err)
return false
}
2026-01-26 11:23:04 +01:00
pub, err := LoadKeyFromFile(true)
2026-01-15 13:35:11 +01:00
if err != nil {
fmt.Println(err)
return false
}
return priv.GetPublic().Equals(pub)
}
2026-01-27 15:49:57 +01:00
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
}