add crypto pkg and DeriveKey func

This commit is contained in:
Andrea Franz 2018-09-27 11:26:21 +02:00
parent fa35b117ff
commit a2e6eec5b2
No known key found for this signature in database
GPG Key ID: 4F0D2F2D9DE7F29D
2 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package crypto
import (
"crypto/cipher"
"crypto/des"
)
var (
DerivationPurposeEnc = []byte{0x01, 0x82}
nullBytes8 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
)
func DeriveKey(cardKey []byte, seq []byte, purpose []byte) ([]byte, error) {
key24 := resizeKey24(cardKey)
derivation := make([]byte, 16)
copy(derivation, purpose[:2])
copy(derivation[2:], seq[:2])
block, err := des.NewTripleDESCipher(key24)
if err != nil {
return nil, err
}
ciphertext := make([]byte, 16)
mode := cipher.NewCBCEncrypter(block, nullBytes8)
mode.CryptBlocks(ciphertext, derivation)
return ciphertext, nil
}
func resizeKey24(key []byte) []byte {
data := make([]byte, 24)
copy(data, key[0:16])
copy(data[16:], key[0:8])
return data
}

View File

@ -0,0 +1,26 @@
package crypto
import (
"testing"
"github.com/status-im/status-go/smartcard/hexutils"
"github.com/stretchr/testify/assert"
)
func TestDeriveKey(t *testing.T) {
cardKey := hexutils.HexToBytes("404142434445464748494a4b4c4d4e4f")
seq := hexutils.HexToBytes("0065")
encKey, err := DeriveKey(cardKey, seq, DerivationPurposeEnc)
assert.NoError(t, err)
expectedEncKey := "85E72AAF47874218A202BF5EF891DD21"
assert.Equal(t, expectedEncKey, hexutils.BytesToHex(encKey))
}
func TestResizeKey24(t *testing.T) {
key := hexutils.HexToBytes("404142434445464748494a4b4c4d4e4f")
resized := resizeKey24(key)
expected := "404142434445464748494A4B4C4D4E4F4041424344454647"
assert.Equal(t, expected, hexutils.BytesToHex(resized))
}