mirror of
https://github.com/status-im/keycard-go.git
synced 2025-02-20 23:58:13 +00:00
add VerifyCryptogram function
This commit is contained in:
parent
e81db1f0bd
commit
e40519c7da
@ -1,6 +1,7 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/cipher"
|
||||
"crypto/des"
|
||||
)
|
||||
@ -30,6 +31,35 @@ func DeriveKey(cardKey []byte, seq []byte, purpose []byte) ([]byte, error) {
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
func VerifyCryptogram(encKey, hostChallenge, cardChallenge, cardCryptogram []byte) (bool, error) {
|
||||
data := make([]byte, 0)
|
||||
data = append(data, hostChallenge...)
|
||||
data = append(data, cardChallenge...)
|
||||
paddedData := appendDESPadding(data)
|
||||
calculated, err := mac3des(encKey, paddedData, nullBytes8)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return bytes.Equal(calculated, cardCryptogram), nil
|
||||
}
|
||||
|
||||
func mac3des(key, data, iv []byte) ([]byte, error) {
|
||||
key24 := resizeKey24(key)
|
||||
|
||||
block, err := des.NewTripleDESCipher(key24)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ciphertext := make([]byte, 24)
|
||||
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
mode.CryptBlocks(ciphertext, data)
|
||||
|
||||
return ciphertext[16:], nil
|
||||
}
|
||||
|
||||
func resizeKey24(key []byte) []byte {
|
||||
data := make([]byte, 24)
|
||||
copy(data, key[0:16])
|
||||
|
@ -31,3 +31,24 @@ func TestAppendDESPadding(t *testing.T) {
|
||||
expected := "AABB800000000000"
|
||||
assert.Equal(t, expected, hexutils.BytesToHex(result))
|
||||
}
|
||||
|
||||
func TestVerifyCryptogram(t *testing.T) {
|
||||
encKey := hexutils.HexToBytes("16B5867FF50BE7239C2BF1245B83A362")
|
||||
hostChallenge := hexutils.HexToBytes("32da078d7aac1cff")
|
||||
cardChallenge := hexutils.HexToBytes("007284f64a7d6465")
|
||||
cardCryptogram := hexutils.HexToBytes("05c4bb8a86014e22")
|
||||
|
||||
result, err := VerifyCryptogram(encKey, hostChallenge, cardChallenge, cardCryptogram)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, result)
|
||||
}
|
||||
|
||||
func TestMac3des(t *testing.T) {
|
||||
key := hexutils.HexToBytes("16B5867FF50BE7239C2BF1245B83A362")
|
||||
data := hexutils.HexToBytes("32DA078D7AAC1CFF007284F64A7D64658000000000000000")
|
||||
result, err := mac3des(key, data, nullBytes8)
|
||||
assert.NoError(t, err)
|
||||
|
||||
expected := "05C4BB8A86014E22"
|
||||
assert.Equal(t, expected, hexutils.BytesToHex(result))
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user