Files
oc-lib/tools/crypto.go
2026-02-26 09:48:51 +01:00

79 lines
1.4 KiB
Go

package tools
import (
"bytes"
"crypto/ed25519"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"cloud.o-forge.io/core/oc-lib/config"
"github.com/libp2p/go-libp2p/core/crypto"
)
func LoadKeyFromFilePrivate() (crypto.PrivKey, error) {
path := config.GetConfig().PrivateKeyPath
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil {
return nil, fmt.Errorf("failed to decode PEM")
}
keyAny, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
edKey, ok := keyAny.(ed25519.PrivateKey)
if !ok {
return nil, fmt.Errorf("not an ed25519 key")
}
// Convert properly to libp2p key
privKey, _, err := crypto.GenerateEd25519Key(
bytes.NewReader(edKey.Seed()),
)
if err != nil {
return nil, err
}
return privKey, nil
}
func LoadKeyFromFilePublic() (crypto.PubKey, error) {
path := config.GetConfig().PublicKeyPath
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil {
return nil, fmt.Errorf("failed to decode PEM")
}
keyAny, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
edKey, ok := keyAny.(ed25519.PublicKey)
if !ok {
return nil, fmt.Errorf("not an ed25519 key")
}
// Convert Go ed25519 key to libp2p key
pubKey, err := crypto.UnmarshalEd25519PublicKey(edKey)
if err != nil {
return nil, err
}
return pubKey, nil
}