File: decoder.go

package info (click to toggle)
golang-github-go-crypt-crypt 0.4.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 516 kB
  • sloc: makefile: 4
file content (76 lines) | stat: -rw-r--r-- 1,939 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package sha1crypt

import (
	"fmt"
	"strconv"

	"github.com/go-crypt/crypt/algorithm"
	"github.com/go-crypt/crypt/internal/encoding"
)

// RegisterDecoder the decoder with the algorithm.DecoderRegister.
func RegisterDecoder(r algorithm.DecoderRegister) (err error) {
	if err = RegisterDecoderCommon(r); err != nil {
		return err
	}

	return nil
}

// RegisterDecoderCommon registers specifically the common decoder variant with the algorithm.DecoderRegister.
func RegisterDecoderCommon(r algorithm.DecoderRegister) (err error) {
	if err = r.RegisterDecodeFunc(AlgIdentifier, Decode); err != nil {
		return err
	}

	return nil
}

// Decode the encoded digest into a algorithm.Digest.
func Decode(encodedDigest string) (digest algorithm.Digest, err error) {
	var (
		parts []string
	)

	if parts, err = decoderParts(encodedDigest); err != nil {
		return nil, fmt.Errorf(algorithm.ErrFmtDigestDecode, AlgName, err)
	}

	if digest, err = decode(parts); err != nil {
		return nil, fmt.Errorf(algorithm.ErrFmtDigestDecode, AlgName, err)
	}

	return digest, nil
}

func decoderParts(encodedDigest string) (parts []string, err error) {
	parts = encoding.Split(encodedDigest, -1)

	if len(parts) != 5 {
		return nil, algorithm.ErrEncodedHashInvalidFormat
	}

	if parts[1] != AlgIdentifier {
		return nil, fmt.Errorf("%w: identifier '%s' is not an encoded %s digest", algorithm.ErrEncodedHashInvalidIdentifier, parts[1], AlgName)
	}

	return parts[2:], nil
}

func decode(parts []string) (digest algorithm.Digest, err error) {
	decoded := &Digest{}

	if parts[0] != "" {
		var iterations uint64

		if iterations, err = strconv.ParseUint(parts[0], 10, 32); err != nil {
			return nil, fmt.Errorf("%w: option '%s' has invalid value '%s': %v", algorithm.ErrEncodedHashInvalidOptionValue, "rounds", parts[0], err)
		}

		decoded.iterations = uint32(iterations)
	}

	decoded.salt, decoded.key = []byte(parts[1]), []byte(parts[2])

	return decoded, nil
}