mirror of
https://github.com/status-im/keycard-go.git
synced 2025-02-21 08:08:07 +00:00
add crypto pkg and DeriveKey func
This commit is contained in:
parent
fa35b117ff
commit
a2e6eec5b2
39
globalplatform/crypto/crypto.go
Normal file
39
globalplatform/crypto/crypto.go
Normal 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
|
||||
}
|
26
globalplatform/crypto/crypto_test.go
Normal file
26
globalplatform/crypto/crypto_test.go
Normal 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))
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user