go-piv / piv-go

Keys and certificates for YubiKeys, written in Go
Apache License 2.0
368 stars 65 forks source link

Unable to retrieve public key #93

Closed hazcod closed 3 years ago

hazcod commented 3 years ago

Hi! Thank you for the library. I'm trying to fetch the public key for generated keypair but this always returns in command failed: smart card error 6a82: data object or application not found.

Code:

    key := piv.Key{
        Algorithm:   piv.AlgorithmRSA2048,
        PINPolicy:   piv.PINPolicyOnce,
        TouchPolicy: piv.TouchPolicyNever,
    }

    newPubKey, err := yubi.GenerateKey(piv.DefaultManagementKey, piv.SlotAuthentication, key)
    if err != nil {
        logger.WithError(err).Fatal("could not generate new public key on the security device")
    }

    cert, err := yubi.Certificate(piv.SlotAuthentication)
    if err != nil {
                // ERROR HERE
        return nil, errors.Wrap(err, "could not get certificate from yubikey")
    }

Any ideas?

ericchiang commented 3 years ago

It's likely you haven't set the certificate

https://pkg.go.dev/github.com/go-piv/piv-go/piv#YubiKey.SetCertificate

hazcod commented 3 years ago

Hmmm, is that necessary when doing a GenerateKey? I thought GenerateKey creates a Public and Private key on that slot on the yubi. Or am I missing something here?

To elaborate: I am just trying to retrieve the public key which I generated on the device.

hazcod commented 3 years ago

never mind:

    cert, err := yubi.Attest(piv.SlotAuthentication)
    if err != nil {
        return nil, errors.Wrap(err, "could not get certificate from yubikey")
    }

    newPubKeyRSA, ok := cert.PublicKey.(*rsa.PublicKey)
    if !ok {
        return nil, errors.New("generated public key on yubikey is invalid")
    }