File: util.go

package info (click to toggle)
golang-github-suapapa-go-eddystone 1.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 112 kB
  • sloc: makefile: 5
file content (87 lines) | stat: -rw-r--r-- 2,200 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
77
78
79
80
81
82
83
84
85
86
87
// Copyright (c) 2015-2020, go_eddystone authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package eddystone

import (
	"crypto/aes"
	"crypto/sha1"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"strings"

	"github.com/google/uuid"
)

// ConstructNSByTruncatedHashFQDN return 10 bytes namespace for UID frame
// by traucated hash of FQDN
func ConstructNSByTruncatedHashFQDN(fqdn string) []byte {
	h := sha1.New()
	h.Write([]byte(fqdn))
	bs := h.Sum(nil)
	return bs[:10]
}

// ConstructNSByElidedUUID return 10 bytes namespace for UID frame
// by elided version 4 UUID
func ConstructNSByElidedUUID(id uuid.UUID) []byte {
	idStr := id.String()
	idStr = strings.Replace(idStr, "-", "", -1)
	uuidBytes, _ := hex.DecodeString(idStr)
	return append(uuidBytes[:4], uuidBytes[10:]...)
}

// ComputeEIDValue returns 8 bytes EID value
// https://github.com/google/eddystone/blob/master/eddystone-eid/eid-computation.md
func ComputeEIDValue(identityKey []byte, ts uint32, k byte) (eid []byte, err error) {
	if len(identityKey) != 16 {
		return nil, fmt.Errorf("identityKey should be 16byte length for AES-128")
	}
	if 0 > k || k > 15 {
		return nil, fmt.Errorf("k should be between 0 and 15")
	}

	ts = ts & makeTsMask(k)

	tsBytes := make([]byte, 4)
	binary.BigEndian.PutUint32(tsBytes, ts)

	// computing the temporary key
	tmpKeySrc := make([]byte, 11)             // padding
	tmpKeySrc = append(tmpKeySrc, 0xFF)       // salt
	tmpKeySrc = append(tmpKeySrc, 0x00, 0x00) // padding
	tmpKeySrc = append(tmpKeySrc, tsBytes[0:0+2]...)

	tmpBlk, err := aes.NewCipher(identityKey)
	if err != nil {
		return nil, err
	}

	tmpKey := make([]byte, 16)
	tmpBlk.Encrypt(tmpKey, tmpKeySrc)

	// computing the EID value
	eidSrc := make([]byte, 11) // padding
	eidSrc = append(eidSrc, k) // rotation period exponent
	eidSrc = append(eidSrc, tsBytes...)

	eidBlk, err := aes.NewCipher(tmpKey)
	if err != nil {
		return nil, err
	}
	eid = make([]byte, 16)
	eidBlk.Encrypt(eid, eidSrc)

	return eid[:8], nil
}

func makeTsMask(k byte) uint32 {
	var tsMask uint32
	for i := byte(0); i < k; i++ {
		tsMask <<= 1
		tsMask |= 1
	}
	return ^tsMask
}