Files
oc-lib/tools/crypto.go

79 lines
1.4 KiB
Go
Raw Normal View History

2026-02-09 12:37:03 +01:00
package tools
import (
2026-02-26 09:48:51 +01:00
"bytes"
2026-02-09 12:37:03 +01:00
"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
}
2026-02-26 09:48:51 +01:00
2026-02-09 12:37:03 +01:00
block, _ := pem.Decode(data)
2026-02-26 09:48:51 +01:00
if block == nil {
return nil, fmt.Errorf("failed to decode PEM")
}
2026-02-09 12:37:03 +01:00
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")
}
2026-02-26 09:48:51 +01:00
// Convert properly to libp2p key
privKey, _, err := crypto.GenerateEd25519Key(
bytes.NewReader(edKey.Seed()),
)
if err != nil {
return nil, err
}
return privKey, nil
2026-02-09 12:37:03 +01:00
}
func LoadKeyFromFilePublic() (crypto.PubKey, error) {
path := config.GetConfig().PublicKeyPath
2026-02-26 09:48:51 +01:00
2026-02-09 12:37:03 +01:00
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
2026-02-26 09:48:51 +01:00
2026-02-09 12:37:03 +01:00
block, _ := pem.Decode(data)
2026-02-26 09:48:51 +01:00
if block == nil {
return nil, fmt.Errorf("failed to decode PEM")
}
2026-02-09 12:37:03 +01:00
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")
}
2026-02-26 09:48:51 +01:00
// Convert Go ed25519 key to libp2p key
pubKey, err := crypto.UnmarshalEd25519PublicKey(edKey)
if err != nil {
return nil, err
}
return pubKey, nil
2026-02-09 12:37:03 +01:00
}