/
main.go
86 lines (76 loc) · 1.64 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base64"
"encoding/pem"
"flag"
"fmt"
"io/ioutil"
"log"
"math/big"
"os"
)
type PublicKeyInfo struct {
Algorithm pkix.AlgorithmIdentifier
PublicKey asn1.BitString
}
type RSAPublicKey struct {
N *big.Int
E int
}
var (
file = flag.String("file", "", "A PEM-encoded public key or certificate file.")
verbose = flag.Bool("verbose", false, "Show more information.")
)
func main() {
flag.Parse()
var contents []byte
var err error
if *file == "" {
contents, err = ioutil.ReadAll(os.Stdin)
} else {
contents, err = ioutil.ReadFile(*file)
}
if err != nil {
log.Fatal(err)
}
block, _ := pem.Decode(contents)
if block == nil {
log.Fatal("Not a PEM block.")
}
var keybytes []byte
switch block.Type {
case "PUBLIC KEY", "RSA PUBLIC KEY":
keybytes = block.Bytes
case "CERTIFICATE":
certs, err := x509.ParseCertificates(block.Bytes)
if err != nil {
log.Fatal(err)
}
if len(certs) < 1 {
log.Fatal("No certificates.")
}
keybytes = certs[0].RawSubjectPublicKeyInfo
default:
log.Fatalf("Unknown block type: %q.", block.Type)
}
hasher := sha256.New()
hasher.Write(keybytes)
fmt.Printf("sha256/%v\n", base64.StdEncoding.EncodeToString(hasher.Sum(nil)))
if *verbose {
var spki PublicKeyInfo
if _, err := asn1.Unmarshal(keybytes, &spki); err != nil {
log.Fatal(err)
}
fmt.Printf("AlgID: %v\n", spki.Algorithm.Algorithm)
var pubkey RSAPublicKey
if _, err := asn1.Unmarshal(spki.PublicKey.Bytes, &pubkey); err != nil {
log.Fatal(err)
}
fmt.Printf("N: %v\n", pubkey.N)
fmt.Printf("E: %v\n", pubkey.E)
}
}