public string GetApdu(byte fileNumber, string offset, byte numberOfBytesToBeRead,
                              CommunicationMode communicationMode)
        {
            ValidateInput(offset);

            _offset = BinaryHelper.ConvertOctetStringToBytes(offset);

            byte[] data;
            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    WritePrefix(writer);

                    writer.Write(SeProcessorCommandTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(ProcessCardAPITag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(CardAPIDESFireTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(DESFireReadDataTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(FileNumberTag);
                    writer.Write(FileNumberValLength);
                    writer.Write(fileNumber);
                    writer.Write(OffsetTag);
                    writer.Write((byte)_offset.Length);
                    writer.Write(_offset);
                    writer.Write(DataTag);
                    writer.Write(DataValLenght);
                    writer.Write(numberOfBytesToBeRead);
                    writer.Write(ModeTag);
                    writer.Write(ModeValLength);
                    writer.Write((byte)communicationMode);

                    WritePostfix(writer);
                }

                data = stream.ToArray();
            }

            return(BinaryHelper.ConvertBytesToOctetString(data));
        }
Exemplo n.º 2
0
        /// <inheritdoc />
        /// <summary>
        /// Encrypts and sends given apdu command, returns decrypted response.
        /// </summary>
        /// <param name="apdu"></param>
        /// <returns></returns>
        public string SendCommand(string apdu)
        {
            if (_sessionStatus != SessionStatus.Established)
            {
                Terminate();
                throw new Exception("Attempt to Send Command via secure session, while session is not established");
            }
            // Encrypt data
            _counter.Increment();

            byte[] mac  = AesSivMac(BinaryHelper.ConvertOctetStringToBytes(_sessionMacKey), _counter.Value, BinaryHelper.ConvertOctetStringToBytes(apdu));
            byte[] enc  = AesSivCtr(BinaryHelper.ConvertOctetStringToBytes(_sessionEncryptionKey), mac, BinaryHelper.ConvertOctetStringToBytes(apdu));
            byte[] data = enc.Concat(mac).ToArray();

            var response = _smartCardReader.Transmit("FF720200" + data.Length.ToString("X2") + BinaryHelper.ConvertBytesToOctetString(data));

            // Decrypt response
            _counter.Increment();

            if (response.Substring(response.Length - 4) != "9000")
            {
                _sessionStatus = SessionStatus.NotEstablished;
                Terminate();
                throw new Exception($"Error {response.Substring(response.Length - 4)}\nSession Terminated.");
            }

            byte[] cryptogram = BinaryHelper.ConvertOctetStringToBytes(response.Substring(0, response.Length - 4));

            byte[] dataEnc = cryptogram.Take(cryptogram.Length - MacLength).ToArray();
            byte[] dataMac = cryptogram.Skip(cryptogram.Length - MacLength).Take(MacLength).ToArray();

            byte[] plain    = AesSivCtr(BinaryHelper.ConvertOctetStringToBytes(_sessionEncryptionKey), dataMac, dataEnc);
            byte[] dataMac2 = AesSivMac(BinaryHelper.ConvertOctetStringToBytes(_sessionMacKey), _counter.Value, plain);
            if (!dataMac.SequenceEqual(dataMac2))
            {
                _sessionStatus = SessionStatus.NotEstablished;
                Terminate();
                throw new Exception("Mac mismatch in decrypted response.\nSession Terminated.");
            }
            return(BinaryHelper.ConvertBytesToOctetString(plain));
        }
        public string GetApdu(string applicationNumber, byte masterKeySettings, byte numberOfKeys)
        {
            ValidateInput(applicationNumber);

            _applicationNumber = BinaryHelper.ConvertOctetStringToBytes(applicationNumber);

            byte[] data;
            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    WritePrefix(writer);

                    writer.Write(SeProcessorCommandTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(ProcessCardAPITag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(CardAPIDESFireTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(DESFireCreateApplicationTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(ApplicationNumberTag);
                    writer.Write((byte)_applicationNumber.Length);
                    writer.Write(_applicationNumber);
                    writer.Write(MasterKeySettingsTag);
                    writer.Write(MasterKeySettingsValLength);
                    writer.Write(masterKeySettings);
                    writer.Write(NumberOfKeysTag);
                    writer.Write(NumberOfKeysValLength);
                    writer.Write(numberOfKeys);

                    WritePostfix(writer);
                }

                data = stream.ToArray();
            }

            return(BinaryHelper.ConvertBytesToOctetString(data));
        }
        public string GetApdu(byte keyNumber, string keyReference)
        {
            ValidateInput(keyReference);

            _keyReference = BinaryHelper.ConvertOctetStringToBytes(keyReference);

            byte[] data;
            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    WritePrefix(writer);

                    writer.Write(SeProcessorCommandTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(ProcessCardAPITag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(CardAPIDESFireTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(DESFireAuthNativeTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(KeyNumberTag);
                    writer.Write(KeyNumberValLength);
                    writer.Write(keyNumber);
                    writer.Write(KeyReferenceTag);
                    writer.Write((byte)_keyReference.Length);
                    writer.Write(_keyReference);

                    WritePostfix(writer);
                }

                data = stream.ToArray();
            }

            return(BinaryHelper.ConvertBytesToOctetString(data));
        }
Exemplo n.º 5
0
        private string HostAuthentication()
        {
            if (_sessionStatus != SessionStatus.GetChallengePhase)
            {
                _sessionStatus = SessionStatus.NotEstablished;
                return(null);
            }

            using (var randomGenerator = RandomNumberGenerator.Create())
            {
                var hostKey   = new byte[KeyLength];
                var hostNonce = new byte[NonceLength];

                randomGenerator.GetBytes(hostKey);
                randomGenerator.GetBytes(hostNonce);

                _hostKey   = BinaryHelper.ConvertBytesToOctetString(hostKey);
                _hostNonce = BinaryHelper.ConvertBytesToOctetString(hostNonce);
            }

            // encrypy data
            byte[] plain = BinaryHelper.ConvertOctetStringToBytes(_hostNonce + _readerNonce + _hostKey);
            var    mac   = AesSivMac(BinaryHelper.ConvertOctetStringToBytes(_sessionMacKey), new byte[] { _keySlot }, plain);
            var    enc   = AesSivCtr(BinaryHelper.ConvertOctetStringToBytes(_sessionEncryptionKey), mac, plain);

            string mutualAuthenticationApdu = "FF72010040" + BinaryHelper.ConvertBytesToOctetString(enc.Concat(mac).ToArray());
            var    response = _smartCardReader.Transmit(mutualAuthenticationApdu);

            if (response.Substring(response.Length - 4) != "9000")
            {
                _sessionStatus = SessionStatus.NotEstablished;
                throw new Exception($"Establish secure session failed at HostAuthenticationPhase \nSend: {mutualAuthenticationApdu}\nRecived apdu: {response}");
            }
            _sessionStatus = SessionStatus.MutualAuthenticationPhase;
            return(response);
        }
        public string Transmit(ref IoRequest sendPci, ref IoRequest recivePci, string apdu)
        {
            var response = Transmit(ref sendPci, ref recivePci, BinaryHelper.ConvertOctetStringToBytes(apdu)).ToArray();

            return(BinaryHelper.ConvertBytesToOctetString(response));
        }
        public string Transmit(string apdu)
        {
            var response = Transmit(BinaryHelper.ConvertOctetStringToBytes(apdu)).ToArray();

            return(BinaryHelper.ConvertBytesToOctetString(response));
        }
        public string Control(ReaderControlCode controlCode, string dataBytes)
        {
            var response = Control(controlCode, BinaryHelper.ConvertOctetStringToBytes(dataBytes)).ToArray();

            return(BinaryHelper.ConvertBytesToOctetString(response));
        }
Exemplo n.º 9
0
 public Counter(string hostNonce, string readerNonce) : this(BinaryHelper.ConvertOctetStringToBytes(hostNonce),
                                                             BinaryHelper.ConvertOctetStringToBytes(readerNonce))
 {
 }
Exemplo n.º 10
0
 /// <inheritdoc />
 /// <summary>
 /// Encrypts and sends given apdu command, returns decrypted response.
 /// </summary>
 /// <param name="apdu"></param>
 /// <returns></returns>
 public byte[] SendCommand(byte[] apdu)
 {
     return(BinaryHelper.ConvertOctetStringToBytes(SendCommand(BinaryHelper.ConvertBytesToOctetString(apdu))));
 }
Exemplo n.º 11
0
 private string GetComplement(string data)
 {
     byte[] result = GetComplement(BinaryHelper.ConvertOctetStringToBytes(data));
     return(BinaryHelper.ConvertBytesToOctetString(result));
 }
Exemplo n.º 12
0
 private string Decrypt(string key, string data, CipherMode cMode = CipherMode.ECB, PaddingMode pMode = PaddingMode.None, string iv = "00000000000000000000000000000000")
 {
     byte[] derivedData;
     using (var aes = new AesCryptoServiceProvider {
         Mode = cMode, Padding = pMode
     })
         using (var ict = aes.CreateDecryptor(BinaryHelper.ConvertOctetStringToBytes(key), BinaryHelper.ConvertOctetStringToBytes(iv)))
         {
             byte[] dataBytes = BinaryHelper.ConvertOctetStringToBytes(data);
             derivedData = ict.TransformFinalBlock(dataBytes, 0, dataBytes.Length);
         }
     return(BinaryHelper.ConvertBytesToOctetString(derivedData));
 }
Exemplo n.º 13
0
        public byte[] SendCommand(byte[] command)
        {
            string response = SendCommand(BinaryHelper.ConvertBytesToOctetString(command));

            return(BinaryHelper.ConvertOctetStringToBytes(response));
        }