github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/signature/paseto/transformer.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // 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, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package paseto 19 20 import ( 21 "context" 22 "crypto/ecdsa" 23 "crypto/ed25519" 24 "errors" 25 "fmt" 26 27 pasetov3 "zntr.io/paseto/v3" 28 pasetov4 "zntr.io/paseto/v4" 29 30 "github.com/zntrio/harp/v2/pkg/sdk/types" 31 ) 32 33 type pasetoTransformer struct { 34 key interface{} 35 } 36 37 // ----------------------------------------------------------------------------- 38 39 func (d *pasetoTransformer) To(_ context.Context, input []byte) ([]byte, error) { 40 if types.IsNil(d.key) { 41 return nil, fmt.Errorf("paseto: signer key must not be nil") 42 } 43 44 var ( 45 out string 46 err error 47 ) 48 49 switch sk := d.key.(type) { 50 case ed25519.PrivateKey: 51 out, err = pasetov4.Sign(input, sk, nil, nil) 52 case *ecdsa.PrivateKey: 53 out, err = pasetov3.Sign(input, sk, nil, nil) 54 default: 55 return nil, errors.New("paseto: key is not supported") 56 } 57 if err != nil { 58 return nil, fmt.Errorf("paseto: unable so sign input: %w", err) 59 } 60 61 // No error 62 return []byte(out), nil 63 } 64 65 func (d *pasetoTransformer) From(_ context.Context, input []byte) ([]byte, error) { 66 var ( 67 payload []byte 68 err error 69 ) 70 71 switch sk := d.key.(type) { 72 case ed25519.PublicKey: 73 payload, err = pasetov4.Verify(string(input), sk, nil, nil) 74 case *ecdsa.PublicKey: 75 payload, err = pasetov3.Verify(string(input), sk, nil, nil) 76 default: 77 return nil, errors.New("paseto: key is not supported") 78 } 79 if err != nil { 80 return nil, fmt.Errorf("paseto: unable so sign input: %w", err) 81 } 82 83 // No error 84 return payload, nil 85 }