|
| 1 | +//go:build go1.27 |
| 2 | + |
| 3 | +package privatekey |
| 4 | + |
| 5 | +import ( |
| 6 | + "crypto" |
| 7 | + "crypto/ecdsa" |
| 8 | + "crypto/mldsa" |
| 9 | + "crypto/rsa" |
| 10 | + "errors" |
| 11 | + "fmt" |
| 12 | + "hash" |
| 13 | +) |
| 14 | + |
| 15 | +// verify ensures that the embedded PublicKey of the provided privateKey is |
| 16 | +// actually a match for the private key. For an example of private keys |
| 17 | +// embedding a mismatched public key, see: |
| 18 | +// https://blog.hboeck.de/archives/888-How-I-tricked-Symantec-with-a-Fake-Private-Key.html. |
| 19 | +// |
| 20 | +// TODO(#8812): move this back to privatekey.go, above Load(). |
| 21 | +func verify(privateKey crypto.Signer) (crypto.Signer, crypto.PublicKey, error) { |
| 22 | + verifyHash, err := makeVerifyHash() |
| 23 | + if err != nil { |
| 24 | + return nil, nil, err |
| 25 | + } |
| 26 | + |
| 27 | + switch k := privateKey.(type) { |
| 28 | + case *rsa.PrivateKey: |
| 29 | + return verifyRSA(k, &k.PublicKey, verifyHash) |
| 30 | + |
| 31 | + case *ecdsa.PrivateKey: |
| 32 | + return verifyECDSA(k, &k.PublicKey, verifyHash) |
| 33 | + |
| 34 | + case *mldsa.PrivateKey: |
| 35 | + return verifyMLDSA(k, k.PublicKey(), verifyHash) |
| 36 | + |
| 37 | + default: |
| 38 | + // This should never happen. |
| 39 | + return nil, nil, errors.New("the provided private key was not *rsa.PrivateKey, *ecdsa.PrivateKey, or *mldsa.PrivateKey") |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// verifyMLDSA verifies ML-DSA private keys. |
| 44 | +func verifyMLDSA(privKey *mldsa.PrivateKey, pubKey *mldsa.PublicKey, msgHash hash.Hash) (crypto.Signer, crypto.PublicKey, error) { |
| 45 | + sig, err := privKey.Sign(nil, msgHash.Sum(nil), nil) |
| 46 | + if err != nil { |
| 47 | + return nil, nil, fmt.Errorf("failed to sign using the provided ML-DSA private key: %s", err) |
| 48 | + } |
| 49 | + |
| 50 | + err = mldsa.Verify(pubKey, msgHash.Sum(nil), sig, nil) |
| 51 | + if err != nil { |
| 52 | + return nil, nil, fmt.Errorf("the provided ML-DSA private key failed signature verification: %s", err) |
| 53 | + } |
| 54 | + return privKey, privKey.Public(), nil |
| 55 | +} |
0 commit comments