File: normalize.go

package info (click to toggle)
golang-github-go-crypt-crypt 0.4.7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 516 kB
  • sloc: makefile: 4
file content (42 lines) | stat: -rw-r--r-- 1,089 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
package crypt

import (
	"fmt"
	"regexp"
	"strings"
)

var (
	reAlgorithmPrefixPBKDF2 = regexp.MustCompile(`^\{(?P<identifier>PBKDF2(-SHA\d+)?)}(?P<remainder>\d+\$.*)$`)
)

// Normalize performs normalization on an encoded digest. This removes prefixes which are not necessary and performs
// minimal modification to the encoded digest to make it possible for decoding.
func Normalize(encodedDigest string) string {
	if strings.HasPrefix(encodedDigest, StorageFormatPrefixLDAPCrypt) {
		encodedDigest = encodedDigest[7:]
	}

	if strings.HasPrefix(encodedDigest, StorageFormatPrefixLDAPArgon2) {
		encodedDigest = encodedDigest[8:]
	}

	matchesPBKDF2 := reAlgorithmPrefixPBKDF2.FindStringSubmatch(encodedDigest)

	if len(matchesPBKDF2) != 0 {
		var identifier, remainder string

		for g, group := range reAlgorithmPrefixPBKDF2.SubexpNames() {
			switch group {
			case "identifier":
				identifier = matchesPBKDF2[g]
			case "remainder":
				identifier = matchesPBKDF2[g]
			}
		}

		encodedDigest = fmt.Sprintf("$%s$%s", strings.ToLower(identifier), remainder)
	}

	return encodedDigest
}