← history for internal/encoding/encoding.go
61186530internal/encoding/encoding.go48 lines⬡ raw↓ 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
/**
 * RemoteBrain - rbrain
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Paolo Lulli <kevwe.com>
 * @copyright Paolo Lulli 2026
 */

package encoding

import (
    "crypto/rand"
    "crypto/sha1"
    "encoding/base64"
    "encoding/hex"
    "fmt"
    "io"
)

func NewUUID() string {
    var b [16]byte
    if _, err := io.ReadFull(rand.Reader, b[:]); err != nil {
        panic(err)
    }
    b[6] = (b[6] & 0x0f) | 0x40 // version 4
    b[8] = (b[8] & 0x3f) | 0x80 // variant RFC 4122
    return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
        b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}

func HashSHA1(s string) string {
    h := sha1.Sum([]byte(s))
    return hex.EncodeToString(h[:])
}

func EncodeB64(s string) string {
    return base64.StdEncoding.EncodeToString([]byte(s))
}

func DecodeB64(s string) string {
    b, err := base64.StdEncoding.DecodeString(s)
    if err != nil {
        return "[decode error]"
    }
    return string(b)
}