Skip to content

Commit

Permalink
Generate 64 character hexadecimal labels
Browse files Browse the repository at this point in the history
  • Loading branch information
Duncan Jones committed Mar 7, 2019
1 parent 529d2c9 commit ac626bf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
13 changes: 7 additions & 6 deletions common.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package crypto11
import (
"C"
"encoding/asn1"
"encoding/base64"
"encoding/hex"
"errors"
"math/big"
"unsafe"

pkcs11 "github.com/miekg/pkcs11"
"github.com/miekg/pkcs11"
)

// ErrMalformedDER represents a failure to decode an ASN.1-encoded message
Expand All @@ -19,6 +19,8 @@ var ErrMalformedDER = errors.New("crypto11: malformed DER message")
// string.
var ErrMalformedSignature = errors.New("crypto11xo: malformed signature")

const labelLength = 64

func ulongToBytes(n uint) []byte {
return C.GoBytes(unsafe.Pointer(&n), C.sizeof_ulong) // ugh!
}
Expand Down Expand Up @@ -98,8 +100,7 @@ func dsaGeneric(slot uint, key pkcs11.ObjectHandle, mechanism uint, digest []byt

// Pick a random label for a key
func generateKeyLabel() ([]byte, error) {
const labelSize = 32
rawLabel := make([]byte, labelSize)
rawLabel := make([]byte, labelLength / 2)
var rand PKCS11RandReader
sz, err := rand.Read(rawLabel)
if err != nil {
Expand All @@ -108,7 +109,7 @@ func generateKeyLabel() ([]byte, error) {
if sz < len(rawLabel) {
return nil, ErrCannotGetRandomData
}
label := make([]byte, 2*labelSize)
base64.URLEncoding.Encode(label, rawLabel)
label := make([]byte, labelLength)
hex.Encode(label, rawLabel)
return label, nil
}
20 changes: 20 additions & 0 deletions common_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package crypto11

import (
"github.com/stretchr/testify/require"
"testing"
)

func TestGenerateKeyLabel(t *testing.T) {
_, err := ConfigureFromFile("config")
require.NoError(t, err)

for i :=0; i < 100; i++ {
label, err := generateKeyLabel()
require.NoError(t, err)
require.Len(t, label, labelLength)
for _, b := range label {
require.NotEqual(t, byte(0), b)
}
}
}

0 comments on commit ac626bf

Please sign in to comment.