Debian Codegraph @

examples/tpm-sign/verify.go

raw
1 //go:build !windows
2
3 // Copyright (c) 2018, Ian Haken. All rights reserved.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 package main
18
19 import (
20 "crypto/rsa"
21 "crypto/x509"
22 "flag"
23 "fmt"
24 "io"
25 "os"
26 )
27
28 func verifyAction() {
29 var pubKeyPath = flag.String("public-key", "publickey", "Input path of public key file")
30 var hashAlgArg = flag.String("hash", "SHA256", "Hash algorithm to use when verifying the signature")
31 var signaturePath = flag.String("signature", "sig.data", "Input path of previously generated signature")
32 var dataPath = flag.String("data", "", "Path to the data that was signed. If empty or omitted, the data will be read from stdin.")
33 flag.CommandLine.Parse(os.Args[2:])
34
35 hashAlg, ok := hashNames[*hashAlgArg]
36 if !ok {
37 fmt.Fprintf(os.Stderr, "Invalid hash algorithm: %s\n", *hashAlgArg)
38 return
39 }
40
41 var err error
42 var data []byte
43 if *dataPath == "" {
44 data, err = io.ReadAll(os.Stdin)
45 } else {
46 data, err = os.ReadFile(*dataPath)
47 }
48 if err != nil {
49 fmt.Fprintf(os.Stderr, "Error reading input data: %s\n", err)
50 return
51 }
52
53 signature, err := os.ReadFile(*signaturePath)
54 if err != nil {
55 fmt.Fprintf(os.Stderr, "Error reading signature file: %s\n", err)
56 return
57 }
58
59 pubKeyBytes, err := os.ReadFile(*pubKeyPath)
60 if err != nil {
61 fmt.Fprintf(os.Stderr, "Error reading public key file: %s\n", err)
62 return
63 }
64 pubKey, err := x509.ParsePKIXPublicKey(pubKeyBytes)
65 if err != nil {
66 fmt.Fprintf(os.Stderr, "Error parsing public key: %s\n", err)
67 return
68 }
69 rsaPubKey, ok := pubKey.(*rsa.PublicKey)
70 if !ok {
71 fmt.Fprintf(os.Stderr, "Expected public key to be an RSA key, but was %T\n", pubKey)
72 return
73 }
74
75 hash := hashAlg.New()
76 if _, err = hash.Write(data); err != nil {
77 fmt.Fprintf(os.Stderr, "Error building hash of data: %s\n", err)
78 return
79 }
80 hashed := hash.Sum(nil)
81 if err = rsa.VerifyPKCS1v15(rsaPubKey, hashAlg, hashed[:], signature); err != nil {
82 fmt.Fprintf(os.Stderr, "Error from verification: %s\n", err)
83 return
84 }
85 fmt.Printf("Signature valid.\n")
86 }