[
  {
    "path": ".gitignore",
    "content": ".DS_Store\n/bin/\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"ext/ant\"]\n\tpath = ext/ant\n\turl = https://github.com/martinpaljak/ant-javacard.git\n"
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "Gauss Key Card\n==============\n\n*Gauss Key Card* is a [Java Card][] applet that implements the minimal\nworking subset of the [Tesla Key Card Protocol][]. Supported Java Card\nimplementations that load this application will be able to be paired\nwith a compatible vehicle and subsequently unlock, start, or lock the\nvehicle in the same way you would with an official key card. ([video][])\n\nIf at this point you can't imagine why you might ever want to use this\napplet, then it is not for you.\n\n[Java Card]: https://en.wikipedia.org/wiki/Java_Card\n[Tesla Key Card Protocol]: https://gist.github.com/darconeous/2cd2de11148e3a75685940158bddf933\n[video]: https://www.youtube.com/watch?v=QBP_Hjlpwjs\n\n## Caveats ##\n\nTHIS APPLET IS INTENDED FOR EXPERIMENTAL USE ONLY. IT HAS NOT BEEN\nREVIEWED, CHECKED, APPROVED, OR ENDORSED BY TESLA. IT MAY BE BLOCKED\nBY TESLA AT ANY TIME.\n\nBY USING THIS APPLET (OR INSTALLING IT TO A CARD FOR SOMEONE ELSE\nTO USE) YOU ASSUME ALL RESPONSIBILITY, RISK, AND LIABILITY FOR THE\nUSE OR MISUSE OF THIS SOFTWARE. SEE [LICENSE AGREEMENT](./LICENSE)\nFOR MORE INFORMATION.\n\nThere are some serious caveats that need to be well understood before\nusing this applet:\n\n### Type-A vs. Type-B ###\n\nISO/IEC 14443 defines two types of contactless devices: Type-A and Type-B.\nThere are javacards available in both varieties, and this applet will\nblissfully allow itself to be installed onto either type. However, *Tesla\nvehicles currently ignore type-B cards*, so make sure that your card is\nindeed a 14443 type-A card.\n\n### Maximum Frame Size ###\n\nThe maximum frame size (FSC) for the card must be 96 bytes or greater.\nThis corresponds to a FSCI value of 6 or greater. **Any card with an FSCI\nof 5 or less will not work**.\n\nTesla vehicles will ignore the FSCI field of the ATS, which means that it\nwill not attempt to break up larger frames if the indicated FSCI is small (<6).\nSpecifically, **the card MUST be able to properly handle receiving the\nauthenticate APDU (86 bytes) in a single frame**. If a card advertises\nan FSCI smaller than 6 then it is unlikely to be able to satisfy this\nrequirement.\n\nFor example, smart cards with DESFire EV1 emulation support have an\nFSCI of 5, and will unfortunately choke if they receive a frame larger\nthan 64 bytes. Such cards are not able to be used as Tesla Key Cards.\n\n> NOTE: In earlier versions of this document, this behavior was confused with\n> the NFC UID length. It just happened to be the case that most of the\n> 4-byte UID cards the author tested also had an FCI of 5. There is no\n> limitation of the length of the UID on the card imposed by the vehicle.\n\nA list of tested cards can be found [here](https://github.com/darconeous/gauss-key-card/wiki/Recommended-Cards).\n\n### Software updates could make this applet useless ###\n\nOfficial Tesla Key Cards have an attestation certificate, which means\nthat Tesla could easily block non-Tesla key cards from pairing with\nvehicles at any point in the future via a software update. Keys\nalready paired with a vehicle *might* continue to work in such a\nscenario, but there are no guarantees.\n\nSince there is no publicly available comprehensive documentation for\nthe Tesla Key Card Protocol, what is known was determined through\nobserving the interactions between the vehicle and an official Tesla\nKey Card. Gauss Key Card supports all commands that are currently\nbeing used by the vehicle during pairing and authentication, but there\nare several additional commands that are not supported because there\nwas not enough context to infer what their purpose might be. If Tesla\nat some point enables additional functionality or features which\nrequire those commands, existing Gauss Key Cards would be unable to\nparticipate.\n\n### Updating GaussKeyCard Applet Will Break Pairing\n\nIf you decide to upgrade the version of GaussKeyCard on your card\nto a new version, the pairing will be broken because a new internal\nprivate key will be generated for the card.\n\n## Security ##\n\nTo increase the difficulty of cloning, the private value of the ECDH\nkey pair is generated on-card when the applet is installed and never\nleaves the secure element. No mechanism for externally supplying a\nprivate key with a known value is provided by this implementation.\n\nAvoid buying Tesla Key Cards from anyone other than Tesla---the card\nmay be have weak or known private keys. Authentic Tesla Key Cards\nshould be safe to buy or use from anyone, but until the vehicle\nactually verifies attestation certificates there is no way to be sure.\nUntil then you should always assume that whoever sold you a key card\nmight also have the ability to unlock and start any vehicle you\nsubsequently pair with the card.\n\n## Smartcard Requirements ##\n\n * Java Card 2.2.2 (or later)\n * Contactless ISO/IEC 14443 **Type-A** interface (NFC)\n * **FSCI must be 6 or larger.** (Must support frame sizes of at least 96 bytes)\n * Must support [`KeyAgreement.ALG_EC_SVDP_DH`][]\n * Must support [`Cipher.ALG_AES_BLOCK_128_ECB_NOPAD`][]\n * [Known card management keys][], so you can actually load the applet\n\n[`KeyAgreement.ALG_EC_SVDP_DH`]: https://docs.oracle.com/javacard/3.0.5/api/javacard/security/KeyAgreement.html#ALG_EC_SVDP_DH\n[`Cipher.ALG_AES_BLOCK_128_ECB_NOPAD`]: https://docs.oracle.com/javacard/3.0.5/api/javacardx/crypto/Cipher.html#ALG_AES_BLOCK_128_ECB_NOPAD\n[Known card management keys]: https://github.com/martinpaljak/GlobalPlatformPro/wiki/Keys\n\nA list of tested cards can be found [here](https://github.com/darconeous/gauss-key-card/wiki/Recommended-Cards).\n\n## Installing/Uninstalling ##\n\nYou can download a pre-built CAP file on the [project release page][];\n\n[project release page]: https://github.com/darconeous/gauss-key-card/releases\n\nTo install the applet to a supported Java Card *with default card\nmanagement keys*, use [GlobalPlatformPro](https://github.com/martinpaljak/GlobalPlatformPro):\n\n```\n$ gp -install bin/GaussKeyCard.cap\n```\n\nUninstalling is similar:\n\n```\n$ gp -uninstall bin/GaussKeyCard.cap\n```\n\n## Building ##\n\n1. Install `ant`.\n   * macOS/homebrew: Run `brew install ant`\n2. Run `git submodule init`\n3. Run `git submodule update --recursive`\n4. Run `ant`\n"
  },
  {
    "path": "build.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project name=\"Gauss Key Card Applet\" default=\"dist\" basedir=\".\">\n  <description>Builds the project.</description>\n\n  <target name=\"dist\" description=\"generate the distribution\">\n    <tstamp/>\n    <get src=\"https://github.com/martinpaljak/ant-javacard/releases/download/18.09.25/ant-javacard.jar\" dest=\"ext/ant/\" skipexisting=\"true\"/>\n\t<!-- <ant dir=\"ext/ant\"/> -->\n    <!-- Create the distribution directory -->\n    <taskdef name=\"javacard\" classname=\"pro.javacard.ant.JavaCard\" classpath=\"ext/ant/ant-javacard.jar\"/>\n    <javacard jckit=\"ext/ant/sdks/jc222_kit/\">\n      <cap aid=\"F465736C614C6F67696330303258\" output=\"bin/GaussKeyCard.cap\" sources=\"src\" classes=\"bin\" version=\"1.1\">\n        <applet class=\"io.github.darconeous.gausskeycard.GaussKeyCard\" aid=\"F465736C614C6F6769633030325801\"/>\n      </cap>\n    </javacard>\n  </target>\n\n  <target name=\"clean\" description=\"clean up\">\n    <!-- Delete the built applet -->\n    <delete dir=\"bin\"/>\n  </target>\n\n</project>\n"
  },
  {
    "path": "src/io/github/darconeous/gausskeycard/ECP256.java",
    "content": "package io.github.darconeous.gausskeycard;\n\nimport javacard.security.ECKey;\nimport javacard.security.ECPrivateKey;\nimport javacard.security.ECPublicKey;\nimport javacard.security.KeyBuilder;\nimport javacard.security.KeyPair;\n\n/** Class for creating NIST P-256 keys. */\npublic class ECP256 {\n\tpublic static final short PRIVATE_KEY_LENGTH = 256;\n\n\tpublic static final byte[] p = {\n\t    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x0,\n\t    (byte)0x0, (byte)0x0, (byte)0x1, (byte)0x0, (byte)0x0, (byte)0x0,\n\t    (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0,\n\t    (byte)0x0, (byte)0x0, (byte)0x0, (byte)0xff, (byte)0xff, (byte)0xff,\n\t    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,\n\t    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff\n\t};\n\n\tpublic static final byte[] a = {\n\t    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x0,\n\t    (byte)0x0, (byte)0x0, (byte)0x1, (byte)0x0, (byte)0x0, (byte)0x0,\n\t    (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0,\n\t    (byte)0x0, (byte)0x0, (byte)0x0, (byte)0xff, (byte)0xff, (byte)0xff,\n\t    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,\n\t    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xfc\n\t};\n\n\tpublic static final byte[] b = {\n\t    (byte)0x5a, (byte)0xc6, (byte)0x35, (byte)0xd8, (byte)0xaa,\n\t    (byte)0x3a, (byte)0x93, (byte)0xe7, (byte)0xb3, (byte)0xeb,\n\t    (byte)0xbd, (byte)0x55, (byte)0x76, (byte)0x98, (byte)0x86,\n\t    (byte)0xbc, (byte)0x65, (byte)0x1d, (byte)0x6, (byte)0xb0,\n\t    (byte)0xcc, (byte)0x53, (byte)0xb0, (byte)0xf6, (byte)0x3b,\n\t    (byte)0xce, (byte)0x3c, (byte)0x3e, (byte)0x27, (byte)0xd2,\n\t    (byte)0x60, (byte)0x4b\n\t};\n\n\tpublic static final byte[] r = {\n\t    (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0x00,\n\t    (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xFF, (byte)0xFF,\n\t    (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,\n\t    (byte)0xFF, (byte)0xBC, (byte)0xE6, (byte)0xFA, (byte)0xAD,\n\t    (byte)0xA7, (byte)0x17, (byte)0x9E, (byte)0x84, (byte)0xF3,\n\t    (byte)0xB9, (byte)0xCA, (byte)0xC2, (byte)0xFC, (byte)0x63,\n\t    (byte)0x25, (byte)0x51\n\t};\n\n\tpublic static final byte[] g = {\n\t    (byte)0x4, (byte)0x6b, (byte)0x17, (byte)0xd1, (byte)0xf2,\n\t    (byte)0xe1, (byte)0x2c, (byte)0x42, (byte)0x47, (byte)0xf8,\n\t    (byte)0xbc, (byte)0xe6, (byte)0xe5, (byte)0x63, (byte)0xa4,\n\t    (byte)0x40, (byte)0xf2, (byte)0x77, (byte)0x3, (byte)0x7d,\n\t    (byte)0x81, (byte)0x2d, (byte)0xeb, (byte)0x33, (byte)0xa0,\n\t    (byte)0xf4, (byte)0xa1, (byte)0x39, (byte)0x45, (byte)0xd8,\n\t    (byte)0x98, (byte)0xc2, (byte)0x96, (byte)0x4f, (byte)0xe3,\n\t    (byte)0x42, (byte)0xe2, (byte)0xfe, (byte)0x1a, (byte)0x7f,\n\t    (byte)0x9b, (byte)0x8e, (byte)0xe7, (byte)0xeb, (byte)0x4a,\n\t    (byte)0x7c, (byte)0xf, (byte)0x9e, (byte)0x16, (byte)0x2b,\n\t    (byte)0xce, (byte)0x33, (byte)0x57, (byte)0x6b, (byte)0x31,\n\t    (byte)0x5e, (byte)0xce, (byte)0xcb, (byte)0xb6, (byte)0x40,\n\t    (byte)0x68, (byte)0x37, (byte)0xbf, (byte)0x51, (byte)0xf5\n\t};\n\n\tpublic static void setCurveParameters(ECKey eckey) {\n\t\teckey.setFieldFP(p, (short)0, (short)(p.length));\n\t\teckey.setA(a, (short)0, (short)(a.length));\n\t\teckey.setB(b, (short)0, (short)(b.length));\n\t\teckey.setG(g, (short)0, (short)(g.length));\n\t\teckey.setR(r, (short)0, (short)(r.length));\n\t}\n\n\tpublic static KeyPair newKeyPair(boolean keyEncryption) {\n\t\tfinal ECPrivateKey ecPriv;\n\t\tfinal ECPublicKey ecPub;\n\n\t\tecPriv = (ECPrivateKey)KeyBuilder.buildKey(\n\t\t\tKeyBuilder.TYPE_EC_FP_PRIVATE,\n\t\t\tPRIVATE_KEY_LENGTH,\n\t\t\tkeyEncryption\n\t\t);\n\n\t\tecPub = (ECPublicKey)KeyBuilder.buildKey(\n\t\t\tKeyBuilder.TYPE_EC_FP_PUBLIC,\n\t\t\tPRIVATE_KEY_LENGTH,\n\t\t\tkeyEncryption\n\t\t);\n\n\t\tECP256.setCurveParameters(ecPriv);\n\t\tECP256.setCurveParameters(ecPub);\n\n\t\treturn new KeyPair(ecPub, ecPriv);\n\t}\n}\n"
  },
  {
    "path": "src/io/github/darconeous/gausskeycard/GaussKeyCard.java",
    "content": "package io.github.darconeous.gausskeycard;\n\nimport javacard.framework.APDU;\nimport javacard.framework.Applet;\nimport javacard.framework.ISO7816;\nimport javacard.framework.ISOException;\nimport javacard.security.AESKey;\nimport javacard.security.CryptoException;\nimport javacard.security.ECPrivateKey;\nimport javacard.security.ECPublicKey;\nimport javacard.security.KeyAgreement;\nimport javacard.security.KeyBuilder;\nimport javacard.security.KeyPair;\nimport javacard.security.RandomData;\nimport javacardx.crypto.Cipher;\n\npublic class GaussKeyCard extends Applet\n{\n\t/* Card commands we support. */\n\tprivate static final byte INS_GET_PUBLIC_KEY = (byte)0x04;\n\tprivate static final byte INS_AUTHENTICATE = (byte)0x11;\n\tprivate static final byte INS_GET_CARD_INFO = (byte)0x14;\n\n\tprivate static final short OFFSET_CHALLENGE = (short)(ISO7816.OFFSET_CDATA + 65);\n\n\t// Constants from JavaCard 3.x. This way we can still install on\n\t// JC 2.2.2 cards and fall back to the traditional behavior.\n\tprivate static final byte TYPE_AES_TRANSIENT_DESELECT = 14;\n\tprivate static final byte TYPE_AES_TRANSIENT_RESET = 13;\n\n\tprivate final KeyPair key1;\n\tprivate final KeyAgreement ecdh;\n\tprivate final Cipher aes_ecb;\n\tprivate final AESKey aes_key;\n\tprivate final RandomData rng;\n\n\tpublic static void\n\tinstall(byte[] info, short off, byte len)\n\t{\n\t\tfinal GaussKeyCard applet = new GaussKeyCard();\n\t\tapplet.register();\n\t}\n\n\tprotected\n\tGaussKeyCard()\n\t{\n\t\tkey1 = ECP256.newKeyPair(false);\n\n\t\tkey1.genKeyPair();\n\n\t\tecdh = KeyAgreement.getInstance(KeyAgreement.ALG_EC_SVDP_DH, false);\n\n\t\tecdh.init(key1.getPrivate());\n\n\t\taes_ecb = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_ECB_NOPAD, false);\n\n\t\tAESKey key = null;\n\n\t\ttry {\n\t\t\t// Put the AES key in RAM if we can.\n\t\t\tkey = (AESKey)KeyBuilder.buildKey(TYPE_AES_TRANSIENT_DESELECT, KeyBuilder.LENGTH_AES_128, false);\n\t\t} catch (CryptoException e) {\n\t\t\ttry {\n\t\t\t\t// This will use a bit more RAM, but\n\t\t\t\t// at least it isn't using flash.\n\t\t\t\tkey = (AESKey)KeyBuilder.buildKey(TYPE_AES_TRANSIENT_RESET, KeyBuilder.LENGTH_AES_128, false);\n\t\t\t} catch (CryptoException x) {\n\t\t\t\t// Uggh. This will wear out the flash\n\t\t\t\t// eventually, but we don't have a better option.\n\t\t\t\tkey = (AESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_128, false);\n\t\t\t}\n\t\t}\n\n\t\taes_key = key;\n\n\t\t// We shouldn't require high-strength random numbers\n\t\t// for calculating the challenge salt.\n\t\trng = RandomData.getInstance(RandomData.ALG_PSEUDO_RANDOM);\n\t}\n\n\tpublic void\n\tprocess(APDU apdu)\n\t{\n\t\tfinal byte[] buffer = apdu.getBuffer();\n\n\t\tif (selectingApplet()) {\n\t\t\treturn;\n\t\t}\n\n\t\t// We only support the proprietary class.\n\t\tif ((buffer[ISO7816.OFFSET_CLA] & (byte)0x80) != (byte)0x80) {\n\t\t\tISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (buffer[ISO7816.OFFSET_INS]) {\n\t\tcase INS_GET_PUBLIC_KEY:\n\t\t\tprocessGetPublicKey(apdu);\n\t\t\tbreak;\n\n\t\tcase INS_AUTHENTICATE:\n\t\t\tprocessAuthenticate(apdu);\n\t\t\tbreak;\n\n\t\tcase INS_GET_CARD_INFO:\n\t\t\tprocessGetCardInfo(apdu);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);\n\t\t}\n\t}\n\n\tprivate void\n\tprocessGetCardInfo(APDU apdu)\n\t{\n\t\tfinal byte[] buffer = apdu.getBuffer();\n\t\tfinal short le = apdu.setOutgoing();\n\n\t\tshort len = 0;\n\t\tbuffer[len++] = 0x00;\n\t\tbuffer[len++] = 0x01;\n\n\t\tlen = le > 0 ? (le > len ? len : le) : len;\n\t\tapdu.setOutgoingLength(len);\n\t\tapdu.sendBytes((short)0, len);\n\t}\n\n\tprivate void\n\tprocessGetPublicKey(APDU apdu)\n\t{\n\t\tfinal byte[] buffer = apdu.getBuffer();\n\n\t\tfinal short le = apdu.setOutgoing();\n\n\t\tfinal ECPublicKey epubk = (ECPublicKey)key1.getPublic();\n\n\t\tshort len = epubk.getW(buffer, (short)0);\n\n\t\tlen = le > 0 ? (le > len ? len : le) : len;\n\t\tapdu.setOutgoingLength(len);\n\t\tapdu.sendBytes((short)0, len);\n\t}\n\n\tprivate void\n\tprocessAuthenticate(APDU apdu)\n\t{\n\t\tfinal byte[] buffer = apdu.getBuffer();\n\t\tfinal short incomingLength = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);\n\n\t\tif (incomingLength < (short)0x51) {\n\t\t\tISOException.throwIt(ISO7816.SW_WRONG_LENGTH);\n\t\t}\n\n\t\tecdh.generateSecret(buffer, ISO7816.OFFSET_CDATA, (short)65, buffer, (short)16);\n\n\t\taes_key.setKey(buffer, (short)16);\n\t\taes_ecb.init(aes_key, Cipher.MODE_ENCRYPT);\n\n\t\t// Generate the random salt.\n\t\trng.generateData(buffer, OFFSET_CHALLENGE, (short)4);\n\n\t\tshort len = aes_ecb.doFinal(buffer, OFFSET_CHALLENGE, (short)16, buffer, (short)0);\n\t\tfinal short le = apdu.setOutgoing();\n\n\t\tlen = le > 0 ? (le > len ? len : le) : len;\n\t\tapdu.setOutgoingLength(len);\n\t\tapdu.sendBytes((short)0, len);\n\t}\n}\n"
  }
]