1// Copyright 2020 Google LLC 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14// 15//////////////////////////////////////////////////////////////////////////////// 16 17package subtle 18 19import ( 20 "crypto/ed25519" 21 "errors" 22 "fmt" 23) 24 25var errInvalidED25519Signature = errors.New("ed25519: invalid signature") 26 27// ED25519Verifier is an implementation of Verifier for ED25519. 28// At the moment, the implementation only accepts signatures with strict DER encoding. 29type ED25519Verifier struct { 30 publicKey *ed25519.PublicKey 31} 32 33// NewED25519Verifier creates a new instance of ED25519Verifier. 34func NewED25519Verifier(pub []byte) (*ED25519Verifier, error) { 35 publicKey := ed25519.PublicKey(pub) 36 return NewED25519VerifierFromPublicKey(&publicKey) 37} 38 39// NewED25519VerifierFromPublicKey creates a new instance of ED25519Verifier. 40func NewED25519VerifierFromPublicKey(publicKey *ed25519.PublicKey) (*ED25519Verifier, error) { 41 return &ED25519Verifier{ 42 publicKey: publicKey, 43 }, nil 44} 45 46// Verify verifies whether the given signature is valid for the given data. 47// It returns an error if the signature is not valid; nil otherwise. 48func (e *ED25519Verifier) Verify(signature, data []byte) error { 49 if len(signature) != ed25519.SignatureSize { 50 return fmt.Errorf("the length of the signature is not %d", ed25519.SignatureSize) 51 } 52 if !ed25519.Verify(*e.publicKey, data, signature) { 53 return errInvalidED25519Signature 54 } 55 return nil 56} 57