1
0
Fork 0
mirror of https://github.com/Mic92/sops-nix.git synced 2025-03-06 08:37:21 +00:00
sops-nix/pkgs/sops-install-secrets/sshkeys/convert.go

70 lines
1.8 KiB
Go
Raw Normal View History

2020-07-12 13:50:55 +01:00
package sshkeys
import (
"crypto"
"crypto/rsa"
"fmt"
"reflect"
"time"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/packet"
"golang.org/x/crypto/ssh"
)
func parsePrivateKey(sshPrivateKey []byte) (*rsa.PrivateKey, error) {
privateKey, err := ssh.ParseRawPrivateKey(sshPrivateKey)
if err != nil {
2020-07-13 06:14:23 +01:00
return nil, err
2020-07-12 13:50:55 +01:00
}
rsaKey, ok := privateKey.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("Only RSA keys are supported right now, got: %s", reflect.TypeOf(privateKey))
}
return rsaKey, nil
}
func SSHPrivateKeyToPGP(sshPrivateKey []byte) (*openpgp.Entity, error) {
key, err := parsePrivateKey(sshPrivateKey)
if err != nil {
2020-07-30 16:22:43 +01:00
return nil, fmt.Errorf("failed to parse private ssh key: %w", err)
2020-07-12 13:50:55 +01:00
}
// Let's make keys reproducible
timeNull := time.Unix(0, 0)
gpgKey := &openpgp.Entity{
PrimaryKey: packet.NewRSAPublicKey(timeNull, &key.PublicKey),
PrivateKey: packet.NewRSAPrivateKey(timeNull, key),
Identities: make(map[string]*openpgp.Identity),
}
2020-07-13 09:12:47 +01:00
uid := packet.NewUserId("root", "Imported from SSH", "root@localhost")
2020-07-12 13:50:55 +01:00
isPrimaryID := true
gpgKey.Identities[uid.Id] = &openpgp.Identity{
Name: uid.Id,
UserId: uid,
SelfSignature: &packet.Signature{
CreationTime: timeNull,
SigType: packet.SigTypePositiveCert,
PubKeyAlgo: packet.PubKeyAlgoRSA,
Hash: crypto.SHA256,
IsPrimaryId: &isPrimaryID,
FlagsValid: true,
FlagSign: true,
FlagCertify: true,
FlagEncryptStorage: true,
FlagEncryptCommunications: true,
IssuerKeyId: &gpgKey.PrimaryKey.KeyId,
},
}
2020-07-13 09:12:47 +01:00
err = gpgKey.Identities[uid.Id].SelfSignature.SignUserId(uid.Id, gpgKey.PrimaryKey, gpgKey.PrivateKey, nil)
if err != nil {
return nil, err
}
2020-07-12 13:50:55 +01:00
return gpgKey, nil
}