CSharp · Console
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Org.BouncyCastle.Utilities;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using Org.BouncyCastle.Security;
public class Program
{
private readonly byte[] keyMAC;
private readonly byte[] keyENC;
private const byte PAD = 0x80;
public static void Main()
{
/*
Key: K_MAC : b5 fe b9 48 8f 17 be 03 e5 4c 7d 80 90 7e 8a 1f
Key: K_Enc : 3d 71 55 f3 79 1c 31 3c 29 24 f5 1a e6 0f 1a c9
*/
string Kenc = "3d7155f3791c313c2924f51ae60f1ac9";
string Kmac = "b5feb9488f17be03e54c7d80907e8a1f";
/* PlatinumReader Log :
APDU: SMRequest -
0c a4 02 0c 1d 87 11 01 1b 33 6a d5 1e e0 5a 7f
a6 9e 60 b8 17 27 8f b6 8e 08 5d 9c ad 57 4b 49
40 5d 00
APDU: SMResponse - 0000000000000000000000000000000A
99 02 90 00 8e 08 b2 ac b1 8b 3e 11 0c 5c 90 00
APDU: Response
90 00
*/
string scc = "0000000000000000000000000000000A";
string responseSM1 = "990290008e08b2acb18b3e110c5c9000";
string apduResonse = decryptAPDU(responseSM1, Kenc, Kmac, scc);
Console.WriteLine(" Expected APDU Response: 9000. Decrypted APDU Response: " + apduResonse);
/* PlatinumReader Log :
APDU: SMRequest -
0c b0 00 00 0d 97 01 05 8e 08 8e 56 63 f9 66 f0 3c 05 00
APDU: SMResponse - 0000000000000000000000000000000C
87 11 01 9d bc 10 6d af 0f d4 f5 ce a5 8f 51 09
15 3f 84 99 02 90 00 8e 08 bc 40 d8 ff e8 2c cb
70 90 00
APDU: Response :
6e 60 31 5e 30 90 00
*/
scc = "0000000000000000000000000000000C";
responseSM1 = "8711019dbc106daf0fd4f5cea58f5109153f84990290008e08bc40d8ffe82ccb709000";
apduResonse = decryptAPDU(responseSM1, Kenc, Kmac, scc);
Console.WriteLine(" Expected APDU Response : 6e60315e309000. Decrypted APDU Response: " + apduResonse);
}
public static string decryptAPDU(string apdu, string keyEnc, string keyMac, string scc)
{
string dechipherApdu = "";
byte[] apduBytes = StringUtils.ToByteArray(apdu);
byte[] KeyENC = StringUtils.ToByteArray(keyEnc);
byte[] KeyMAC = StringUtils.ToByteArray(keyMac);
SecureMessaging sm = new SecureMessaging(KeyMAC, KeyENC);
dechipherApdu = byteToHexStr(sm.decrypt(apduBytes, StringUtils.ToByteArray(scc)));
return dechipherApdu;
}
private CMac getCMAC(byte[] smssc)
{
CMac cmac = new CMac(new AesEngine());
cmac.Init(new KeyParameter(keyMAC));
cmac.BlockUpdate(smssc, 0, smssc.Length);
return cmac;
}
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
private byte[] pad(byte[] data, int blockSize)
{
byte[] result = new byte[data.Length + (blockSize - data.Length % blockSize)];
Array.Copy(data, 0, result, 0, data.Length);
result[data.Length] = PAD;
return result;
}
public byte[] decrypt(byte[] response, byte[] secureMessagingSSC)
{
using (MemoryStream bais = new MemoryStream(response))
using (MemoryStream baos = new MemoryStream(response.Length - 10))
{
byte[] statusBytes = new byte[2];
byte[] dataObject = null;
byte[] macObject = new byte[8];
byte tag = (byte)bais.ReadByte();
if (tag == 0x87)
{
int size = bais.ReadByte();
if (size > 0x80)
{
byte[] sizeBytes = new byte[size & 0x0F];
bais.Read(sizeBytes, 0, sizeBytes.Length);
size = new BigInteger(1, sizeBytes).IntValue;
}
bais.Seek(1, SeekOrigin.Current); // Skip encryption header
dataObject = new byte[size - 1];
bais.Read(dataObject, 0, dataObject.Length);
tag = (byte)bais.ReadByte();
}
if (tag == 0x99)
{
if (bais.ReadByte() == 0x02)
{
bais.Read(statusBytes, 0, 2);
tag = (byte)bais.ReadByte();
}
}
else
{
throw new IOException("Malformed Secure Messaging APDU");
}
if (tag == 0x8E)
{
if (bais.ReadByte() == 0x08)
{
bais.Read(macObject, 0, 8);
}
}
else
{
throw new IOException("Malformed Secure Messaging APDU");
}
// Only 2 bytes status should remain
if (bais.Length - bais.Position != 2)
{
throw new IOException("Malformed Secure Messaging APDU");
}
Org.BouncyCastle.Crypto.Macs.CMac cmac = getCMAC(secureMessagingSSC);
byte[] mac = new byte[16];
using (MemoryStream macData = new MemoryStream())
{
if (dataObject != null)
{
TLV paddedDataObject = new TLV();
paddedDataObject.SetTagNumWithClass(0x87);
paddedDataObject.SetValue(ByteUtils.Concatenate(new byte[] { 0x01 }, dataObject));
macData.Write(paddedDataObject.ToBER(), 0, paddedDataObject.ToBER().Length);
}
TLV statusBytesObject = new TLV();
statusBytesObject.SetTagNumWithClass(0x99);
statusBytesObject.SetValue(statusBytes);
macData.Write(statusBytesObject.ToBER(), 0, statusBytesObject.ToBER().Length);
byte[] paddedData = pad(macData.ToArray(), 16);
cmac.BlockUpdate(paddedData, 0, paddedData.Length);
cmac.DoFinal(mac, 0);
mac = ByteUtils.Copy(mac, 0, 8);
}
/*
if (!ByteUtils.Compare(mac, macObject))
{
throw new GeneralSecurityException("Secure Messaging MAC verification failed");
}
if (dataObject != null)
{
AesManaged c = GetCipher(secureMessagingSSC, CipherMode.CBC);
try
{
byte[] data_decrypted = c.DoFinal(dataObject);
baos.Write(Unpad(data_decrypted), 0, Unpad(data_decrypted).Length);
}
finally
{
// Assurez-vous de libérer les ressources en appelant Dispose() une fois terminé.
c.Dispose();
}
}*/
baos.Write(statusBytes, 0, statusBytes.Length);
return baos.ToArray();
}
}
public class TLV
{
private TagLengthValue tag;
private TLV next = null;
private TLV child = null;
public TLV()
{
tag = new TagLengthValue();
}
public TLV(TLV obj)
{
this.tag = obj.tag;
this.next = (obj.next != null) ? new TLV(obj.next) : null;
this.child = (obj.child != null) ? new TLV(obj.child) : null;
}
public Tag GetTag()
{
return this.tag.GetTag();
}
public void SetTag(Tag tag)
{
this.tag.SetTag(tag);
}
public TagClass GetTagClass()
{
return tag.GetTagClass();
}
public void SetTagClass(TagClass tagClass)
{
tag.SetTagClass(tagClass);
}
public bool IsPrimitive()
{
return tag.IsPrimitive();
}
public void SetPrimitive(bool primitive)
{
tag.SetPrimitive(primitive);
}
public long GetTagNum()
{
return tag.GetTagNum();
}
public void SetTagNum(byte tagNum)
{
SetTagNum(tagNum & 0xFF);
}
public void SetTagNum(long tagNum)
{
tag.SetTagNum(tagNum);
}
public long GetTagNumWithClass()
{
return tag.GetTagNumWithClass();
}
public void SetTagNumWithClass(byte tagNumWithClass)
{
SetTagNumWithClass(tagNumWithClass & 0xFF);
}
public void SetTagNumWithClass(long tagNumWithClass)
{
tag.SetTagNumWithClass(tagNumWithClass);
}
public void SetTagNumWithClass(byte[] tagNumWithClass)
{
tag.SetTagNumWithClass(tagNumWithClass);
}
public int GetValueLength()
{
return tag.GetValueLength();
}
public byte[] GetValue()
{
return tag.GetValue();
}
public void SetValue(byte[] value)
{
tag.SetValue(value);
}
public void AddToEnd(TLV sibling)
{
if (next == null)
{
next = sibling;
}
else
{
next.AddToEnd(sibling);
}
}
public TLV Remove(int n)
{
if (n == 0)
{
TLV tmp = next;
next = null;
return tmp;
}
else if (n > 0 && next != null)
{
return next.Remove(n - 1);
}
else
{
return null;
}
}
public TLV RemoveNext()
{
return Remove(0);
}
public void SetChild(TLV child)
{
this.child = child;
}
public bool HasChild()
{
return child != null;
}
public TLV GetChild()
{
return child;
}
public bool HasNext()
{
return next != null;
}
public TLV GetNext()
{
return next;
}
public List<TLV> AsList()
{
LinkedList<TLV> result = new LinkedList<TLV>();
TLV nextTag = this;
while (nextTag != null)
{
TLV toAdd = new TLV(nextTag);
toAdd.next = null;
result.AddLast(toAdd);
nextTag = nextTag.next;
}
return result.ToList();
}
public List<TLV> FindNextTags(long num)
{
List<TLV> all = AsList();
LinkedList<TLV> result = new LinkedList<TLV>();
foreach (TLV nextTLV in all)
{
if (nextTLV.GetTagNumWithClass() == num)
{
result.AddLast(nextTLV);
}
}
return result.ToList();
}
public List<TLV> FindChildTags(long num)
{
if (HasChild())
{
return GetChild().FindNextTags(num);
}
else
{
return new List<TLV>();
}
}
public static TLV FromBER(byte[] input)
{
byte[] rest = input;
TLV first = new TLV();
bool isFirst = true;
TLV last = first;
while (rest.Length > 0)
{
TLV next;
if (isFirst)
{
next = first;
}
else
{
next = new TLV();
}
if (rest[0] == 0)
{
return first;
}
next.tag = TagLengthValue.FromBER(rest);
if (!next.tag.IsPrimitive() && next.tag.GetValueLength() > 0)
{
next.child = FromBER(next.tag.GetValue());
}
if (isFirst)
{
isFirst = false;
}
else
{
last.next = next;
}
last = next;
rest = last.tag.ExtractRest(rest);
}
return first;
}
public byte[] ToBER()
{
return ToBER(false);
}
public byte[] ToBER(bool withSuccessors)
{
try
{
using (MemoryStream outStream = new MemoryStream())
{
ToBER(outStream, withSuccessors);
return outStream.ToArray();
}
}
catch (IOException ex)
{
throw new Exception("IOException: " + ex.Message);
}
}
private void ToBER(MemoryStream outStream, bool withSuccessors)
{
if (child != null)
{
byte[] childBytes = child.ToBER(true);
tag.SetPrimitive(false);
tag.SetValue(childBytes);
}
else
{
tag.SetPrimitive(true);
}
outStream.Write(tag.ToBER(), 0, tag.ToBER().Length);
if (withSuccessors && next != null)
{
next.ToBER(outStream, withSuccessors);
}
}
public override string ToString()
{
return ToString("");
}
public string ToString(string prefix)
{
string result = prefix + String.Format("{0:X2}", GetTagNumWithClass());
if (!HasChild())
{
result += " " + tag.GetValueLength() + " " + BitConverter.ToString(tag.GetValue()).Replace("-", "");
}
else
{
result += "\n" + GetChild().ToString(prefix + " ");
}
if (HasNext())
{
result += "\n" + GetNext().ToString(prefix);
}
return result;
}
}
public class TagLengthValue
{
private int numOctets;
private Tag tag;
private byte[] value;
public TagLengthValue(int numOctets, Tag tag, byte[] value)
{
this.numOctets = numOctets;
this.tag = tag;
this.value = value;
}
public TagLengthValue(int numOctets, TagClass tagClass, bool primitive, long tagNum, byte[] value)
{
// this(numOctets, new Tag(tagClass, primitive, tagNum), value);
this.numOctets = numOctets;
tag = new Tag(tagClass, primitive, tagNum);
this.value = value;
}
public TagLengthValue(Tag tag, byte[] value)
{
// this(0, tag, value);
this.numOctets = 0;
this.tag = tag;
this.value = value;
}
public TagLengthValue(TagClass tagClass, bool primitive, long tagNum, byte[] value)
{
// this(0, tagClass, primitive, tagNum, value);
this.numOctets = 0;
tag = new Tag(tagClass, primitive, tagNum);
this.value = value;
}
public TagLengthValue()
{
// this(0, new Tag(), new byte[] { });
this.numOctets = 0;
this.tag = new Tag();
this.value = new byte[] { };
}
public Tag GetTag()
{
return new Tag(this.tag);
}
public void SetTag(Tag tag)
{
this.tag = new Tag(tag);
}
public TagClass GetTagClass()
{
return this.tag.GetTagClass();
}
public void SetTagClass(TagClass tagClass)
{
this.tag.SetTagClass(tagClass);
}
public bool IsPrimitive()
{
return this.tag.IsPrimitive();
}
public void SetPrimitive(bool primitive)
{
this.tag.SetPrimitive(primitive);
}
public long GetTagNum()
{
return this.tag.GetTagNum();
}
public void SetTagNum(long tagNum)
{
this.tag.SetTagNum(tagNum);
}
public long GetTagNumWithClass()
{
return this.tag.GetTagNumWithClass();
}
public void SetTagNumWithClass(long tagNumWithClass)
{
this.tag.SetTagNumWithClass(tagNumWithClass);
}
public void SetTagNumWithClass(byte[] tagNumWithClass)
{
this.tag = Tag.FromBER(tagNumWithClass);
}
public int GetValueLength()
{
return this.value.Length;
}
public byte[] GetValue()
{
return this.value;
}
public void SetValue(byte[] value)
{
this.value = value;
}
/**
* Obtient le nombre d'octets à partir desquels ce TLV a été créé.<br>
* N'a de sens que s'il a été créé à partir d'octets.
* @return
*/
int GetRawLength()
{
return this.numOctets;
}
public byte[] ExtractRest(byte[] inputWithThisTag)
{
try
{
int from = GetRawLength();
int to = inputWithThisTag.Length;
return Arrays.CopyOfRange(inputWithThisTag, from, to);
}
catch (Exception ex) when (ex is IndexOutOfRangeException || ex is ArgumentException)
{
throw new TLVException("Data length and claimed length do not match.", ex);
}
}
public static TagLengthValue FromBER(byte[] data)
{
Tag tag = Tag.FromBER(data);
int numOctets = tag.numOctets;
int dataLength = 0;
bool endOfLine = false;
if (((data[numOctets] >> 7) & 0x01) == 0)
{
dataLength = data[numOctets];
numOctets++;
}
else
{
if ((data[numOctets] & 0x7F) == 0x00)
{
endOfLine = true;
numOctets++;
int i = 0;
bool endFound = false;
bool zeroFound = false;
do
{
if (data.Length <= numOctets + i)
{
throw new TLVException("Not enough bytes in input to read TLV length.");
}
byte next = data[numOctets + i];
if (next == 0x00)
{
if (zeroFound)
{
endFound = true;
}
else
{
zeroFound = true;
}
}
else
{
zeroFound = false;
}
i++;
} while (!endFound);
dataLength = i - 2;
}
else
{
int numLengthBytes = data[numOctets] & 0x7F;
numOctets++;
int i = 0;
while (i < numLengthBytes)
{
if (i * 8 > 32)
{
throw new TLVException("Length doesn't fit into a 32 bit word.");
}
else if (data.Length < numOctets + i + 1)
{
throw new TLVException("Not enough bytes in input to read TLV length.");
}
if (data[numOctets + i] < 0)
{
dataLength = (dataLength << 8) | (256 + data[numOctets + i]);
}
else
{
dataLength = (dataLength << 8) | data[numOctets + i];
}
i++;
}
numOctets += i;
}
}
byte[] dataField = Arrays.CopyOfRange(data, numOctets, numOctets + dataLength);
numOctets = numOctets + dataLength;
if (endOfLine)
{
numOctets += 2;
}
TagLengthValue result = new TagLengthValue(numOctets, tag, dataField);
return result;
}
public byte[] ToBER()
{
try
{
using (MemoryStream outStream = new MemoryStream())
{
byte[] tagBytes = tag.ToBER();
outStream.Write(tagBytes, 0, tagBytes.Length);
int len = GetValueLength();
if (len <= 127)
{
outStream.WriteByte((byte)len);
}
else
{
byte[] lenBytes = BitConverter.GetBytes(len);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(lenBytes);
}
byte lenHeader = (byte)(0x80 | lenBytes.Length);
outStream.WriteByte(lenHeader);
outStream.Write(lenBytes, 0, lenBytes.Length);
}
outStream.Write(GetValue(), 0, GetValue().Length);
return outStream.ToArray();
}
}
catch (IOException ex)
{
throw new Exception("An error occurred while writing to the stream.", ex);
}
}
}
public static class ByteUtils
{
/**
* Cloner un tableau d'octets.
*
* @param input le tableau d'octets à cloner
* @return un nouveau tableau d'octets, ou null si l'entrée est null
*/
public static byte[] Clone(byte[] input)
{
if (input == null)
{
return null;
}
byte[] ret = new byte[input.Length];
Array.Copy(input, 0, ret, 0, input.Length);
return ret;
}
/**
* Concaténer deux tableaux d'octets.
*
* @param x tableau d'octets
* @param y tableau d'octets
* @return x || y
*/
public static byte[] Concatenate(byte[] x, byte[] y)
{
if (x == null)
{
return y;
}
if (y == null)
{
return x;
}
byte[] ret = new byte[x.Length + y.Length];
Array.Copy(x, 0, ret, 0, x.Length);
Array.Copy(y, 0, ret, x.Length, y.Length);
return ret;
}
/**
* Concaténer un tableau d'octets avec un octet.
*
* @param x octet
* @param y tableau d'octets
* @return x || y
*/
public static byte[] Concatenate(byte x, byte[] y)
{
return Concatenate(new byte[] { x }, y);
}
/**
* Concaténer un tableau d'octets avec un octet.
*
* @param x tableau d'octets
* @param y octet
* @return x || y
*/
public static byte[] Concatenate(byte[] x, byte y)
{
return Concatenate(x, new byte[] { y });
}
/**
* Concaténer deux octets.
*
* @param x octet
* @param y octet
* @return x || y
*/
public static byte[] Concatenate(byte x, byte y)
{
return Concatenate(new byte[] { x }, new byte[] { y });
}
/**
* Convertit un tableau d'octets en entier long.
* La taille du tableau d'octets doit être comprise entre 1 et 8. L'ordre des octets en entrée est déterminé par le paramètre correspondant.
*
* @param bytes Tableau d'octets à convertir.
* @param bigEndian {@code true} si l'entrée doit être traitée en Big Endian, {@code false} pour Little Endian.
* @return long
*/
public static long ToLong(byte[] bytes, bool bigEndian)
{
if (bytes.Length > 8 || bytes.Length < 1)
{
throw new ArgumentException("La taille du tableau d'octets doit être comprise entre 1 et 8.");
}
long result = 0;
if (bigEndian)
{
for (int i = 0; i < bytes.Length; i++)
{
result |= ((long)0xFF & bytes[bytes.Length - 1 - i]) << i * 8;
}
}
else
{
for (int i = 0; i < bytes.Length; i++)
{
result |= ((long)0xFF & bytes[i]) << i * 8;
}
}
return result;
}
/**
* Convertit un tableau d'octets en entier long.
* La taille du tableau d'octets doit être comprise entre 1 et 8. L'entrée est traitée en Big Endian.
*
* @param bytes Tableau d'octets à convertir.
* @return long
*/
public static long ToLong(byte[] bytes)
{
return ToLong(bytes, true);
}
/**
* Copie d'une plage de données.
*
* @param input les données d'entrée
* @param offset l'indice de départ de la copie
* @param length la longueur de la copie
* @return le tableau de bytes copié
*/
public static byte[] Copy(byte[] input, int offset, int length)
{
if (input == null)
{
return null;
}
byte[] tmp = new byte[length];
Array.Copy(input, offset, tmp, 0, length);
return tmp;
}
/**
* Convertit un tableau d'octets en une chaîne hexadécimale.
*
* @param bytes Entrée
* @param formatted Si vrai, la chaîne est formatée en présentation 0xXX
* @return Chaîne hexadécimale
*/
public static string ToHexString(byte[] bytes, bool formatted)
{
return ToHexString(bytes, formatted, false);
}
/**
* Convertit un tableau d'octets en une chaîne hexadécimale.
*
* @param bytes Entrée
* @param formatted Si vrai, la chaîne est formatée en présentation 0xXX
* @param addLinebreak Si vrai, la chaîne est formatée avec 16 valeurs par ligne
* @return Chaîne hexadécimale
*/
public static string ToHexString(byte[] bytes, bool formatted, bool addLinebreak)
{
if (formatted)
{
return ToHexString(bytes, "0x%02X ", addLinebreak);
}
else
{
return ToHexString(bytes, "%02X", addLinebreak);
}
}
private static string ToHexString(byte[] bytes, string format, bool addLinebreak)
{
if (bytes == null)
{
return null;
}
StringBuilder builder = new StringBuilder(bytes.Length * 2);
for (int i = 1; i <= bytes.Length; i++)
{
builder.AppendFormat(format, bytes[i - 1]);
if (addLinebreak && i % 16 == 0)
{
builder.AppendLine();
}
}
return builder.ToString();
}
public static bool Compare(byte[] x, byte[] y)
{
if (y == null || x == null)
{
return false;
}
if (x.Length != y.Length)
{
return false;
}
return ByteUtils.AreEqual(x, y);
}
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static bool AreEqual(byte[] x, byte[] y)
{
if (x.Length != y.Length)
{
return false;
}
for (int i = 0; i < x.Length; i++)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
}
public class Tag
{
public static readonly Tag BOOLEAN_TAG = new Tag(TagClass.UNIVERSAL, true, 1);
public static readonly Tag INTEGER_TAG = new Tag(TagClass.UNIVERSAL, true, 2);
public static readonly Tag BITSTRING_TAG = new Tag(TagClass.UNIVERSAL, true, 3);
public static readonly Tag OCTETSTRING_TAG = new Tag(TagClass.UNIVERSAL, true, 4);
public static readonly Tag NULL_TAG = new Tag(TagClass.UNIVERSAL, true, 5);
public static readonly Tag OID_TAG = new Tag(TagClass.UNIVERSAL, true, 6);
public static readonly Tag REAL_TAG = new Tag(TagClass.UNIVERSAL, true, 9);
public static readonly Tag ENUMERATED_TAG = new Tag(TagClass.UNIVERSAL, true, 10);
public static readonly Tag EMBEDDED_PDV_TAG = new Tag(TagClass.UNIVERSAL, false, 11);
public static readonly Tag RELATIVE_OID_TAG = new Tag(TagClass.UNIVERSAL, true, 13);
public static readonly Tag SEQUENCE_TAG = new Tag(TagClass.UNIVERSAL, false, 16);
public static readonly Tag SET_TAG = new Tag(TagClass.UNIVERSAL, false, 17);
private TagClass tagClass;
private bool primitive;
private long tagNum;
private long tagNumWithClass;
public int numOctets = 0;
public Tag()
{
this.tagClass = TagClass.UNIVERSAL;
this.primitive = true;
this.tagNum = 0;
CalculateTagNumWithClass();
}
public Tag(Tag tag)
{
this.tagClass = tag.tagClass;
this.primitive = tag.primitive;
this.tagNum = tag.tagNum;
CalculateTagNumWithClass();
}
public Tag(TagClass tagClass, bool primitive, long tagNum)
{
this.tagClass = tagClass;
this.primitive = primitive;
this.tagNum = tagNum;
CalculateTagNumWithClass();
}
public TagClass GetTagClass()
{
return this.tagClass;
}
public void SetTagClass(TagClass tagClass)
{
this.tagClass = tagClass;
CalculateTagNumWithClass();
}
public bool IsPrimitive()
{
return this.primitive;
}
public void SetPrimitive(bool primitive)
{
this.primitive = primitive;
CalculateTagNumWithClass();
}
public long GetTagNum()
{
return this.tagNum;
}
public void SetTagNum(long tagNum)
{
this.tagNum = tagNum;
CalculateTagNumWithClass();
}
public long GetTagNumWithClass()
{
return this.tagNumWithClass;
}
public void SetTagNumWithClass(long tagNumWithClass)
{
Tag newTag = Tag.FromBER(LongUtils.ToByteArray(tagNumWithClass));
this.tagClass = newTag.tagClass;
this.primitive = newTag.primitive;
this.tagNum = newTag.tagNum;
this.tagNumWithClass = tagNumWithClass;
}
private void CalculateTagNumWithClass()
{
byte leading = (byte)tagClass;
leading = (byte)((leading << 1) | ((this.primitive) ? 0 : 1));
byte[] rest;
if (this.tagNum >= 31)
{
leading = (byte)((leading << 5) | 0x1F);
rest = LongUtils.ToByteArray(this.tagNum, 7);
for (int i = 0; i < rest.Length - 1; i++)
{
rest[i] |= 0x80;
}
}
else
{
leading = (byte)((leading << 5) | (byte)this.tagNum);
rest = new byte[0];
}
byte[] resultBytes = ByteUtils.Concatenate(leading, rest);
this.tagNumWithClass = ByteUtils.ToLong(resultBytes);
}
public static Tag FromBER(byte[] data)
{
int numOctets = 1;
TagClass tagClass = (TagClass)data[0];
bool primitive = ((data[0] >> 5) & 0x01) == 0x00;
long tagNum = 0;
byte tmpTagNum = (byte)(data[0] & 0x1F);
if (tmpTagNum <= 30)
{
tagNum = tmpTagNum;
}
else
{
byte next;
do
{
if (numOctets * 7 > 64)
{
throw new TLVException("Tag number doesn't fit into a 64 bit word.");
}
else if (data.Length < numOctets)
{
throw new TLVException("Not enough bytes in input bytes to build TLV tag.");
}
next = data[numOctets];
numOctets++;
byte nextValue = (byte)(next & 0x7F);
tagNum = (tagNum << 7) | nextValue;
} while (((next >> 7) & 0x01) == 0x01);
}
Tag resultTag = new Tag(tagClass, primitive, tagNum);
resultTag.numOctets = numOctets;
return resultTag;
}
public byte[] ToBER()
{
return LongUtils.ToByteArray(tagNumWithClass);
}
public override string ToString()
{
return "[" + tagClass.ToString() + " " +
(primitive ? "prim " : "cons ") +
tagNum + " (0x" + tagNumWithClass.ToString("X") + ")]";
}
public override bool Equals(object obj)
{
if (obj is Tag)
{
Tag other = (Tag)obj;
return this.GetTagNumWithClass() == other.GetTagNumWithClass();
}
else
{
return false;
}
}
public override int GetHashCode()
{
int hash = 7;
hash = 79 * hash + (int)(this.tagNumWithClass ^ (this.tagNumWithClass >> 32));
return hash;
}
}
public enum TagClass
{
UNIVERSAL = 0,
APPLICATION = 1,
CONTEXT = 2,
PRIVATE = 3
}
public class TLVException : Exception
{
public TLVException(string message) : base(message)
{
}
public TLVException(string message, Exception innerException) : base(message, innerException)
{
}
}
public class LongUtils
{
public static byte[] ToByteArray(long value)
{
return ToByteArray(value, 8);
}
public static byte[] ToByteArray(long value, int numBits)
{
return ToByteArray(value, numBits, true);
}
public static byte[] ToByteArray(long value, int numBits, bool bigEndian)
{
if (numBits <= 0 || numBits > 8)
{
throw new ArgumentException("Numbits must be between 0 and 8.");
}
if (value == 0)
{
return new byte[1];
}
byte[] buffer = null;
int numBytesInBuffer = 64 / numBits;
int restBits = 64 - (numBytesInBuffer * numBits);
int j = 0;
for (int i = numBytesInBuffer - ((restBits > 0) ? 0 : 1); i >= 0; i--)
{
byte b;
if (i == numBytesInBuffer)
{
byte mask = NumBitsToMask((byte)restBits);
b = (byte)((byte)(value >> (((i - 1) * numBits) + restBits)) & mask);
}
else
{
byte mask = NumBitsToMask((byte)numBits);
b = (byte)((value >> (i * numBits)) & mask);
}
if (buffer == null && b != 0)
{
buffer = new byte[i + 1];
}
else if (buffer == null)
{
continue;
}
buffer[j] = b;
j++;
}
if (!bigEndian)
{
Array.Reverse(buffer);
}
return buffer;
}
private static byte NumBitsToMask(byte numBits)
{
byte result = 0;
for (byte i = 0; i < numBits; i++)
{
result = (byte)((result << 1) | 1);
}
return result;
}
public static byte[] ToByteArray(long value, bool padArrayToTypeLength)
{
return ToByteArray(value, padArrayToTypeLength, true);
}
public static byte[] ToByteArray(long value, bool padArrayToTypeLength, bool bigEndian)
{
byte[] result = ToByteArray(value, 8, bigEndian);
if (padArrayToTypeLength && result.Length < 8)
{
byte[] padding = new byte[8 - result.Length];
result = Concatenate(padding, result);
}
return result;
}
private static byte[] Concatenate(byte[] array1, byte[] array2)
{
byte[] result = new byte[array1.Length + array2.Length];
Array.Copy(array1, 0, result, 0, array1.Length);
Array.Copy(array2, 0, result, array1.Length, array2.Length);
return result;
}
}
public class StringUtils
{
private static readonly Regex WS_PATTERN = new Regex("\\s");
/**
* Convertit une chaîne hexadécimale en tableau d'octets.
*
* @param hex Chaîne hexadécimale
* @return Tableau d'octets
* @throws FormatException Lancée si la chaîne hexadécimale contient des caractères invalides.
*/
public static byte[] ToByteArray(string hex)
{
if ((hex.Length % 2) != 0)
{
hex = "0" + hex;
}
byte[] ret = new byte[hex.Length / 2];
for (int i = 0; i < ret.Length; i++)
{
ret[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return ret;
}
/**
* Convertit une chaîne hexadécimale en tableau d'octets.<br>
* Supprime tous les caractères d'espacement si le drapeau est défini.
*
* @param hex Chaîne hexadécimale
* @param removeWhitespace
* @return Tableau d'octets
*/
public static byte[] ToByteArray(string hex, bool removeWhitespace)
{
if (removeWhitespace)
{
hex = WS_PATTERN.Replace(hex, "");
}
return ToByteArray(hex);
}
/**
* Vérifie si la chaîne donnée est nulle ou vide.
*
* @param value Chaîne à vérifier.
* @return {@code true} si la chaîne est {@code null} ou vide, {@code false} sinon.
*/
public static bool IsNullOrEmpty(string value)
{
return string.IsNullOrEmpty(value);
}
/**
* Convertit la chaîne donnée en une chaîne vide si elle est nulle.
*
* @param s Chaîne à normaliser.
* @return La chaîne vide si la chaîne donnée était {@code null} ou vide, la chaîne donnée sinon.
*/
public static string NullToEmpty(string s)
{
return s ?? "";
}
/**
* Convertit la chaîne donnée en {@code null} si elle est vide.
*
* @param s Chaîne à normaliser.
* @return {@code null} si la chaîne donnée était {@code null} ou vide, la chaîne donnée sinon.
*/
public static string EmptyToNull(string s)
{
return string.IsNullOrEmpty(s) ? null : s;
}
}
internal class SecureMessaging
{
private readonly byte[] NULL = new byte[] { 0x00 };
private const byte PAD = 0x80;
private readonly byte[] secureMessagingSSC;
private readonly byte[] keyMAC;
private readonly byte[] keyENC;
private int i;
public SecureMessaging(byte[] keyMAC, byte[] keyENC)
{
this.keyENC = keyENC;
this.keyMAC = keyMAC;
secureMessagingSSC = new byte[16];
}
public byte[] encrypt(byte[] apdu)
{
incrementSSC(secureMessagingSSC);
byte[] commandAPDU = encrypt(apdu, secureMessagingSSC);
incrementSSC(secureMessagingSSC);
return commandAPDU;
}
public byte[] encrypt(byte[] apdu, byte[] secureMessagingSSC)
{
Console.WriteLine("secureMessagingSSC : " + i + " " + ByteUtils.byteToHexStr(secureMessagingSSC));
i++;
using (MemoryStream baos = new MemoryStream())
{
CardCommandAPDU cAPDU = new CardCommandAPDU(apdu);
if (cAPDU.IsSecureMessaging())
{
throw new ArgumentException("APDU malformé.");
}
byte[] data = cAPDU.GetData();
byte[] header = cAPDU.getHeader();
int lc = cAPDU.getLC();
int le = cAPDU.GetLE();
byte[] dataEncrypted = Array.Empty<byte>();
if (data.Length > 0)
{
data = pad(data, 16);
// Chiffrer les données
using (Aes aes = Aes.Create())
{
aes.Key = keyENC;
aes.IV = getCipherIV(secureMessagingSSC);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
dataEncrypted = encryptor.TransformFinalBlock(data, 0, data.Length);
dataEncrypted = new byte[] { 0x01 }.Concat(dataEncrypted).ToArray();
dataEncrypted = new byte[] { 0x87, (byte)dataEncrypted.Length }.Concat(dataEncrypted).ToArray();
}
}
// Écrire LE protégé
if (le >= 0)
{
TLV leObject = new TLV();
leObject.SetTagNumWithClass(0x97);
if (le == 0x100)
{
leObject.SetValue(NULL);
}
else if (le > 0x100)
{
leObject.SetValue(new byte[] { (byte)((le >> 8) & 0xFF), (byte)(le & 0xFF) });
}
else
{
leObject.SetValue(new byte[] { (byte)le });
}
baos.Write(leObject.ToBER(), 0, leObject.ToBER().Length);
}
// Indiquer Secure Messaging
// note : doit être fait avant le calcul du MAC
header[0] |= 0x0C;
/*
* Calcul du MAC
*/
// Calculate MAC
// Java code: https://github.com/ecsec/open-ecard/blob/master/ifd/ifd-protocols/pace/src/main/java/org/openecard/ifd/protocol/pace/SecureMessaging.java#L142
byte[] mac = new byte[16];
CMac cmac = getCMAC(secureMessagingSSC);
byte[] paddedHeader = pad(header, 16);
cmac.BlockUpdate(paddedHeader, 0, paddedHeader.Length);
if (dataEncrypted.Length > 0)
{
byte[] paddedData = pad(dataEncrypted, 16);
cmac.BlockUpdate(paddedData, 0, paddedData.Length);
}
cmac.DoFinal(mac, 0);
mac = mac.Take(8).ToArray();
// ASN.1/DER (TLV) - MAC
// Java code: https://github.com/ecsec/open-ecard/blob/master/ifd/ifd-protocols/pace/src/main/java/org/openecard/ifd/protocol/pace/SecureMessaging.java#L160
// mac = [0x8e, (byte)mac.Length, .. mac];
mac = new byte[] { 0x8e, (byte)mac.Length }.Concat(mac).ToArray();
// Concate encrypted data and MAC
// Java code: https://github.com/ecsec/open-ecard/blob/master/ifd/ifd-protocols/pace/src/main/java/org/openecard/ifd/protocol/pace/SecureMessaging.java#L163
//byte[] secureData = [.. dataEncrypted, .. mac];
byte[] secureData = dataEncrypted.Concat(mac).ToArray();
// Add header and footer
// Java code: https://github.com/ecsec/open-ecard/blob/master/ifd/ifd-protocols/pace/src/main/java/org/openecard/ifd/protocol/pace/SecureMessaging.java#L165
// byte[] secureCommand = [.. header, (byte)secureData.Length, .. secureData, 0x00];
byte[] secureCommand = header
.Concat(new byte[] { (byte)secureData.Length })
.Concat(secureData)
.Concat(new byte[] { 0x00 })
.ToArray();
return secureCommand;
}
}
public byte[] decrypt(byte[] response)
{
if (response.Length < 12)
{
throw new ArgumentException("Malformed Secure Messaging APDU.");
}
return decrypt(response, secureMessagingSSC);
}
public byte[] decrypt(byte[] response, byte[] secureMessagingSSC)
{
using (MemoryStream bais = new MemoryStream(response))
using (MemoryStream baos = new MemoryStream(response.Length - 10))
{
byte[] statusBytes = new byte[2];
byte[] dataObject = null;
byte[] macObject = new byte[8];
byte tag = (byte)bais.ReadByte();
if (tag == 0x87)
{
int size = bais.ReadByte();
if (size > 0x80)
{
byte[] sizeBytes = new byte[size & 0x0F];
bais.Read(sizeBytes, 0, sizeBytes.Length);
size = new BigInteger(1, sizeBytes).IntValue;
}
bais.Seek(1, SeekOrigin.Current); // Skip encryption header
dataObject = new byte[size - 1];
bais.Read(dataObject, 0, dataObject.Length);
tag = (byte)bais.ReadByte();
}
if (tag == 0x99)
{
if (bais.ReadByte() == 0x02)
{
bais.Read(statusBytes, 0, 2);
tag = (byte)bais.ReadByte();
}
}
else
{
throw new IOException("Malformed Secure Messaging APDU");
}
if (tag == 0x8E)
{
if (bais.ReadByte() == 0x08)
{
bais.Read(macObject, 0, 8);
}
}
else
{
throw new IOException("Malformed Secure Messaging APDU");
}
// Only 2 bytes status should remain
if (bais.Length - bais.Position != 2)
{
throw new IOException("Malformed Secure Messaging APDU");
}
// Calculate MAC for verification
CMac cmac = getCMAC(secureMessagingSSC);
byte[] mac = new byte[16];
lock (cmac)
{
MemoryStream macData = new MemoryStream();
// Write padding-content
if (dataObject != null)
{
TLV paddedDataObject = new TLV();
paddedDataObject.SetTagNumWithClass(0x87);
paddedDataObject.SetValue(ByteUtils.Concatenate((byte)0x01, dataObject));
macData.Write(paddedDataObject.ToBER(), 0, paddedDataObject.ToBER().Length);
}
// Write status bytes
TLV statusBytesObject = new TLV();
statusBytesObject.SetTagNumWithClass(0x99);
statusBytesObject.SetValue(statusBytes);
macData.Write(statusBytesObject.ToBER(), 0, statusBytesObject.ToBER().Length);
byte[] paddedData = pad(macData.ToArray(), 16);
cmac.BlockUpdate(paddedData, 0, paddedData.Length);
cmac.DoFinal(mac, 0);
mac = ByteUtils.Copy(mac, 0, 8);
}
// Verify MAC
if (!ByteUtils.Compare(mac, macObject))
{
throw new GeneralSecurityException("Secure Messaging MAC verification failed");
}
baos.Write(statusBytes, 0, statusBytes.Length);
return baos.ToArray();
}
}
public static void incrementSSC(byte[] ssc)
{
for (int i = ssc.Length - 1; i >= 0; i--)
{
ssc[i]++;
if (ssc[i] != 0)
{
break;
}
}
}
// Other methods omitted for brevity
private byte[] pad(byte[] data, int blockSize)
{
byte[] result = new byte[data.Length + (blockSize - data.Length % blockSize)];
Array.Copy(data, 0, result, 0, data.Length);
result[data.Length] = PAD;
return result;
}
private byte[] getCipherIV(byte[] smssc)
{
using (Aes aes = Aes.Create())
{
aes.Key = keyENC;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.None;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, null);
return encryptor.TransformFinalBlock(smssc, 0, smssc.Length);
}
}
private CMac getCMAC(byte[] smssc)
{
CMac cmac = new CMac(new AesEngine());
cmac.Init(new KeyParameter(keyMAC));
cmac.BlockUpdate(smssc, 0, smssc.Length);
return cmac;
}
}
public class CardCommandAPDU : CardAPDU
{
public readonly byte[] header = new byte[4];
public int le = -1;
public int lc = -1;
/**
* Crée une nouvelle APDU de commande.
*/
protected CardCommandAPDU()
{
}
/**
* Crée une nouvelle APDU de commande.
*
* @param commandAPDU APDU
*/
public CardCommandAPDU(byte[] commandAPDU)
{
System.Array.Copy(commandAPDU, 0, header, 0, 4);
setBody(ByteUtils.Copy(commandAPDU, 4, commandAPDU.Length - 4));
}
/**
* Crée une nouvelle APDU de commande.
*
* @param cla Byte de classe
* @param ins Byte d'instruction
* @param p1 Byte de paramètre P1
* @param p2 Byte de paramètre P2
*/
public CardCommandAPDU(byte cla, byte ins, byte p1, byte p2)
{
header[0] = cla;
header[1] = ins;
header[2] = p1;
header[3] = p2;
}
/**
* Crée une nouvelle APDU de commande.
*
* @param cla Byte de classe
* @param ins Byte d'instruction
* @param p1 Byte de paramètre P1
* @param p2 Byte de paramètre P2
* @param le Longueur attendue du champ
*/
public CardCommandAPDU(byte cla, byte ins, byte p1, byte p2, byte le)
{
// this(cla, ins, p1, p2, (short)(le & 0xFF));
header[0] = cla;
header[1] = ins;
header[2] = p1;
header[3] = p2;
this.le = le;
}
/**
* Crée une nouvelle APDU de commande.
*
* @param cla Byte de classe
* @param ins Byte d'instruction
* @param p1 Byte de paramètre P1
* @param p2 Byte de paramètre P2
* @param le Longueur attendue du champ
*/
public CardCommandAPDU(byte cla, byte ins, byte p1, byte p2, short le)
{
// this(cla, ins, p1, p2, (short)(le & 0xFFFF));
header[0] = cla;
header[1] = ins;
header[2] = p1;
header[3] = p2;
this.le = le;
}
/**
* Crée une nouvelle APDU de commande.
*
* @param cla Byte de classe
* @param ins Byte d'instruction
* @param p1 Byte de paramètre P1
* @param p2 Byte de paramètre P2
* @param le Longueur attendue du champ
*/
public CardCommandAPDU(byte cla, byte ins, byte p1, byte p2, int le)
{
// this(cla, ins, p1, p2);
header[0] = cla;
header[1] = ins;
header[2] = p1;
header[3] = p2;
this.le = le;
}
/**
* Crée une nouvelle APDU de commande.
*
* @param cla Byte de classe
* @param ins Byte d'instruction
* @param p1 Byte de paramètre P1
* @param p2 Byte de paramètre P2
* @param data Champ de données
*/
public CardCommandAPDU(byte cla, byte ins, byte p1, byte p2, byte[] data)
{
// this(cla, ins, p1, p2);
header[0] = cla;
header[1] = ins;
header[2] = p1;
header[3] = p2;
this.data = data;
setLC(data.Length);
}
/**
* Crée une nouvelle APDU de commande.
*
* @param cla Byte de classe
* @param ins Byte d'instruction
* @param p1 Byte de paramètre P1
* @param p2 Byte de paramètre P2
* @param data Champ de données
* @param le Longueur attendue du champ
*/
public CardCommandAPDU(byte cla, byte ins, byte p1, byte p2, byte[] data, byte le)
{
// this(cla, ins, p1, p2, data, (short)(le & 0xFF));
header[0] = cla;
header[1] = ins;
header[2] = p1;
header[3] = p2;
this.data = data;
SetLE(le);
}
/**
* Crée une nouvelle APDU de commande.
*
* @param cla Byte de classe
* @param ins Byte d'instruction
* @param p1 Byte de paramètre P1
* @param p2 Byte de paramètre P2
* @param data Champ de données
* @param le Longueur attendue du champ
*/
public CardCommandAPDU(byte cla, byte ins, byte p1, byte p2, byte[] data, short le)
{
// this(cla, ins, p1, p2, data, (int)le & 0xFFFF);
header[0] = cla;
header[1] = ins;
header[2] = p1;
header[3] = p2;
this.data = data;
SetLE(le);
}
/**
* Crée une nouvelle APDU de commande.
*
* @param cla Byte de classe
* @param ins Byte d'instruction
* @param p1 Byte de paramètre P1
* @param p2 Byte de paramètre P2
* @param data Champ de données
* @param le Longueur attendue du champ
*/
public CardCommandAPDU(byte cla, byte ins, byte p1, byte p2, byte[] data, int le)
{
// this(cla, ins, p1, p2, data);
header[0] = cla;
header[1] = ins;
header[2] = p1;
header[3] = p2;
this.data = data;
SetLE(le);
}
/**
* Définit le byte de classe de l'APDU.
*
* @param cla Byte de classe
*/
protected void SetCLA(byte cla)
{
header[0] = cla;
}
/**
* Retourne le byte de classe de l'APDU.
*
* @return Byte de classe
*/
public byte getCLA()
{
return (byte)(header[0] & 0xFF);
}
/**
* Définit le byte d'instruction de l'APDU.
*
* @param ins Byte d'instruction
*/
protected void setINS(byte ins)
{
header[1] = ins;
}
/**
* Retourne le byte d'instruction de l'APDU.
*
* @return Byte d'instruction
*/
public byte getINS()
{
return (byte)(header[1] & 0xFF);
}
/**
* Définit le byte de paramètre P1 de l'APDU.
*
* @param p1 Byte de paramètre P1
*/
protected void setP1(byte p1)
{
header[2] = p1;
}
/**
* Retourne le byte de paramètre P1 de l'APDU.
*
* @return Byte de paramètre P1
*/
public byte getP1()
{
return (byte)(header[2] & 0xFF);
}
/**
* Définit le byte de paramètre P2 de l'APDU.
*
* @param p2 Byte de paramètre P2
*/
protected void setP2(byte p2)
{
header[3] = p2;
}
/**
* Retourne le byte de paramètre P2 de l'APDU.
*
* @return Byte de paramètre P2
*/
public byte getP2()
{
return (byte)(header[3] & 0xFF);
}
/**
* Définit les bytes de paramètre P1 et P2 de l'APDU.
*
* @param p1p2 Bytes de paramètre P1 et P2
*/
protected void setP1P2(byte[] p1p2)
{
setP1(p1p2[0]);
setP2(p1p2[1]);
}
/**
* Retourne les bytes de paramètre P1 et P2 de l'APDU.
*
* @return Bytes de paramètre P1 et P2
*/
public byte[] getP1P2()
{
return new byte[] { getP1(), getP2() };
}
/**
* Retourne l'en-tête de l'APDU: CLA | INS | P1 | P2
*
* @return En-tête de l'APDU
*/
public byte[] getHeader()
{
return header;
}
/**
* Retourne l'en-tête de l'APDU.
*
* @param commandAPDU Command APDU
* @return En-tête de l'APDU
*/
public static byte[] getHeader(byte[] commandAPDU)
{
if (commandAPDU.Length < 4)
{
throw new ArgumentException("APDU mal formée");
}
return ByteUtils.Copy(commandAPDU, 0, 4);
}
/**
* Définit le champ de longueur de commande (LC) de l'APDU.
*
* @param lc Champ de longueur de commande (LC)
*/
protected void setLC(byte lc)
{
setLC((byte)(lc & 0xFF));
}
/**
* Définit le champ de longueur de commande (LC) de l'APDU.
*
* @param lc Champ de longueur de commande (LC)
*/
protected void setLC(short lc)
{
setLC((byte)(lc & 0xFFFF));
}
/**
* Définit le champ de longueur de commande (LC) de l'APDU.
*
* @param lc Champ de longueur de commande (LC)
*/
protected void setLC(int lc)
{
if (lc < 1 || lc > 65535)
{
throw new ArgumentException("La longueur doit être comprise entre '1' et '65535'.");
}
this.lc = lc;
}
/**
* Retourne le champ de longueur de commande (LC).
*
* @return Champ de longueur de commande (LC)
*/
public int getLC()
{
return lc;
}
/**
* Définit le champ de données de l'APDU. Le champ de longueur de commande (LC) sera calculé.
*
* @param data Champ de données
*/
public void SetData(byte[] data)
{
base.setData(data);
setLC(data.Length);
}
/**
* Définit le corps (LE, DATA, LC) de l'APDU.
*
* @param body Corps de l'APDU
*/
public void setBody(byte[] body)
{
/*
* Cas 1. : |CLA|INS|P1|P2|
* Cas 2. : |CLA|INS|P1|P2|LE|
* Cas 2.1: |CLA|INS|P1|P2|EXTLE|
* Cas 3. : |CLA|INS|P1|P2|LC|DATA|
* Cas 3.1: |CLA|INS|P1|P2|EXTLC|DATA|
* Cas 4. : |CLA|INS|P1|P2|LC|DATA|LE|
* Cas 4.1: |CLA|INS|P1|P2|EXTLC|DATA|LE|
* Cas 4.2: |CLA|INS|P1|P2|LC|DATA|EXTLE|
* Cas 4.3: |CLA|INS|P1|P2|EXTLC|DATA|EXTLE|
*/
try
{
using (MemoryStream bais = new MemoryStream(body))
{
int length = (int)bais.Length;
// Nettoyage
lc = -1;
le = -1;
data = new byte[0];
if (length == 0)
{
// Cas 1. : |CLA|INS|P1|P2|
}
else if (length == 1)
{
// Cas 2 |CLA|INS|P1|P2|LE|
le = bais.ReadByte() & 0xFF;
}
else if (length < 65536)
{
int tmp = bais.ReadByte();
if (tmp == 0)
{
// Cas 2.1, 3.1, 4.1, 4.3
if (bais.Length < 3)
{
// Cas 2.1 |CLA|INS|P1|P2|EXTLE|
le = ((bais.ReadByte() & 0xFF) << 8) | (bais.ReadByte() & 0xFF);
}
else
{
// Cas 3.1, 4.1, 4.3
lc = ((bais.ReadByte() & 0xFF) << 8) | (bais.ReadByte() & 0xFF);
data = new byte[lc];
bais.Read(data, 0, lc);
if (bais.Length == 1)
{
// Cas 4.1 |CLA|INS|P1|P2|EXTLC|DATA|LE|
le = bais.ReadByte() & 0xFF;
}
else if (bais.Length == 2)
{
// Cas 4.3 |CLA|INS|P1|P2|EXTLC|DATA|EXTLE|
le = ((bais.ReadByte() & 0xFF) << 8) | (bais.ReadByte() & 0xFF);
}
else if (bais.Length == 3)
{
if (bais.ReadByte() == 0)
{
// Cas 4.3 |CLA|INS|P1|P2|EXTLC|DATA|EXTLE|
le = ((bais.ReadByte() & 0xFF) << 8) | (bais.ReadByte() & 0xFF);
}
else
{
throw new ArgumentException("APDU malformée.");
}
}
else if (bais.Length > 3)
{
throw new ArgumentException("APDU malformée.");
}
}
}
else if (tmp > 0)
{
// Cas 3, 4, 4.2
lc = tmp & 0xFF;
data = new byte[lc];
bais.Read(data, 0, lc);
if (bais.Length == 1)
{
// Cas 4 |CLA|INS|P1|P2|LC|DATA|LE|
SetLE((byte)bais.ReadByte());
}
else if (bais.Length == 3)
{
// Cas 4.2 |CLA|INS|P1|P2|LC|DATA|EXTLE|
bais.ReadByte(); // Ignorer le premier octet
SetLE((byte)(short)(((bais.ReadByte() & 0xFF) << 8) | (bais.ReadByte() & 0xFF)));
}
else if (bais.Length == 2 || bais.Length > 3)
{
throw new ArgumentException("APDU malformée.");
}
}
else
{
throw new ArgumentException("APDU malformée.");
}
}
else
{
throw new ArgumentException("APDU malformée.");
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception", e);
}
}
/**
* Retourne le corps de l'APDU (LC*|DATA|LE*).
*
* @param commandAPDU Commande APDU
* @return Corps de l'APDU
*/
public static byte[] getBody(byte[] commandAPDU)
{
if (commandAPDU.Length < 4)
{
throw new ArgumentException("APDU malformée");
}
return ByteUtils.Copy(commandAPDU, 4, commandAPDU.Length - 4);
}
/**
* Définit le champ longueur attendue (LE) de l'APDU.
*
* @param le Champ longueur attendue (LE)
*/
public void setLE(byte le)
{
if (le == (byte)0x00)
{
SetLE(256);
}
else
{
SetLE((byte)(le & 0xFF));
}
}
/**
* Définit le champ de longueur attendue (LE) de l'APDU.
*
* @param le Champ de longueur attendue (LE)
*/
public void SetLE(short le)
{
if (le == 0x0000)
{
SetLE(65536);
}
else
{
SetLE(le & 0xFFFF);
}
}
/**
* Définit le champ de longueur attendue (LE) de l'APDU.
*
* @param le Champ de longueur attendue (LE)
*/
public void SetLE(int le)
{
if (le < 0 || le > 65536)
{
throw new ArgumentException("La longueur doit être comprise entre '1' et '65535'.");
}
else
{
this.le = le;
}
}
/**
* Retourne le champ de longueur attendue (LE).
*
* @return Champ de longueur attendue (LE)
*/
public int GetLE()
{
return le;
}
/**
* Met à jour le byte de classe de l'en-tête pour indiquer le chaînage de commandes.
* Voir ISO/IEC 7816-4 Section 5.1.1.1
*/
public void SetChaining()
{
header[0] = (byte)(header[0] | 0x10);
}
/**
* Retourne un itérateur sur les APDU de chaînage.
*
* @return Itérateur contenant les APDU.
*/
/* public IEnumerable GetChainingIterator()
{
// TODO: Implémentez l'itérateur de chaînage et ajoutez un type générique à Iterable. Je suppose que c'est cette classe.
throw new Exception("Pas encore implémenté");
}*/
/**
* Met à jour le byte de classe de l'en-tête pour indiquer le Secure Messaging.
* Voir ISO/IEC 7816-4 Section 6
*/
public void SetSecureMessaging()
{
header[0] = (byte)(header[0] | 0x0C);
}
/**
* Retourne vrai si l'en-tête de l'APDU indique le Secure Messaging.
*
* @return Vrai si l'APDU est une APDU de Secure Messaging.
*/
public bool IsSecureMessaging()
{
return ((header[0] & (byte)0x0F) == (byte)0x0C);
}
/**
* Retourne l'APDU encodée : CLA | INS | P1 | P2 | (EXT)LC | DATA | (EXT)LE
*
* @return APDU encodée
*/
public byte[] ToByteArray()
{
using (MemoryStream ms = new MemoryStream())
{
try
{
// Écrit l'en-tête de l'APDU
ms.Write(header, 0, header.Length);
// Écrit le champ LC de l'APDU
if (lc > 255 || (le > 256 && lc > 0))
{
// Champ LC étendu encodé sur trois octets
ms.WriteByte(x00);
ms.WriteByte((byte)(lc >> 8));
ms.WriteByte((byte)lc);
}
else if (lc > 0)
{
// Écrit le champ LC court
ms.WriteByte((byte)lc);
}
// Écrit le champ de données de l'APDU
ms.Write(data, 0, data.Length);
// Écrit le champ LE de l'APDU
if (le > 256)
{
// Écrit le champ LE étendu
if (lc == 0 || lc == -1)
{
// Champ LE étendu encodé sur trois octets
ms.WriteByte(x00);
}
// Champ LE étendu encodé sur deux octets si le champ LC étendu est présent
if (le >= 65536)
{
ms.WriteByte(x00);
ms.WriteByte(x00);
}
else
{
ms.WriteByte((byte)(le >> 8));
ms.WriteByte((byte)le);
}
}
else if (le > 0)
{
if (lc > 255)
{
// Écrit le champ LE étendu sur deux octets car le champ LC étendu est présent
ms.WriteByte((byte)(le >> 8));
ms.WriteByte((byte)le);
}
else
{
// Écrit le champ LE court
ms.WriteByte((byte)le);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Échec de la création de l'APDU en mémoire.", ex);
}
return ms.ToArray();
}
}
/**
* Retourne les octets de l'APDU sous forme d'une chaîne hexadécimale encodée.
*
* @return Chaîne hexadécimale encodée de l'APDU
*/
public override string ToString()
{
return ByteUtils.ToHexString(ToByteArray(), true);
}
/// <summary>
/// Transmet l'APDU.
/// Cette fonction utilise 0x9000 comme code de statut attendu et génère une erreur si un résultat différent est retourné par la carte.
/// </summary>
/// <param name="dispatcher">Dispatcher</param>
/// <param name="slotHandle">Handle du slot</param>
/// <returns>Réponse APDU</returns>
/// <exception cref="APDUException"></exception>
/* public CardResponseAPDU Transmit(Dispatcher dispatcher, byte[] slotHandle)
{
return Transmit(dispatcher, slotHandle, CardCommandStatus.ResponseOk());
}*/
}
public class CardAPDU
{
// TODO : quel est ce commentaire "ne pas utiliser avec un masque de bits
/**
* Octet 0x00. Ne pas utiliser avec un masque de bits !
*/
protected static readonly byte x00 = 0x00;
/**
* Octet 0xFF. Ne pas utiliser avec un masque de bits !
*/
protected static readonly byte xFF = 0xFF;
// TODO : rendre le champ inaccessible
/**
* Champ de données de l'APDU.
*/
public byte[] data = new byte[0];
/**
* Renvoie le champ de données de l'APDU.
*
* @return Champ de données. Peut être vide si aucune donnée n'est disponible
*/
public byte[] GetData()
{
if (data.Length == 0)
{
return new byte[0];
}
else
{
byte[] ret = new byte[data.Length];
System.Array.Copy(data, 0, ret, 0, data.Length);
return ret;
}
}
/**
* Définit le champ de données de l'APDU.
*
* @param data Champ de données
*/
public void setData(byte[] data)
{
this.data = data;
}
}
}