borepin/NFC_Test/AuthCrypto_Test.cs
2020-10-01 19:06:09 +02:00

130 lines
3.4 KiB
C#

using NFC;
using NFC.Crypto;
using NFC.Mifare_DESFire;
using NSubstitute;
using NUnit.Framework;
using PCSC.Iso7816;
using System;
using System.Collections.Generic;
using System.Text;
namespace NFC_Test
{
public class AuthCrypto_Test
{
public byte[] GenerateDefaultKey(int size)
{
List<byte> key = new List<byte>();
for (int i = 0; i < size; i++)
{
key.Add(0);
}
return key.ToArray();
}
[Test]
// https://www.linkedin.com/pulse/mifare-desfire-introduction-david-coelho
public void AuthExample()
{
DES des = new DES();
byte[] challenge = new byte[]
{
0x93 ,0x9d ,0x2c ,0x2e ,0xa1 ,0x65 ,0x75 ,0xd5
};
byte[] key = GenerateDefaultKey(8);
byte[] iv = GenerateDefaultKey(8);
byte[] rndA = new byte[]
{
0x00 ,0x01 ,0x02 ,0x03 ,0x04 ,0x05 ,0x06 ,0x07
};
byte[] rndB = des.Decrypt(challenge, key, iv);
byte[] rndB_expected = new byte[]
{
0xea ,0x48 ,0x50 ,0x13 ,0xd8 ,0x0a ,0x05 ,0x67
};
Assert.AreEqual(rndB_expected, rndB);
}
[Test]
public void concatenate()
{
MifareDESFire mifareDESFire = new MifareDESFire(null);
byte[] rndA = new byte[]
{
0x00 ,0x01 ,0x02 ,0x03 ,0x04 ,0x05 ,0x06 ,0x07
};
byte[] rndB = new byte[]
{
0x48 ,0x50 ,0x13 ,0xd8 ,0x0a ,0x05 ,0x67 ,0xea
};
byte[] rndA_rndB_expected = new byte[]
{
0x00 ,0x01 ,0x02 ,0x03 ,0x04 ,0x05 ,0x06 ,0x07, 0x48 ,0x50 ,0x13 ,0xd8 ,0x0a ,0x05 ,0x67 ,0xea
};
byte[] rndA_rndB = mifareDESFire.concatenate(rndA, rndB);
Assert.AreEqual(rndA_rndB_expected, rndA_rndB);
}
[Test]
public void Auth()
{
APDUCommand cmd_getchallange = new APDUCommand(IsoCase.Case4Short)
{
CLA = 0x90,
INS = (byte)0x1A,
Data = new byte[]
{
0x00
}
};
APDUCommand cmd_answerchallange = new APDUCommand(IsoCase.Case4Short)
{
CLA = 0x90,
INS = (byte)0xAF,
Data = new byte[]
{
0x69, 0x17, 0x8b, 0x93, 0x8c, 0x03, 0xed, 0xf1, 0x86, 0xd3, 0x05, 0x6b, 0xed, 0xc8, 0xd6, 0xcf
}
};
APDUResponse response = new APDUResponse()
{
Body = new byte[]
{
0xB8, 0x90, 0x04, 0x7F, 0x2D, 0xC8, 0xD6, 0x8B
}
};
APDUResponse response2 = new APDUResponse()
{
Body = new byte[]
{
0x04, 0x79, 0xed, 0x6c, 0x4f, 0x74, 0xda, 0x4a
}
};
ICard card = Substitute.For<ICard>();
card.Transmit(cmd_getchallange).ReturnsForAnyArgs(response);
card.Transmit(cmd_answerchallange).Returns(response2);
MifareDESFire mifareDESFire = new MifareDESFire(card);
mifareDESFire.Authenticate(0x00, mifareDESFire.GenerateDefaultKey(16));
}
}
}