Last active
January 30, 2023 02:19
-
-
Save blacknon/8eca60b57ed986107aad83258ed81d31 to your computer and use it in GitHub Desktop.
goで`github.com/miekg/pkcs11/p11`を使って、Yubikey内のpublic keyをssh-rsa形式で出力するsampleコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2020 Blacknon. All rights reserved. | |
// Use of this source code is governed by an MIT license | |
// that can be found in the LICENSE file. | |
// `github.com/miekg/pkcs11/p11`を使って、Yubikey内のpublic keyをssh-rsa形式で出力するsampleコード | |
package main | |
import ( | |
"crypto/rsa" | |
"crypto/x509" | |
"encoding/base64" | |
"fmt" | |
"os" | |
"github.com/miekg/pkcs11" | |
"github.com/miekg/pkcs11/p11" | |
"golang.org/x/crypto/ssh" | |
) | |
var ( | |
provider = "/usr/local/lib/opensc-pkcs11.so" | |
) | |
// main | |
func main() { | |
module, err := p11.OpenModule(provider) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
slots, err := module.Slots() | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
for _, slot := range slots { | |
tokenInfo, _ := slot.TokenInfo() | |
fmt.Println(tokenInfo.Label) | |
session, _ := slot.OpenSession() | |
pub := []*pkcs11.Attribute{ | |
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY), | |
} | |
obj, _ := session.FindObjects(pub) | |
for _, o := range obj { | |
l, err := o.Label() | |
if err != nil { | |
fmt.Println(err) | |
continue | |
} | |
v, err := o.Value() | |
if err != nil { | |
fmt.Println(err) | |
continue | |
} | |
rsaPubKey, err := x509.ParsePKIXPublicKey(v) | |
if err != nil { | |
fmt.Println(err) | |
continue | |
} | |
sshKey, ok := rsaPubKey.(*rsa.PublicKey) | |
if !ok { | |
fmt.Println("invalid PEM passed in from user") | |
continue | |
} | |
pub, err := ssh.NewPublicKey(sshKey) | |
if err != nil { | |
fmt.Println(err) | |
continue | |
} | |
p := base64.StdEncoding.EncodeToString(pub.Marshal()) | |
fmt.Println(l, ":", p) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考