func()

in pkg/sdk/value/signature/raw/transformer.go [44:138]


func (d *rawTransformer) To(ctx context.Context, input []byte) ([]byte, error) {
	if types.IsNil(d.key) {
		return nil, fmt.Errorf("paseto: signer key must not be nil")
	}

	var (
		sig []byte
		err error
	)

	switch sk := d.key.(type) {
	case ed25519.PrivateKey:
		// Ed25519 doesn't support pre-hash as input to prevent collision.
		sig = ed25519.Sign(sk, input)

	case *ecdsa.PrivateKey:
		var digest []byte

		// Get hash function for curve
		hf, errHash := d.hashFromCurve(sk.Curve)
		if errHash != nil {
			return nil, fmt.Errorf("raw: unable to retrieve hash function for curve: %w", errHash)
		}

		// Build a hash function instance
		h := hf()

		// Input is already a hash?
		if signature.IsInputPreHashed(ctx) {
			digest = input
			if len(digest) != h.Size() {
				return nil, fmt.Errorf("raw: invalid pre-hash length, expected %d bytes, got %d", h.Size(), len(input))
			}
		} else {
			// Hash the decoded content
			h.Write(input)

			// Set hash value
			digest = h.Sum(nil)
		}

		var (
			errSig error
			r, s   *big.Int
		)
		if signature.IsDeterministic(ctx) {
			// Deterministic signature
			r, s = rfc6979.SignECDSA(sk, digest, hf)
			if r == nil {
				errSig = errors.New("unable to apply determistic signature")
			}
		} else {
			// Sign
			r, s, errSig = ecdsa.Sign(rand.Reader, sk, digest)
		}
		if errSig != nil {
			return nil, fmt.Errorf("raw: unable to sign the content: %w", errSig)
		}

		// Calculate optimized buffer size
		curveBits := sk.Curve.Params().BitSize
		keyBytes := curveBits / 8
		if curveBits%8 > 0 {
			keyBytes++
		}

		// We serialize the outputs (r and s) into big-endian byte arrays and pad
		// them with zeros on the left to make sure the sizes work out. Both arrays
		// must be keyBytes long, and the output must be 2*keyBytes long.
		rBytes := r.Bytes()
		rBytesPadded := make([]byte, keyBytes)
		copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)

		sBytes := s.Bytes()
		sBytesPadded := make([]byte, keyBytes)
		copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)

		// Assemble the signature
		sig = rBytesPadded
		sig = append(sig, sBytesPadded...)
	default:
		return nil, errors.New("raw: key is not supported")
	}
	if err != nil {
		return nil, fmt.Errorf("raw: unable to sign input: %w", err)
	}

	// Detached signature requested?
	if signature.IsDetached(ctx) {
		return sig, nil
	}

	// No error
	return append(sig, input...), nil
}