A communication error with the smart card has been detected

При возникновении проблем в работе со смарт-картами нужно проверить следующее: 1. Смарт-карта видится в системе как три устройства: Egate USB SmartCard Egate Virtual Reader Enumerator egate USB SmartCard Reader Каждое из устройств должно видится без восклицательного знака. Если хотя бы...

При возникновении проблем в работе со смарт-картами нужно проверить следующее:

1. Смарт-карта видится в системе как три устройства:

  • Egate USB SmartCard
  • Egate Virtual Reader Enumerator
  • egate USB SmartCard Reader

Каждое из устройств должно видится без восклицательного знака.

attachment.php

Если хотя бы одно из устройств не определяется, или определяется с восклицательным знаком, удалите карту из USB порта, установите последние драйверы для карты отсюда:

купить чтобы получить доступ к скрытому контенту.

(в самом низу «Latest version of the e-gate driver»). После установки драйвера перезагрузите компьютер и вставьте карту.

2. Служба «Смарт-карты» запущена и работает.
Это можно сделать из Панель управления -> Администрирование -> Службы. Если она не запущена — ее следует запустить. Если служба не запускается, следует попытаться восстановить работоспособность подсистемы работы со смарт-картами Windows. Для этого скачайте приложенный к посту Smart-Card Repair и запустите его. Нажмите на кнопку Repair Step 1. После сообщения программы, что все ок. Перезагрузите компьютер. Снова запустите SmartCardRepair. Нажмите на кнопку Repair Step 2. После сообщения программы, что все ок снова перезапустите компьютер.

attachment.php

Коды ошибок и сообщения об ошибках:
$80100001:
‘An internal consistency check failed.’
Внутренний тест целостности не пройден

$80100002:
‘The action was cancelled by an SCardCancel request.’;
Действие было отменено вызовом SCardCancel

$80100003:
‘The supplied handle was invalid.’;
Переданный дескриптор некорректен

$80100004:
‘One or more of the supplied parameters could not be properly interpreted.’;
Один или более переданных параметров не могут быть корректно интерпретированы.

$80100005:
‘Registry startup information is missing or invalid.’;
Информация в регистре неверна или отсутствует

$80100006:
‘Not enough memory available to complete this command.’;
Недостаточно памяти для завершения исполнения данной команды

$80100007:
‘An internal consistency timer has expired.’;
Сработал таймер контроля внутренней целостности

$80100008:
‘The data buffer to receive returned data is too small for the returned data.’;
Буфер данных для приема слишком мал для возвращаемых данных.

$80100009:
‘The specified reader name is not recognized.’;
Переданное имя ридера не опознано

$8010000A:
‘The user-specified timeout value has expired.’;
Заданный таймаут истек

$8010000B:
‘The smart card cannot be accessed because of other connections outstanding.’;
Невозможно получить доступ к смарт-карте из-за того, что существуют другие открытые подключения к ней.

$8010000C:
‘The operation requires a Smart Card, but no Smart Card is currently in the device.’;
Эта операция требует наличие смарт-карты, но смарт-карта не обнаружена.

$8010000D:
‘The specified smart card name is not recognized.’;
Смарт-карта с заданным именем не обнаружена.

$8010000E:
‘The system could not dispose of the media in the requested manner.’;
Система не может освободить ресурсы запрошенным способом.

$8010000F:
‘The requested protocols are incompatible with the protocol currently in use with the smart card.’;
Запрошенные протоколы несовместимы с протоколами, которые используются для работы с картой в текущий момент.

$80100010:
‘The reader or smart card is not ready to accept commands.’;
Ридер или смарт-карта не готовы к принятию команд.

$80100011:
‘One or more of the supplied parameters values could not be properly interpreted.’;
Одно или более переданных значений параметров не могут быть корректно интерпретированы.

$80100012:
‘The action was cancelled by the system, presumably to log off or shut down.’;
Действие было отменено из-за того, что был инициирован выход из системы или завершение работы.

$80100013:
‘An internal communications error has been detected.’;
Произвошла ошибка при внутренней коммуникации

$80100014:
‘An internal error has been detected, but the source is unknown.’;
Произошла внутренняя ошибка, но источник ошибки неизвестен

$80100015:
‘An ATR obtained from the registry is not a valid ATR string.’;
Полученный ATR не является корректной ATR строкой.

$80100016:
‘An attempt was made to end a non-existent transaction.’;
Была выполнена попытка завершить несуществующую транзакцию.

$80100017:
‘The specified reader is not currently available for use.’;
Указанный ридер в настоящее время недоступен для использования.

$80100018:
‘The operation has been aborted to allow the server application to exit.’;
Операция прервана, чтобы позволить приложению сервера успешно завершиться.

$80100019:
‘The PCI Receive buffer was too small.’;
Буфер приема PCI слишком мал.

$8010001A:
‘The reader driver does not meet minimal requirements for support.’;
Установленный драйвер ридера не удовлетворяет минимальным требованиям для поддержки

$8010001B:
‘The reader driver did not produce a unique reader name.’;
Драйвер ридера не герерирует уникальное имя

$8010001C:
‘The smart card does not meet minimal requirements for support.’;
Смарткарта не удовлетворяет минимальным требованиям для поддержки

$8010001D:
‘The Smart card resource manager is not running.’;
Служба «Смарт-карты» (Scardsvr) не запущена.

$8010001E:
‘The Smart card resource manager has shut down.’;
Служба «Смарт-карты» остановлена.

$8010001F:
‘An unexpected card error has occurred.’;
Произошла неожиданная ошибка карты.

$80100020:
‘No Primary Provider can be found for the smart card.’;
Первичный провайдер для данной карты не найден.

$80100021:
‘The requested order of object creation is not supported.’;
Запрошенный порядок создания объектов не поддерживается

$80100022:
‘This smart card does not support the requested feature.’;
Смарткарта не поддерживает запрошенную возможность.

$80100023:
‘The identified directory does not exist in the smart card.’;
Указанный каталог на карте не существует.

$80100024:
‘The identified file does not exist in the smart card.’;
Указанный файл на карте не существует.

$80100025:
‘The supplied path does not represent a smart card directory.’;
Переданный путь не является корректным именем каталога смарт-карты

$80100026:
‘The supplied path does not represent a smart card file.’;
Переданный путь не является корректным именем файла

$80100027:
‘Access is denied to this file.’;
Доступ к файлу отвергнут

$80100028:
‘The smartcard does not have enough memory to store the information.’;
У смарткарты недостаточно памяти для хранения информации

$80100029:
‘There was an error trying to set the smart card file object pointer.’;
Возникла ошибка при попытке установить указать на объект смарт-карты

$8010002A:
‘The supplied PIN is incorrect.’;
Переданный PIN-код некорректен

$8010002B:
‘An unrecognized error code was returned from a layered component.’;
От компонента получен нераспознанный код ошибки

$8010002C:
‘The requested certificate does not exist.’;
Запрошенный сертификат не существует

$8010002D:
‘The requested certificate could not be obtained.’;
Запрошенный сертификат не может быть получет

$8010002E:
‘Cannot find a smart card reader.’;
Невозможно найти кардридер

$08010002F:
‘A communications error with the smart card has been detected. Retry the operation.’;
Возникла ошибка при обмене информации с картой. Повторите операцию.

$080100030:
‘The requested key container does not exist on the smart card.’;
Запрошенный контейнер ключей на карте не существует

$80100065:
‘The reader cannot communicate with the smart card, due to ATR configuration conflicts.’;
Ридер не может работать с картой из-за конфликтов конфигураций ATR

$80100066:
‘The smart card is not responding to a reset.’;
Смарт-карта не отвечает на сигнал сброса

$80100067:
‘Power has been removed from the smart card, so that further communication is not possible.’;
Питание на карту более не подается, дальнейшая работа с картой невозможна.

$80100068:
‘The smart card has been reset, so any shared state information is invalid.’;
Смарткарте передан сигнал сброса, поэтому любые общие данные некорректны.

$80100069:
‘The smart card has been removed, so that further communication is not possible.’;
Смарткарта удалена, дальнейший обмен информацией с ней невозможен.

$8010006A:
‘Access was denied because of a security violation.’;
Доступ отвергнут из-за нарушения безопасности

$8010006B:
‘The card cannot be accessed because the wrong PIN was presented.’;
Невозможно произвести доступ к карте, поскольку передан некорректный код PIN

$8010006C:
‘The card cannot be accessed because the maximum number of PIN entry attempts has been reached.’;
Невозможно получить доступ к карте, поскольку количество попыток ввести правильный PIN код было слишком велико.

$8010006D:
‘The end of the smart card file has been reached.’;
Достигнут конец файла на смарткарте

$8010006E:
‘The action was cancelled by the user.’;
Действие отменено пользователем

$08010006F:
‘No PIN was presented to the smart card.’;
Смарткарте не был передан PIN код.

This article describes all the error codes for smart card logon to Windows and how to troubleshoot them.

For more information on how to set up smart card logon, see Set up smart card logon in Active Directory. 

Expand/Collapse All

No card is detected

 No card is detected

Error: No card is detected, and the login screen shows Connect a smart card.

Troubleshooting

  1. Make sure that the card reader is connected to the computer.
  2. Make sure that the card is inserted in the card reader. Often there is an indicator light on the card reader to show if the card is inserted or if the card is loading.
  3. Make sure that the drivers for the card reader are installed correctly.
  4. Make sure that the Cryptographic Service Provider (CSP) software, for example Nexus Personal Desktop Client, is installed correctly.

General error messages

 No valid certificates were found on this smart card.

Error message: No Valid Certificates were found on this smart card.

Either the driver for the card has not been installed or the card is empty or missing certificates.

Troubleshooting

  1. Make sure that the card contains certificates.
  2. Make sure that the CSP software (for example Nexus Personal Desktop Client) is installed correctly.
  3. Make sure that the drivers for the card reader are installed correctly.

 The requested key container does not exist on the smart card.

Error message: The requested key container does not exist on the smart card.

Troubleshooting

  1. Make sure that the CSP software (for example Nexus Personal Desktop Client) is installed correctly.
  2. Make sure that the drivers for the card reader are installed correctly.

Error message: «The system could not log you on…»

 A communication error with the smart card has been detected.

Error message: The system could not log you on. A communication error with the smart card has been detected.

Troubleshooting

  1. Was the card removed during the login procedure? Then try again.
  2. Make sure that the card reader is functioning.
  3. Switch USB port for the card reader and try again.

 An error occurred trying to use this smart card. You can find further details in the event log.

Error message: The system could not log you on. An error occurred trying to use this smart card. You can find further details in the event log. Please report this error to the system administrator.

Troubleshooting

  1. Check the log events/event viewer for errors. Troubleshoot depending on logged errors, and try to login again.

 An incorrect PIN was presented to the smart card.

Error message: The system could not log you on. An incorrect PIN was presented to the smart card.

Troubleshooting

  1. Make sure that NUM LOCK is on, if it is used.
  2. Try to log in again with the correct PIN.

 An untrusted certificate authority was detected while processing the smartcard certificate used for authentication.

Error message: The system could not log you on. An untrusted certificate authority was detected while processing the smartcard certificate used for authentication.

Troubleshooting

  1. Make sure that the CA certificates are available on your client and on the domain controllers.
  2. Make sure that the card certificates are valid.

 Make sure your User name and domain are correct, then type your password again.

Error message: The system could not log you on. Make sure your User name and domain are correct, then type your password again. Letters in passwords must be typed using the correct case.

Troubleshooting

  1. If login with username and password is not allowed, then you must log in with your smart card.
  2. If login with username and password is allowed, then verify the domain, user name, and password. If needed, reset the password and try again.

 The domain is not available.

Error message: The system cannot log you on now because the domain is not available.

Troubleshooting

  1. Make sure that the computer is connected to the network.
  2. If the computer is connected to the network, make sure that the domain controllers are reachable with ping.
  3. Make sure that the computer has a valid IP address and that DNS works.

 The requested certificate does not exist on the smart card.

Error message: The system could not log you on. The requested certificate does not exist on the smart card.

Troubleshooting

  1. Make sure that the CSP software (for example Nexus Personal Desktop Client) is installed correctly.
  2. Make sure that the drivers for the card reader are installed correctly.

 The requested keyset does not exist on the smart card.

Error message: The system could not log you on. The requested keyset does not exist on the smart card.

Troubleshooting

  1. Make sure that the CSP software (for example Nexus Personal Desktop Client) is installed correctly.
  2. Make sure that the drivers for the card reader are installed correctly.

 The revocation status of the domain controller certificate for smart card authentication could not be determined.

Error message: The system could not log you on. The revocation status of the domain controller certificate for smart card authentication could not be determined.

Troubleshooting

  1. Make sure that the OCSP service is running and that a valid certificate revocation list (CRL) is available in the Active Directory (AD).
  2. Try to log in on another computer, to see if you get the same result.

 The revocation status of the smartcard certificate used for authentication could not be determined.

Error message: The system could not log you on. The revocation status of the smartcard certificate used for authentication could not be determined.

Troubleshooting

  1. Restart the Key Distribution Center (KDC) service on the domain controllers.
  2. Make sure that all object identifiers (OIDs) are available for the CA certificates.

 The server authenticating you reported an error (0x%08lX). You can find further details in the event log.

Error message: The system could not log you on. The server authenticating you reported an error (0x%08lX). You can find further details in the event log. Please report this error to the system administrator.

Troubleshooting

  1. Check the log events/event viewer for errors. Troubleshoot depending on logged errors, and try to login again.

 The server authenticating you reported an error. You can find further details in the event log.

Error message: The system could not log you on. The server authenticating you reported an error. You can find further details in the event log. Please report this error to the system administrator.

Troubleshooting

  1. Check the log events/event viewer for errors. Troubleshoot depending on logged errors, and try to login again.

 The smart card is blocked.

Error message: The system could not log you on. The smart card is blocked.

Troubleshooting

  1. Unlock the smart card with the PUK code or challenge and response, depending on the card type and CSP software.

 The smartcard certificate used for authentication has been revoked.

Error message: The system could not log you on. The smartcard certificate used for authentication has been revoked.

Troubleshooting

  1. Make sure if your certificate is revoked or not.
  2. Clear the OCSP cache.
  3. Make sure that the OCSP service is running and that a valid certificate revocation list (CRL) is available in the Active Directory (AD).

 The smartcard certificate used for authentication has expired.

Error message: The system could not log you on. The smartcard certificate used for authentication has expired.

Troubleshooting

  1. Make sure that the card certificates are valid.

 The smartcard certificate used for authentication was not trusted.

Error message: The system could not log you on. The smartcard certificate used for authentication was not trusted.

Troubleshooting

  1. Make sure that the CA certificates are available on your client and on the domain controllers.
  2. Make sure that the card certificates are valid.

 This card cannot be used to authenticate you in this domain.

Error message: The system could not log you on. This card cannot be used to authenticate you in this domain.

Troubleshooting

  1. Make sure that the card certificates are valid.
  2. Make sure that the user principle name (UPN) has the right suffix on the domain.
  3. Make sure that the CA certificates are trusted by the domain, that is, that they are available on the domain controller.

 You cannot use a smart card to log on because smart card logon is not supported for your user account.

Error message: The system could not log you on. You cannot use a smart card to log on because smart card logon is not supported for your user account, Contact your system administrator to ensure that smart card logon is configured for your organization.

Troubleshooting

  1. Make sure that the CA certificates are available on your client and on the domain controllers.
  2. Make sure that the CSP software (for example Nexus Personal Desktop Client) is installed correctly.
  3. Make sure that the drivers for the card reader are installed correctly.
  4. Make sure that all object identifiers (OIDs) are available for the CA certificates.

 Your credentials could not be verified.

Error message: The system could not log you on. Your credentials could not be verified.

Troubleshooting

  1. Make sure that the user principle name (UPN) is configured correctly in the Active Directory (AD).
  2. Make sure that you have a network connection.
  3. Make sure that the computer has not been removed from the domain.
  4. Make sure that the CA certificates are installed on the client.
  5. Restart the Key Distribution Center (KDC) service on the domain controllers.

Offline

Вячеслав К.

 


#1
Оставлено
:

3 декабря 2021 г. 10:00:09(UTC)

Вячеслав К.

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.12.2021(UTC)
Сообщений: 2
Российская Федерация

Добрый день!

Проблема следующая — при попытке подписать документ в 1С при обращении к ключевому носителю выпадает окно «Смарт-карта не читается в устройстве чтения из-за конфликтов настройки ATR»
Screenshot_2.png (186kb) загружен 4 раз(а).

Если изъять носитель и заново вставить — начинает работать в штатном режиме. Частота повторений — рандом, может несколько раз за день, может раз в неделю — при выполнении одинаковых операций.

Проблема повторилась на нескольких ПК с разными носителями (Rutoken Lite, JaCarta) и разными ОС — Win 10.0 (Build 18362), сборка 18363, Win 10.0 (Build 19041), сборка 19041


Вверх


Offline

Grey

 


#2
Оставлено
:

3 декабря 2021 г. 10:56:33(UTC)

Grey

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 12.08.2013(UTC)
Сообщений: 805
Мужчина
Российская Федерация
Откуда: Москва

Сказал «Спасибо»: 5 раз
Поблагодарили: 197 раз в 162 постах

Автор: Вячеслав К. Перейти к цитате

Добрый день!

Проблема следующая — при попытке подписать документ в 1С при обращении к ключевому носителю выпадает окно «Смарт-карта не читается в устройстве чтения из-за конфликтов настройки ATR»
Screenshot_2.png (186kb) загружен 4 раз(а).

Если изъять носитель и заново вставить — начинает работать в штатном режиме. Частота повторений — рандом, может несколько раз за день, может раз в неделю — при выполнении одинаковых операций.

Проблема повторилась на нескольких ПК с разными носителями (Rutoken Lite, JaCarta) и разными ОС — Win 10.0 (Build 18362), сборка 18363, Win 10.0 (Build 19041), сборка 19041

Добрый день.

Подскажите, пожалуйста, какая используется версия провайдера? Есть ли в журнале событий (Правая кнопка на «Пуск» — Просмотр событий — Журналы Windows — Приложение) какие-то подозрительные ошибки в это время?

На всякий случай сразу порекомендую обновиться до сертифицированной сборки CSP 5.0 R2 — в ней мы упростили диагностику ошибок работы с токенами и повысили стабильность работы с ними. Соответственно, в сборках < 5.0.12000 присутствует некоторое количество известных ошибок, с одной из которых вы могли столкнуться.

С уважением,
Сергей
Техническую поддержку оказываем здесь.
Наша база знаний.


Вверх


Offline

Вячеслав К.

 


#3
Оставлено
:

3 декабря 2021 г. 11:24:43(UTC)

Вячеслав К.

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.12.2021(UTC)
Сообщений: 2
Российская Федерация

Автор: Grey Перейти к цитате

одскажите, пожалуйста, какая используется версия провайдера? Есть ли в журнале событий (Правая кнопка на «Пуск» — Просмотр событий — Журналы Windows — Приложение) какие-то подозрительные ошибки в это время?

КриптоПро 5.0.11944

Ошибки в журнале присутствуют:
АРМ1
Источник: Smart Card Service
код события: 610
Устройство чтения смарт-карт «ARDS JaCarta 0» отклонило IOCTL POWER: Запрос не был выполнен из-за ошибки ввода/вывода на устройстве.. Если ошибка повторяется, возможно, смарт-карта или устройство чтения смарт-карт работает неправильно.
Заголовок команды: 01 00 00 00

Источник: Smart Card Service
код события: 610
Устройство чтения смарт-карт «ARDS JaCarta 0» отклонило IOCTL POWER: Устройство не опознает команду.. Если ошибка повторяется, возможно, смарт-карта или устройство чтения смарт-карт работает неправильно.
Заголовок команды: 01 00 00 00

Источник: Smart Card Service
код события: 610
Устройство чтения смарт-карт «ARDS JaCarta 0» отклонило IOCTL GET_ATTRIBUTE: Устройство не опознает команду.. Если ошибка повторяется, возможно, смарт-карта или устройство чтения смарт-карт работает неправильно.
Заголовок команды: 01 02 08 00

АРМ2 (около 80 одинаково-веселых событий)
Источник: Smart Card Service
код события: 410
При подключении считывателя обнаружено недопустимое состояние доступности


Вверх


Online

Александр Лавник

 


#4
Оставлено
:

7 декабря 2021 г. 10:30:06(UTC)

Александр Лавник

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 30.06.2016(UTC)
Сообщений: 3,202
Мужчина
Российская Федерация

Сказал «Спасибо»: 53 раз
Поблагодарили: 722 раз в 674 постах

Автор: Вячеслав К. Перейти к цитате

Автор: Grey Перейти к цитате

одскажите, пожалуйста, какая используется версия провайдера? Есть ли в журнале событий (Правая кнопка на «Пуск» — Просмотр событий — Журналы Windows — Приложение) какие-то подозрительные ошибки в это время?

КриптоПро 5.0.11944

Ошибки в журнале присутствуют:
АРМ1
Источник: Smart Card Service
код события: 610
Устройство чтения смарт-карт «ARDS JaCarta 0» отклонило IOCTL POWER: Запрос не был выполнен из-за ошибки ввода/вывода на устройстве.. Если ошибка повторяется, возможно, смарт-карта или устройство чтения смарт-карт работает неправильно.
Заголовок команды: 01 00 00 00

Источник: Smart Card Service
код события: 610
Устройство чтения смарт-карт «ARDS JaCarta 0» отклонило IOCTL POWER: Устройство не опознает команду.. Если ошибка повторяется, возможно, смарт-карта или устройство чтения смарт-карт работает неправильно.
Заголовок команды: 01 00 00 00

Источник: Smart Card Service
код события: 610
Устройство чтения смарт-карт «ARDS JaCarta 0» отклонило IOCTL GET_ATTRIBUTE: Устройство не опознает команду.. Если ошибка повторяется, возможно, смарт-карта или устройство чтения смарт-карт работает неправильно.
Заголовок команды: 01 02 08 00

АРМ2 (около 80 одинаково-веселых событий)
Источник: Smart Card Service
код события: 410
При подключении считывателя обнаружено недопустимое состояние доступности

Вопрос обсуждается на портале технической поддержки в рамках обращения № 43180.

Техническую поддержку оказываем тут
Наша база знаний


Вверх

Пользователи, просматривающие эту тему

Guest

Быстрый переход
 

Вы не можете создавать новые темы в этом форуме.

Вы не можете отвечать в этом форуме.

Вы не можете удалять Ваши сообщения в этом форуме.

Вы не можете редактировать Ваши сообщения в этом форуме.

Вы не можете создавать опросы в этом форуме.

Вы не можете голосовать в этом форуме.

  • Remove From My Forums
  • Вопрос

  • Hi TechNet folks,

    We’ve an odd situation to resolve and it’s becoming more and more embarassing:

    • Base Info:

    Smart Card: .NET V2+ Card
    Middleware: Gemalto V5
    Smart Card Management: CLM 2007
    Internal Reader: Microsoft Usbccid Smart Card Reader
    External Reader: SCM SCR3310
    Drivers are up to date.

    • Issue Description:

    The internal readers on workstations do not work for him, he has to use an external reader to logon with his Smart Card.
    Gemalto is able to read the card while it’s inserted in both readers, but the card does not work to logon and CLM is not able to read it when it’s inserted into the internal reader.
    If we retire his card or give him a blank card and try to personalize it with in the internal reader, we get the following error «A communication error with the Smart Card has been detected.»
    The issue happens to this user only, on every workstation, and no one else using the same machines. He already got three replacement cards and even a different computer.
    If we personalize the Smart Card using the external reader, to read it in CLM is the same thing, to unlock the workstation it either says the certificate is invalid or that it had a communication error. However, CLM Smart Card Logon certificate seems to be
    correctly applied to the personal store when the card is personalized.

    I’m almost deleting this guy’s ID and recreating it from scratch but this is far from being the appropriate solution.

    Any help or idea would be greatly appreciated.

I building a project on Java Card using Java Card 2.1.2 SDK and GPShell as the way of communicating with the device.I tested the helloworld example from GpShell and I managed to send Simple APDU . However when I try to send APDU to a bigger .cap file the device gives me the following error

send_APDU() returns 0x8010002F (A communications error with the smart card has b
een detected. Retry the operation.
)

I attached pieces of code from the applet below.It seems to me a memory problem although Java Card has 80 Kb EEPROM and almost 2 Kb of RAM.In the Eclipse simulator the application works well.

TwineCipher.java

 public class TwineCipher implements IConsts{

    /**
     * The 80 bits of cipher twine
     */

    public static final short MAX_MEMORY_TEMPORARY=32;
    private static  TwineCipher ref_twineCipher_80 = null;
    private static  TwineCipher ref_twineCipher_128 = null;

    public  byte[] temp   =  JCSystem.makeTransientByteArray(MAX_MEMORY_TEMPORARY,JCSystem.CLEAR_ON_DESELECT);
    public  byte[] rk   = JCSystem.makeTransientByteArray((short) ((short)36*8),JCSystem.CLEAR_ON_DESELECT); 

    private static byte  [] roundconst = 
        {
                0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x03, 0x06, 0x0c, 0x18, 0x30, 0x23, 0x05, 0x0a, 0x14, 0x28, 0x13, 0x26,
                0x0f, 0x1e, 0x3c, 0x3b, 0x35, 0x29, 0x11, 0x22, 0x07, 0x0e, 0x1c, 0x38, 0x33, 0x25, 0x09, 0x12, 0x24, 0x0b,
        };

    private static short [] shufinv = {1, 2, 11, 6, 3, 0, 9, 4, 7, 10, 13, 14, 5, 8, 15, 12};
    private static short [] shuf = { 5, 0, 1, 4, 7, 12, 3, 8, 13, 6, 9, 2, 15, 10, 11, 14};
    private static byte  [] sbox = {0x0C, 0x00, 0x0F, 0x0A, 0x02, 0x0B, 0x09, 0x05, 0x08, 0x03, 0x0D, 0x07, 0x01, 0x0E, 0x06, 0x04};
    private static byte  [] data_enc  = new byte[16];

    public static TwineCipher getInstance(byte type,byte[] key)
    {
        switch(type)
        {
            case TWINE_CIPHER_80:
                if(ref_twineCipher_80 != null)
                    return ref_twineCipher_80;
                ref_twineCipher_80 =  new TwineCipher(key,TWINE_CIPHER_80);
                return ref_twineCipher_80;
            case TWINE_CIPHER_128:
                if(ref_twineCipher_128 != null)
                    return ref_twineCipher_128;
                ref_twineCipher_128 =  new TwineCipher(key,TWINE_CIPHER_128);
                return ref_twineCipher_128;
            default:
                ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
        }
        ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
        return null;
    }

    public static TwineCipher getInstance(byte type)
    {
        switch(type)
        {
            case TWINE_CIPHER_80:
                if(ref_twineCipher_80 != null)
                    return ref_twineCipher_80;
                ref_twineCipher_80 =  new TwineCipher();
                return ref_twineCipher_80;
            case TWINE_CIPHER_128:
                if(ref_twineCipher_128 != null)
                    return ref_twineCipher_128;
                ref_twineCipher_128 =  new TwineCipher();
                return ref_twineCipher_128;
            default:
                ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
        }
        ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
        return null;
    }
    private TwineCipher(byte[] key,byte keySize)
    {
        switch(keySize)
        {
            case TWINE_CIPHER_80:
                expand80Key(key);
                break;
            case TWINE_CIPHER_128:
                expand128Key(key);
                break;
            default:
                ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
        }
    }
    private TwineCipher()
    {

    }

    private void expand80Key(byte[] key)
    {
        short len_x = 20;
        short key_size = 10;
        short iterator = 0,iterator2=0;;
        byte temp_val=-1;
        byte temp_val2=-1,temp_val3=-1,temp_val4=-1;
        short sh=0;
        // reset the array
        Util.arrayFillNonAtomic(temp, (short)0, (short)20, IConsts.UNTOUCHED_VALUE);

        unrowl80ExpandKey(key);

        for ( iterator = 0 ; iterator < 35;iterator ++)
        {
            rk[(short)(iterator * 8 + 0)] = temp[1];
            rk[(short)(iterator * 8 + 1)] = temp[3];
            rk[(short)(iterator * 8 + 2)] = temp[4];
            rk[(short)(iterator * 8 + 3)] = temp[6];
            rk[(short)(iterator * 8 + 4)] = temp[13];
            rk[(short)(iterator * 8 + 5)] = temp[14];
            rk[(short)(iterator * 8 + 6)] = temp[15];
            rk[(short)(iterator * 8 + 7)] = temp[16];

            temp[1] ^= sbox[temp[0]];
            temp[4] ^= sbox[temp[16]];
            temp_val = roundconst[iterator];
            temp[7] ^= temp_val >> 3;
            temp[19] ^= temp_val & 7;

            temp_val  = temp[0];
            temp_val2 = temp[1];
            temp_val3 = temp[2];
            temp_val4 = temp[3];

            for (iterator2 = 0 ; iterator2 < 4;iterator2++)
            {
                sh                  = (short)(iterator2*4);
                temp[sh]            = temp[(short)(sh+4)];
                temp[(short)(sh+1)] = temp[(short)(sh+5)];
                temp[(short)(sh+2)] = temp[(short)(sh+6)];
                temp[(short)(sh+3)] = temp[(short)(sh+7)];
            }

            temp[16]   = temp_val2;
            temp[17]   = temp_val3;
            temp[18]   = temp_val4;
            temp[19]   = temp_val;

        }
        rk[(short)(35 * 8 + 0)] = temp[1];  
        rk[(short)(35 * 8 + 1)] = temp[3];  
        rk[(short)(35 * 8 + 2)] = temp[4];  
        rk[(short)(35 * 8 + 3)] = temp[6];  
        rk[(short)(35 * 8 + 4)] = temp[13]; 
        rk[(short)(35 * 8 + 5)] = temp[14]; 
        rk[(short)(35 * 8 + 6)] = temp[15]; 
        rk[(short)(35 * 8 + 7)] = temp[16]; 

    }
    private void expand128Key(byte[] key)
    {

    }

    public byte[] encrypt(byte[] src,byte[] dest,short len_src)
    {
        Util.arrayFillNonAtomic(temp, (short)0, (short)32, IConsts.UNTOUCHED_VALUE); //reset all values 
                                                   // 16 bytes for first part
                                                  // 16 bytes for next
        short iterator=0,iterator2=0,iterator3=0;
        short START_ITERATOR = 16;
        for( iterator = 0 ; iterator < len_src ; iterator++)
        {
            temp[(short)(2*iterator)] = (byte)((short) (src[iterator] & 0x00FF) >> 4);
            temp[(short)(2*iterator+1)] = (byte)((short) (src[iterator] & 0x00FF) & 0x0F);
        }

        for ( iterator = 0 ; iterator < 35 ; iterator ++)
        {
            for ( iterator2 = 0 ; iterator2 < 8 ; iterator2 ++)
            {
                temp[(short)(2*iterator2+1)] ^= sbox[temp[(short)(2*iterator2)] ^ rk[(short)(iterator*8+iterator2)]]; 

            }

            for (iterator3 = 0 ; iterator3 < 16;iterator3++)
            {
                temp[(short)(shuf[iterator3]+16)] = temp[(short)(iterator3)];
            }
            Util.arrayCopy(temp, (short)16, temp, (short)0, (short)16);
        }
        iterator = 35;
        for (iterator2 = 0; iterator2 < 8 ;iterator2++)
        {
            temp[(short)(2*iterator2+1)] ^= sbox[temp[(short)(2*iterator2)]^ rk[(short)(iterator*8+iterator2)]];        
        }

        for ( iterator = 0 ;iterator < 8 ;iterator++)
        {
            temp[(short)(24+iterator)] = (byte)(temp[(short)(2*iterator)] << 4 | temp[(short)(2*iterator + 1)]);
        }
        Util.arrayCopy(temp, (short)24, dest, (short)(ISO7816.OFFSET_CDATA), (short)8);
        return temp; // returns bytes from 24 to 32
    }
    public byte[] decrypt(byte[] src,byte[] dest,short len_src)
    {
        // for this alg len_src is always 8 
        Util.arrayFillNonAtomic(temp, (short)0, (short)32, IConsts.UNTOUCHED_VALUE); //reset all values 
        short iterator=0,iterator2=0,iterator3=0;
        short START_ITERATOR = 16;
        for( iterator = 0 ; iterator < len_src ; iterator++)
        {
            temp[(short)(2*iterator)] = (byte)((short) (src[iterator] & 0x00FF) >> 4);
            temp[(short)(2*iterator+1)] = (byte)((short) (src[iterator] & 0x00FF) & 0x0F);
        }

        for ( iterator = 35 ; iterator > 0 ; iterator --)
        {
            for ( iterator2 = 0 ; iterator2 < 8 ; iterator2 ++)
            {
                temp[(short)(2*iterator2+1)] ^= sbox[temp[(short)(2*iterator2)]^ rk[(short)(iterator*8+iterator2)]];
            }

            for (iterator3 = 0 ; iterator3 < 16;iterator3++)
            {
                temp[(short)(shufinv[iterator3]+16)] = temp[(short)(iterator3)];
            }
            Util.arrayCopy(temp, (short)16, temp, (short)0, (short)16);
        }
        //FINAL
        iterator = 0;
        for (iterator2 = 0; iterator2 < 8 ;iterator2++)
        {
            temp[(short)(2*iterator2+1)] ^= sbox[temp[(short)(2*iterator2)]^ rk[(short)(iterator*8+iterator2)]];
        }

        for ( iterator = 0 ;iterator < 8 ;iterator++)
        {
            temp[(short)(24+iterator)] = (byte)(temp[(short)(2*iterator)] << 4 | temp[(short)(2*iterator + 1)]);
        }
        Util.arrayCopy(temp, (short)24, dest, (short)(ISO7816.OFFSET_CDATA), (short)8);
        return temp; // returns bytes from 24 to 32 indexes
    }

    public short process(byte type,byte[] data,short start_offset,short len_data)
    {
        Util.arrayCopy(data, start_offset, data_enc, (short) 0, len_data);
        switch(type)
        {
            case OFFSET_P1_ENC:
                encrypt(data_enc, data, len_data);
                return (short)8;
            case OFFSET_P1_DEC:
                decrypt(data_enc, data, len_data);
                return (short)8;
            case OFFSET_P1_GEN:
                expand80Key(data_enc);
                return 10;
            default:
                return (short)-1;
        }

    }

    private void unrowl80ExpandKey(byte[] key)
    {
        temp[(short)(2*0)] = (byte)((short) (key[0] & 0x00FF) >> 4);
        temp[(short)(2*0 + 1)] = (byte)((short) (key[0] & 0x00FF) & 0x0F);  

        temp[(short)(2*1)] = (byte)((short) (key[1] & 0x00FF) >> 4);
        temp[(short)(2*1 + 1)] = (byte)((short) (key[1] & 0x00FF) & 0x0F);  

        temp[(short)(2*2)] = (byte)((short) (key[2] & 0x00FF) >> 4);
        temp[(short)(2*2 + 1)] = (byte)((short) (key[2] & 0x00FF) & 0x0F);  

        temp[(short)(2*3)] = (byte)((short) (key[3] & 0x00FF) >> 4);
        temp[(short)(2*3 + 1)] = (byte)((short) (key[3] & 0x00FF) & 0x0F);  

        temp[(short)(2*4)] = (byte)((short) (key[4] & 0x00FF) >> 4);
        temp[(short)(2*4 + 1)] = (byte)((short) (key[4] & 0x00FF) & 0x0F);  

        temp[(short)(2*5)] = (byte)((short) (key[5] & 0x00FF) >> 4);
        temp[(short)(2*5 + 1)] = (byte)((short) (key[5] & 0x00FF) & 0x0F);  

        temp[(short)(2*6)] = (byte)((short) (key[6] & 0x00FF) >> 4);
        temp[(short)(2*6 + 1)] = (byte)((short) (key[6] & 0x00FF) & 0x0F);  

        temp[(short)(2*7)] = (byte)((short) (key[7] & 0x00FF) >> 4);
        temp[(short)(2*7 + 1)] = (byte)((short) (key[7] & 0x00FF) & 0x0F);  

        temp[(short)(2*8)] = (byte)((short) (key[8] & 0x00FF) >> 4);
        temp[(short)(2*8 + 1)] = (byte)((short) (key[8] & 0x00FF) & 0x0F);  

        temp[(short)(2*9)] = (byte)((short) (key[9] & 0x00FF) >> 4);
        temp[(short)(2*9 + 1)] = (byte)((short) (key[9] & 0x00FF) & 0x0F);  
    }
}

IConst.java interface

  public interface IConsts 
{
    public static final byte UNTOUCHED_VALUE = 0x50;
    public static final byte TRUE = 0x01;
    public static final byte FALSE = 0x00;

    public static final byte OFFSET_CLA_CIPHERS = (byte) 0x00;
    public static final byte OFFSET_INS_LIGHT = (byte) 0x11;


    public static final byte OFFSET_P1_ENC   = (byte) 0x21;
    public static final byte OFFSET_P1_DEC   = (byte) 0x22;
    public static final byte OFFSET_P1_GEN   = (byte) 0x23;

    public static final byte TWINE_CIPHER_80=0x30;
    public static final byte TWINE_CIPHER_128=0x31;
    public static final byte LBLOCK_CIPHER=0x32;
}

LBlockCipher.java 

   public class LBlockCipher implements IConsts {


    public static final byte  LBLOCK_NBROUNDS =  32;
    public static final byte  LBLOCK_KEY_SIZE =  80;
    public static final short MEMORY_OUTPUT=32*4;
    public static final short MEMORY_TEMPORARY=32;  

    static final byte[] S0 = { 14, 9, 15, 0, 13, 4, 10, 11, 1, 2, 8, 3, 7, 6, 12, 5};
    static final byte[] S1 = { 4, 11, 14, 9, 15, 13, 0, 10, 7, 12, 5, 6, 2, 8, 1, 3 };
    static final byte[] S2 = { 1, 14, 7, 12, 15, 13, 0, 6, 11, 5, 9, 3, 2, 4, 8, 10 };
    static final byte[] S3 = { 7, 6, 8, 11, 0, 15, 3, 14, 9, 10, 12, 13, 5, 2, 4, 1 };
    static final byte[] S4 = { 14, 5, 15, 0, 7, 2, 12, 13, 1, 8, 4, 9, 11, 10, 6, 3 };
    static final byte[] S5 = { 2, 13, 11, 12, 15, 14, 0, 9, 7, 10, 6, 3, 1, 8, 4, 5 };
    static final byte[] S6 = { 11, 9, 4, 14, 0, 15, 10, 13, 6, 12, 5, 7, 3, 8, 1, 2 };
    static final byte[] S7 = { 13, 10, 15, 0, 14, 4, 9, 11, 2, 1, 8, 3, 7, 5, 12, 6 };
    static final byte[] S8 = { 8, 7, 14, 5, 15, 13, 0, 6, 11, 12, 9, 10, 2, 4, 1, 3 };
    static final byte[] S9 = { 11, 5, 15, 0, 7, 2, 9, 13, 4, 8, 1, 12, 14, 10, 3, 6 };  

    public  byte[] output    =  JCSystem.makeTransientByteArray(MEMORY_OUTPUT,JCSystem.CLEAR_ON_DESELECT); 
    public  byte[] temp      =  JCSystem.makeTransientByteArray(MEMORY_TEMPORARY,JCSystem.CLEAR_ON_DESELECT); 

    private static LBlockCipher m_instance_Cipher = null;

    public void keySchedule(byte[] key,short start_offset)
    {
        // use for keyR offset temp [0 - 3 ]
        short i = 0 ;
        output[(short)(0*4+3)] = key[(short)(9 + start_offset)];
        output[(short)(0*4+2)] = key[(short)(8 + start_offset)];
        output[(short)(0*4+1)] = key[(short)(7 + start_offset)];
        output[(short)(0*4+0)] = key[(short)(6 + start_offset)];

        for ( i = 1;i<32;i++)
        {
            temp[3] = key[(short)(9 + start_offset)];
            temp[2] = key[(short)(8 + start_offset)];
            temp[1] = key[(short)(7 + start_offset)];
            temp[0] = key[(short)(6 + start_offset)];

            key[(short)(9 + start_offset)] = (byte) ((((key[(short)(6 + start_offset)] & 0x07) << 5) 
                                            & 0xE0) ^ (((key[(short)(5 + start_offset)] & 0xF8) >> 3) & 0x1F));
            key[(short)(8 + start_offset)] = (byte) ((((key[(short)(5 + start_offset)]
                                            & 0x07) << 5) & 0xE0) ^ (((key[(short)(4 + start_offset)] & 0xF8) >> 3) & 0x1F));
            key[(short)(7 + start_offset)] = (byte) ((((key[(short)(4 + start_offset)] 
                                            & 0x07) << 5) & 0xE0) ^ (((key[(short)(3 + start_offset)] & 0xF8) >> 3) & 0x1F));
            key[(short)(6 + start_offset)] = (byte) ((((key[(short)(3 + start_offset)] 
                                            & 0x07) << 5) & 0xE0) ^ (((key[(short)(2 + start_offset)] & 0xF8) >> 3) & 0x1F));
            key[(short)(5 + start_offset)] = (byte) ((((key[(short)(2 + start_offset)] & 0x07) << 5) 
                                            & 0xE0) ^ (((key[(short)(1 + start_offset)] & 0xF8) >> 3) & 0x1F));

            key[(short)(4 + start_offset)] = (byte) ((((key[(short)(1 + start_offset)] & 0x07) << 5) 
                                            & 0xE0) ^ (((key[(short)(0 + start_offset)] & 0xF8) >> 3) & 0x1F));
            key[(short)(3 + start_offset)] = (byte) ((((key[(short)(0 + start_offset)] & 0x07) << 5) 
                                            & 0xE0) ^ (((temp[3] & 0xF8) >> 3) & 0x1F));
            key[(short)(2 + start_offset)] = (byte) ((((temp[3] & 0x07) << 5) & 0xE0) ^ (((temp[2] & 0xF8) >> 3) & 0x1F));
            key[(short)(1 + start_offset)] = (byte) ((((temp[2] & 0x07) << 5) & 0xE0) ^ (((temp[1] & 0xF8) >> 3) & 0x1F));
            key[(short)(0 + start_offset)] = (byte) ((((temp[1] & 0x07) << 5) & 0xE0) ^ (((temp[0] & 0xF8) >> 3) & 0x1F));

            key[(short)(9 + start_offset)] = (byte) ((S9[((key[(short)(9 + start_offset)] >> 4) & 0x0F)] << 4)
                                            ^ S8[(key[(short)(9 + start_offset)] & 0x0F)]);

            key[(short)(6 + start_offset)] = (byte) (key[(short)(6 + start_offset)] ^ ((i >> 2) & 0x07));
            key[(short)(5 + start_offset)] = (byte) (key[(short)(5 + start_offset)] ^ ((i & 0x03) << 6));

            output[(short)(i*4 + 3)] =  key[(short)(9 + start_offset)];
            output[(short)(i*4 + 2)] =  key[(short)(8 + start_offset)];
            output[(short)(i*4 + 1)] =  key[(short)(7 + start_offset)];
            output[(short)(i*4 + 0)] =  key[(short)(6 + start_offset)];;
        }
    }
    public void OneRound(byte[] x,byte[] k,short offset,short offset_x)
    {
        // t  - from 5 - 8 tmp from 9 to 12
        //  u8 t[4], tmp[4];

        temp[9]  = x[(short)(4 + offset_x)];
        temp[10] = x[(short)(5 + offset_x)];
        temp[11] = x[(short)(6 + offset_x)];
        temp[12] = x[(short)(7 + offset_x)];

        x[(short)(4 + offset_x)] ^= k[offset];
        x[(short)(5 + offset_x)] ^= k[(short)(offset+1)];
        x[(short)(6 + offset_x)] ^= k[(short)(offset+2)];
        x[(short)(7 + offset_x)] ^= k[(short)(offset+3)];

        x[(short)(4 + offset_x)] = (byte) (((S1[((x[(short)(4 + offset_x)]) >> 4) & 0x0F]) << 4) 
                                ^ S0[(x[(short)(4 + offset_x)] & 0x0F)]);
        x[(short)(5 + offset_x)] = (byte) (((S3[((x[(short)(5 + offset_x)]) >> 4) & 0x0F]) << 4) 
                                ^ S2[(x[(short)(5 + offset_x)] & 0x0F)]);
        x[(short)(6 + offset_x)] = (byte) (((S5[((x[(short)(6 + offset_x)]) >> 4) & 0x0F]) << 4) 
                                ^ S4[(x[(short)(6 + offset_x)] & 0x0F)]);
        x[(short)(7 + offset_x)]= (byte) (((S7[((x[(short)(7 + offset_x)]) >> 4) & 0x0F]) << 4)
                                ^  S6[(x[(short)(7 + offset_x)] & 0x0F)]);

        temp[5] = (byte) (((x[(short)(4 + offset_x)] >> 4) & 0x0F) ^ (x[(short)(5 + offset_x)] & 0xF0));
        temp[6] = (byte) ((x[(short)(4 + offset_x)] & 0x0F) ^ ((x[(short)(5 + offset_x)] & 0x0F) << 4));
        temp[7] = (byte) (((x[(short)(6 + offset_x)] >> 4) & 0x0F) ^ (x[(short)(7 + offset_x)] & 0xF0));
        temp[8] = (byte) ((x[(short)(6 + offset_x)] & 0x0F) ^ ((x[(short)(7 + offset_x)] & 0x0F) << 4));

        x[(short)(4 + offset_x)] = (byte) (x[(short)(3 + offset_x)] ^ temp[5]);
        x[(short)(5 + offset_x)] = (byte) (x[(short)(0 + offset_x)] ^ temp[6]);
        x[(short)(6 + offset_x)] = (byte) (x[(short)(1 + offset_x)] ^ temp[7]);
        x[(short)(7 + offset_x)] = (byte) (x[(short)(2 + offset_x)] ^ temp[8]);

        x[(short)(0 + offset_x)] = temp[9];
        x[(short)(1 + offset_x)] = temp[10];
        x[(short)(2 + offset_x)] = temp[11];
        x[(short)(3 + offset_x)] = temp[12];


    }
    public void encrypt(byte[] x,short offset_x)
    {
        short i;
        for (i = 0; i<32; i++)
        {
            OneRound(x,output,(short)(4*i),offset_x);
        }
    }
    public void OneRoundInv(byte[] y, byte[] k,short offset,short offset_y)
    {
        // t  - from 5 - 8 tmp from 9 to 12
        //  u8 t[4], tmp[4];

        temp[9]  = y[(short)(0 + offset_y)];
        temp[10] = y[(short)(1 + offset_y)];
        temp[11] = y[(short)(2 + offset_y)];
        temp[12] = y[(short)(3 + offset_y)];

        y[(short)(0 + offset_y)] = (byte) (y[(short)(0 + offset_y)] ^ k[offset]);
        y[(short)(1 + offset_y)] = (byte) (y[(short)(1 + offset_y)] ^ k[(short)(offset+1)]);
        y[(short)(2 + offset_y)] = (byte) (y[(short)(2 + offset_y)] ^ k[(short)(offset+2)]);
        y[(short)(3 + offset_y)] = (byte) (y[(short)(3 + offset_y)] ^ k[(short)(offset+3)]);


        y[(short)(0 + offset_y)] = (byte) (((S1[((y[(short)(0 + offset_y)]) >> 4) & 0x0F]) << 4) ^ S0[(y[(short)(0 + offset_y)] & 0x0F)]);
        y[(short)(1 + offset_y)] = (byte) (((S3[((y[(short)(1 + offset_y)]) >> 4) & 0x0F]) << 4) ^ S2[(y[(short)(1 + offset_y)] & 0x0F)]);
        y[(short)(2 + offset_y)] = (byte) (((S5[((y[(short)(2 + offset_y)]) >> 4) & 0x0F]) << 4) ^ S4[(y[(short)(2 + offset_y)] & 0x0F)]);
        y[(short)(3 + offset_y)] = (byte) (((S7[((y[(short)(3 + offset_y)]) >> 4) & 0x0F]) << 4) ^ S6[(y[(short)(3 + offset_y)] & 0x0F)]);


        temp[5] = (byte) (((y[(short)(0 + offset_y)] >> 4) & 0x0F) ^ (y[(short)(1 + offset_y)] & 0xF0));
        temp[6] = (byte) ((y[(short)(0 + offset_y)] & 0x0F) ^ ((y[(short)(1 + offset_y)] & 0x0F) << 4));
        temp[7] = (byte) (((y[(short)(2 + offset_y)] >> 4) & 0x0F) ^ (y[(short)(3 + offset_y)] & 0xF0));
        temp[8] = (byte) ((y[(short)(2 + offset_y)] & 0x0F) ^ ((y[(short)(3 + offset_y)] & 0x0F) << 4));

        y[(short)(0 + offset_y)] = (byte) (y[(short)(5 + offset_y)] ^ temp[6]);
        y[(short)(1 + offset_y)] = (byte) (y[(short)(6 + offset_y)] ^ temp[7]);
        y[(short)(2 + offset_y)] = (byte) (y[(short)(7 + offset_y)] ^ temp[8]);
        y[(short)(3 + offset_y)] = (byte) (y[(short)(4 + offset_y)] ^ temp[5]);

        // PARTIE GAUCHE
        y[(short)(4 + offset_y)] = temp[9];
        y[(short)(5 + offset_y)] = temp[10];
        y[(short)(6 + offset_y)] = temp[11];
        y[(short)(7 + offset_y)] = temp[12];


    }
    public void decrypt(byte[] x,short offset_x)
    {
        short i;

        for (i = 31; i >= 0; i--)
        {
            OneRoundInv(x,output,(short)(i*4),offset_x);
        }
    }

    private LBlockCipher()
    {

    }
    public short process(byte type,byte[] data,short start_offset,short len_data)
    {
        Util.arrayCopy(data, start_offset, temp, (short) 16, len_data);
        switch(type)
        {
            case OFFSET_P1_ENC:
                encrypt(temp,(short)(16));
                Util.arrayCopy(temp,(short) 16, data, (short) start_offset, len_data);
                return (short)8;
            case OFFSET_P1_DEC:
                decrypt(temp,(short)(16));
                Util.arrayCopy(temp,(short) 16, data, (short) start_offset, len_data);
                return (short)8;
            case OFFSET_P1_GEN:
                keySchedule(temp,(short)(16));
                Util.arrayCopy(temp,(short) 16, data, (short) start_offset, len_data);
                return 10;
            default:
                return (short)-1;
        }

    }
    public static LBlockCipher getInstance()
    {
        if(m_instance_Cipher == null)
            m_instance_Cipher =  new LBlockCipher();
        return m_instance_Cipher;
    }

}

TestApplet.java

  public class TestApplet extends Applet 
            implements IConsts {
    private TestApplet()
    {   

    }

    public static void install(byte bArray[], short bOffset, byte bLength) throws ISOException {
        new TestApplet().register();
    }

    public void process(APDU apdu) throws ISOException {
        if (selectingApplet()) {
            return;
        }
        byte[] buf = apdu.getBuffer();
        if(buf[ISO7816.OFFSET_CLA] != IConsts.OFFSET_CLA_CIPHERS)
            ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
        switch (buf[ISO7816.OFFSET_INS]) 
        {
            case IConsts.OFFSET_INS_LIGHT:
                processLight(apdu);
                return;
            default:
                break;
        }
    }

    private void processLight(APDU apdu)
    {
         //cla and ins are proccessed
        byte[] buf = apdu.getBuffer();
        byte state = (buf[ISO7816.OFFSET_P1]);
        byte type = (buf[ISO7816.OFFSET_P2]);
        byte count_data = buf[ISO7816.OFFSET_LC];
        if(count_data == 0x00)
            ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
        short len_data = -1;
        switch(state)
        {
            case OFFSET_P1_ENC:
                switch(type)
                {
                    case TWINE_CIPHER_80:
                        TwineCipher m_instance = TwineCipher.getInstance(TwineCipher.TWINE_CIPHER_80);
                        len_data  = m_instance.process(OFFSET_P1_ENC, buf, (short)(ISO7816.OFFSET_CDATA), count_data);
                        apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, len_data);
                        return;
                    case TWINE_CIPHER_128:
                        TwineCipher.getInstance(TwineCipher.TWINE_CIPHER_80); //TODO change that
                        return;
                    case LBLOCK_CIPHER:
                        LBlockCipher m_instance_lblock= LBlockCipher.getInstance();
                        len_data  = m_instance_lblock.process(OFFSET_P1_ENC, buf, (short)(ISO7816.OFFSET_CDATA), count_data);
                        apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, len_data);
                        return;
                    default:
                        ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
                }
            case OFFSET_P1_DEC:
                switch(type)
                {
                    case TwineCipher.TWINE_CIPHER_80:
                        TwineCipher m_instance = TwineCipher.getInstance(TwineCipher.TWINE_CIPHER_80);
                        len_data  = m_instance.process(TwineCipher.OFFSET_P1_DEC, buf, (short)(ISO7816.OFFSET_CDATA), count_data);
                        apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, len_data);
                        return;
                    case TwineCipher.TWINE_CIPHER_128:
                        TwineCipher.getInstance(TwineCipher.TWINE_CIPHER_80); //TODO change that
                        return;
                    case LBLOCK_CIPHER:
                        LBlockCipher m_instance_lblock= LBlockCipher.getInstance();
                        len_data  = m_instance_lblock.process(OFFSET_P1_DEC, buf, (short)(ISO7816.OFFSET_CDATA), count_data);
                        apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, len_data);
                        return;
                    default:
                        ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
                }
            case OFFSET_P1_GEN:
                switch(type)
                {
                    case TwineCipher.TWINE_CIPHER_80:
                        TwineCipher m_instance = TwineCipher.getInstance(TwineCipher.TWINE_CIPHER_80);
                        len_data = m_instance.process(TwineCipher.OFFSET_P1_GEN, buf, (short)(ISO7816.OFFSET_CDATA), count_data);
                        apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, len_data);
                        return;
                    case TwineCipher.TWINE_CIPHER_128:
                        TwineCipher.getInstance(TwineCipher.TWINE_CIPHER_80); //TODO change that
                        return;
                    case LBLOCK_CIPHER:
                        LBlockCipher m_instance_lblock= LBlockCipher.getInstance();
                        len_data  = m_instance_lblock.process(OFFSET_P1_GEN, buf, (short)(ISO7816.OFFSET_CDATA), count_data);
                        apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, len_data);
                        return;
                    default:
                        ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
                }
                default:
                    break;
        }
    }

}

Понравилась статья? Поделить с друзьями:
  • 9cb2 ошибка bmw e60
  • A communication error occurred operation timed out the web server may be down
  • A client log file containing error information has been generated in terraria
  • 9cb1 ошибка bmw
  • A call to a d3d12 api failed with d3d hresult error code 887a0005