Full Code of darconeous/gauss-key-card for AI

master 5555081e4871 cached
7 files
26.3 KB
7.4k tokens
10 symbols
1 requests
Download .txt
Repository: darconeous/gauss-key-card
Branch: master
Commit: 5555081e4871
Files: 7
Total size: 26.3 KB

Directory structure:
gitextract_tdvdpbfu/

├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── build.xml
└── src/
    └── io/
        └── github/
            └── darconeous/
                └── gausskeycard/
                    ├── ECP256.java
                    └── GaussKeyCard.java

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
.DS_Store
/bin/


================================================
FILE: .gitmodules
================================================
[submodule "ext/ant"]
	path = ext/ant
	url = https://github.com/martinpaljak/ant-javacard.git


================================================
FILE: LICENSE
================================================

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
Gauss Key Card
==============

*Gauss Key Card* is a [Java Card][] applet that implements the minimal
working subset of the [Tesla Key Card Protocol][]. Supported Java Card
implementations that load this application will be able to be paired
with a compatible vehicle and subsequently unlock, start, or lock the
vehicle in the same way you would with an official key card. ([video][])

If at this point you can't imagine why you might ever want to use this
applet, then it is not for you.

[Java Card]: https://en.wikipedia.org/wiki/Java_Card
[Tesla Key Card Protocol]: https://gist.github.com/darconeous/2cd2de11148e3a75685940158bddf933
[video]: https://www.youtube.com/watch?v=QBP_Hjlpwjs

## Caveats ##

THIS APPLET IS INTENDED FOR EXPERIMENTAL USE ONLY. IT HAS NOT BEEN
REVIEWED, CHECKED, APPROVED, OR ENDORSED BY TESLA. IT MAY BE BLOCKED
BY TESLA AT ANY TIME.

BY USING THIS APPLET (OR INSTALLING IT TO A CARD FOR SOMEONE ELSE
TO USE) YOU ASSUME ALL RESPONSIBILITY, RISK, AND LIABILITY FOR THE
USE OR MISUSE OF THIS SOFTWARE. SEE [LICENSE AGREEMENT](./LICENSE)
FOR MORE INFORMATION.

There are some serious caveats that need to be well understood before
using this applet:

### Type-A vs. Type-B ###

ISO/IEC 14443 defines two types of contactless devices: Type-A and Type-B.
There are javacards available in both varieties, and this applet will
blissfully allow itself to be installed onto either type. However, *Tesla
vehicles currently ignore type-B cards*, so make sure that your card is
indeed a 14443 type-A card.

### Maximum Frame Size ###

The maximum frame size (FSC) for the card must be 96 bytes or greater.
This corresponds to a FSCI value of 6 or greater. **Any card with an FSCI
of 5 or less will not work**.

Tesla vehicles will ignore the FSCI field of the ATS, which means that it
will not attempt to break up larger frames if the indicated FSCI is small (<6).
Specifically, **the card MUST be able to properly handle receiving the
authenticate APDU (86 bytes) in a single frame**. If a card advertises
an FSCI smaller than 6 then it is unlikely to be able to satisfy this
requirement.

For example, smart cards with DESFire EV1 emulation support have an
FSCI of 5, and will unfortunately choke if they receive a frame larger
than 64 bytes. Such cards are not able to be used as Tesla Key Cards.

> NOTE: In earlier versions of this document, this behavior was confused with
> the NFC UID length. It just happened to be the case that most of the
> 4-byte UID cards the author tested also had an FCI of 5. There is no
> limitation of the length of the UID on the card imposed by the vehicle.

A list of tested cards can be found [here](https://github.com/darconeous/gauss-key-card/wiki/Recommended-Cards).

### Software updates could make this applet useless ###

Official Tesla Key Cards have an attestation certificate, which means
that Tesla could easily block non-Tesla key cards from pairing with
vehicles at any point in the future via a software update. Keys
already paired with a vehicle *might* continue to work in such a
scenario, but there are no guarantees.

Since there is no publicly available comprehensive documentation for
the Tesla Key Card Protocol, what is known was determined through
observing the interactions between the vehicle and an official Tesla
Key Card. Gauss Key Card supports all commands that are currently
being used by the vehicle during pairing and authentication, but there
are several additional commands that are not supported because there
was not enough context to infer what their purpose might be. If Tesla
at some point enables additional functionality or features which
require those commands, existing Gauss Key Cards would be unable to
participate.

### Updating GaussKeyCard Applet Will Break Pairing

If you decide to upgrade the version of GaussKeyCard on your card
to a new version, the pairing will be broken because a new internal
private key will be generated for the card.

## Security ##

To increase the difficulty of cloning, the private value of the ECDH
key pair is generated on-card when the applet is installed and never
leaves the secure element. No mechanism for externally supplying a
private key with a known value is provided by this implementation.

Avoid buying Tesla Key Cards from anyone other than Tesla---the card
may be have weak or known private keys. Authentic Tesla Key Cards
should be safe to buy or use from anyone, but until the vehicle
actually verifies attestation certificates there is no way to be sure.
Until then you should always assume that whoever sold you a key card
might also have the ability to unlock and start any vehicle you
subsequently pair with the card.

## Smartcard Requirements ##

 * Java Card 2.2.2 (or later)
 * Contactless ISO/IEC 14443 **Type-A** interface (NFC)
 * **FSCI must be 6 or larger.** (Must support frame sizes of at least 96 bytes)
 * Must support [`KeyAgreement.ALG_EC_SVDP_DH`][]
 * Must support [`Cipher.ALG_AES_BLOCK_128_ECB_NOPAD`][]
 * [Known card management keys][], so you can actually load the applet

[`KeyAgreement.ALG_EC_SVDP_DH`]: https://docs.oracle.com/javacard/3.0.5/api/javacard/security/KeyAgreement.html#ALG_EC_SVDP_DH
[`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
[Known card management keys]: https://github.com/martinpaljak/GlobalPlatformPro/wiki/Keys

A list of tested cards can be found [here](https://github.com/darconeous/gauss-key-card/wiki/Recommended-Cards).

## Installing/Uninstalling ##

You can download a pre-built CAP file on the [project release page][];

[project release page]: https://github.com/darconeous/gauss-key-card/releases

To install the applet to a supported Java Card *with default card
management keys*, use [GlobalPlatformPro](https://github.com/martinpaljak/GlobalPlatformPro):

```
$ gp -install bin/GaussKeyCard.cap
```

Uninstalling is similar:

```
$ gp -uninstall bin/GaussKeyCard.cap
```

## Building ##

1. Install `ant`.
   * macOS/homebrew: Run `brew install ant`
2. Run `git submodule init`
3. Run `git submodule update --recursive`
4. Run `ant`


================================================
FILE: build.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project name="Gauss Key Card Applet" default="dist" basedir=".">
  <description>Builds the project.</description>

  <target name="dist" description="generate the distribution">
    <tstamp/>
    <get src="https://github.com/martinpaljak/ant-javacard/releases/download/18.09.25/ant-javacard.jar" dest="ext/ant/" skipexisting="true"/>
	<!-- <ant dir="ext/ant"/> -->
    <!-- Create the distribution directory -->
    <taskdef name="javacard" classname="pro.javacard.ant.JavaCard" classpath="ext/ant/ant-javacard.jar"/>
    <javacard jckit="ext/ant/sdks/jc222_kit/">
      <cap aid="F465736C614C6F67696330303258" output="bin/GaussKeyCard.cap" sources="src" classes="bin" version="1.1">
        <applet class="io.github.darconeous.gausskeycard.GaussKeyCard" aid="F465736C614C6F6769633030325801"/>
      </cap>
    </javacard>
  </target>

  <target name="clean" description="clean up">
    <!-- Delete the built applet -->
    <delete dir="bin"/>
  </target>

</project>


================================================
FILE: src/io/github/darconeous/gausskeycard/ECP256.java
================================================
package io.github.darconeous.gausskeycard;

import javacard.security.ECKey;
import javacard.security.ECPrivateKey;
import javacard.security.ECPublicKey;
import javacard.security.KeyBuilder;
import javacard.security.KeyPair;

/** Class for creating NIST P-256 keys. */
public class ECP256 {
	public static final short PRIVATE_KEY_LENGTH = 256;

	public static final byte[] p = {
	    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x0,
	    (byte)0x0, (byte)0x0, (byte)0x1, (byte)0x0, (byte)0x0, (byte)0x0,
	    (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0,
	    (byte)0x0, (byte)0x0, (byte)0x0, (byte)0xff, (byte)0xff, (byte)0xff,
	    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
	    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff
	};

	public static final byte[] a = {
	    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x0,
	    (byte)0x0, (byte)0x0, (byte)0x1, (byte)0x0, (byte)0x0, (byte)0x0,
	    (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0,
	    (byte)0x0, (byte)0x0, (byte)0x0, (byte)0xff, (byte)0xff, (byte)0xff,
	    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
	    (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xfc
	};

	public static final byte[] b = {
	    (byte)0x5a, (byte)0xc6, (byte)0x35, (byte)0xd8, (byte)0xaa,
	    (byte)0x3a, (byte)0x93, (byte)0xe7, (byte)0xb3, (byte)0xeb,
	    (byte)0xbd, (byte)0x55, (byte)0x76, (byte)0x98, (byte)0x86,
	    (byte)0xbc, (byte)0x65, (byte)0x1d, (byte)0x6, (byte)0xb0,
	    (byte)0xcc, (byte)0x53, (byte)0xb0, (byte)0xf6, (byte)0x3b,
	    (byte)0xce, (byte)0x3c, (byte)0x3e, (byte)0x27, (byte)0xd2,
	    (byte)0x60, (byte)0x4b
	};

	public static final byte[] r = {
	    (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0x00,
	    (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xFF, (byte)0xFF,
	    (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
	    (byte)0xFF, (byte)0xBC, (byte)0xE6, (byte)0xFA, (byte)0xAD,
	    (byte)0xA7, (byte)0x17, (byte)0x9E, (byte)0x84, (byte)0xF3,
	    (byte)0xB9, (byte)0xCA, (byte)0xC2, (byte)0xFC, (byte)0x63,
	    (byte)0x25, (byte)0x51
	};

	public static final byte[] g = {
	    (byte)0x4, (byte)0x6b, (byte)0x17, (byte)0xd1, (byte)0xf2,
	    (byte)0xe1, (byte)0x2c, (byte)0x42, (byte)0x47, (byte)0xf8,
	    (byte)0xbc, (byte)0xe6, (byte)0xe5, (byte)0x63, (byte)0xa4,
	    (byte)0x40, (byte)0xf2, (byte)0x77, (byte)0x3, (byte)0x7d,
	    (byte)0x81, (byte)0x2d, (byte)0xeb, (byte)0x33, (byte)0xa0,
	    (byte)0xf4, (byte)0xa1, (byte)0x39, (byte)0x45, (byte)0xd8,
	    (byte)0x98, (byte)0xc2, (byte)0x96, (byte)0x4f, (byte)0xe3,
	    (byte)0x42, (byte)0xe2, (byte)0xfe, (byte)0x1a, (byte)0x7f,
	    (byte)0x9b, (byte)0x8e, (byte)0xe7, (byte)0xeb, (byte)0x4a,
	    (byte)0x7c, (byte)0xf, (byte)0x9e, (byte)0x16, (byte)0x2b,
	    (byte)0xce, (byte)0x33, (byte)0x57, (byte)0x6b, (byte)0x31,
	    (byte)0x5e, (byte)0xce, (byte)0xcb, (byte)0xb6, (byte)0x40,
	    (byte)0x68, (byte)0x37, (byte)0xbf, (byte)0x51, (byte)0xf5
	};

	public static void setCurveParameters(ECKey eckey) {
		eckey.setFieldFP(p, (short)0, (short)(p.length));
		eckey.setA(a, (short)0, (short)(a.length));
		eckey.setB(b, (short)0, (short)(b.length));
		eckey.setG(g, (short)0, (short)(g.length));
		eckey.setR(r, (short)0, (short)(r.length));
	}

	public static KeyPair newKeyPair(boolean keyEncryption) {
		final ECPrivateKey ecPriv;
		final ECPublicKey ecPub;

		ecPriv = (ECPrivateKey)KeyBuilder.buildKey(
			KeyBuilder.TYPE_EC_FP_PRIVATE,
			PRIVATE_KEY_LENGTH,
			keyEncryption
		);

		ecPub = (ECPublicKey)KeyBuilder.buildKey(
			KeyBuilder.TYPE_EC_FP_PUBLIC,
			PRIVATE_KEY_LENGTH,
			keyEncryption
		);

		ECP256.setCurveParameters(ecPriv);
		ECP256.setCurveParameters(ecPub);

		return new KeyPair(ecPub, ecPriv);
	}
}


================================================
FILE: src/io/github/darconeous/gausskeycard/GaussKeyCard.java
================================================
package io.github.darconeous.gausskeycard;

import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.security.AESKey;
import javacard.security.CryptoException;
import javacard.security.ECPrivateKey;
import javacard.security.ECPublicKey;
import javacard.security.KeyAgreement;
import javacard.security.KeyBuilder;
import javacard.security.KeyPair;
import javacard.security.RandomData;
import javacardx.crypto.Cipher;

public class GaussKeyCard extends Applet
{
	/* Card commands we support. */
	private static final byte INS_GET_PUBLIC_KEY = (byte)0x04;
	private static final byte INS_AUTHENTICATE = (byte)0x11;
	private static final byte INS_GET_CARD_INFO = (byte)0x14;

	private static final short OFFSET_CHALLENGE = (short)(ISO7816.OFFSET_CDATA + 65);

	// Constants from JavaCard 3.x. This way we can still install on
	// JC 2.2.2 cards and fall back to the traditional behavior.
	private static final byte TYPE_AES_TRANSIENT_DESELECT = 14;
	private static final byte TYPE_AES_TRANSIENT_RESET = 13;

	private final KeyPair key1;
	private final KeyAgreement ecdh;
	private final Cipher aes_ecb;
	private final AESKey aes_key;
	private final RandomData rng;

	public static void
	install(byte[] info, short off, byte len)
	{
		final GaussKeyCard applet = new GaussKeyCard();
		applet.register();
	}

	protected
	GaussKeyCard()
	{
		key1 = ECP256.newKeyPair(false);

		key1.genKeyPair();

		ecdh = KeyAgreement.getInstance(KeyAgreement.ALG_EC_SVDP_DH, false);

		ecdh.init(key1.getPrivate());

		aes_ecb = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_ECB_NOPAD, false);

		AESKey key = null;

		try {
			// Put the AES key in RAM if we can.
			key = (AESKey)KeyBuilder.buildKey(TYPE_AES_TRANSIENT_DESELECT, KeyBuilder.LENGTH_AES_128, false);
		} catch (CryptoException e) {
			try {
				// This will use a bit more RAM, but
				// at least it isn't using flash.
				key = (AESKey)KeyBuilder.buildKey(TYPE_AES_TRANSIENT_RESET, KeyBuilder.LENGTH_AES_128, false);
			} catch (CryptoException x) {
				// Uggh. This will wear out the flash
				// eventually, but we don't have a better option.
				key = (AESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_128, false);
			}
		}

		aes_key = key;

		// We shouldn't require high-strength random numbers
		// for calculating the challenge salt.
		rng = RandomData.getInstance(RandomData.ALG_PSEUDO_RANDOM);
	}

	public void
	process(APDU apdu)
	{
		final byte[] buffer = apdu.getBuffer();

		if (selectingApplet()) {
			return;
		}

		// We only support the proprietary class.
		if ((buffer[ISO7816.OFFSET_CLA] & (byte)0x80) != (byte)0x80) {
			ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
			return;
		}

		switch (buffer[ISO7816.OFFSET_INS]) {
		case INS_GET_PUBLIC_KEY:
			processGetPublicKey(apdu);
			break;

		case INS_AUTHENTICATE:
			processAuthenticate(apdu);
			break;

		case INS_GET_CARD_INFO:
			processGetCardInfo(apdu);
			break;

		default:
			ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
		}
	}

	private void
	processGetCardInfo(APDU apdu)
	{
		final byte[] buffer = apdu.getBuffer();
		final short le = apdu.setOutgoing();

		short len = 0;
		buffer[len++] = 0x00;
		buffer[len++] = 0x01;

		len = le > 0 ? (le > len ? len : le) : len;
		apdu.setOutgoingLength(len);
		apdu.sendBytes((short)0, len);
	}

	private void
	processGetPublicKey(APDU apdu)
	{
		final byte[] buffer = apdu.getBuffer();

		final short le = apdu.setOutgoing();

		final ECPublicKey epubk = (ECPublicKey)key1.getPublic();

		short len = epubk.getW(buffer, (short)0);

		len = le > 0 ? (le > len ? len : le) : len;
		apdu.setOutgoingLength(len);
		apdu.sendBytes((short)0, len);
	}

	private void
	processAuthenticate(APDU apdu)
	{
		final byte[] buffer = apdu.getBuffer();
		final short incomingLength = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);

		if (incomingLength < (short)0x51) {
			ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
		}

		ecdh.generateSecret(buffer, ISO7816.OFFSET_CDATA, (short)65, buffer, (short)16);

		aes_key.setKey(buffer, (short)16);
		aes_ecb.init(aes_key, Cipher.MODE_ENCRYPT);

		// Generate the random salt.
		rng.generateData(buffer, OFFSET_CHALLENGE, (short)4);

		short len = aes_ecb.doFinal(buffer, OFFSET_CHALLENGE, (short)16, buffer, (short)0);
		final short le = apdu.setOutgoing();

		len = le > 0 ? (le > len ? len : le) : len;
		apdu.setOutgoingLength(len);
		apdu.sendBytes((short)0, len);
	}
}
Download .txt
gitextract_tdvdpbfu/

├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── build.xml
└── src/
    └── io/
        └── github/
            └── darconeous/
                └── gausskeycard/
                    ├── ECP256.java
                    └── GaussKeyCard.java
Download .txt
SYMBOL INDEX (10 symbols across 2 files)

FILE: src/io/github/darconeous/gausskeycard/ECP256.java
  class ECP256 (line 10) | public class ECP256 {
    method setCurveParameters (line 67) | public static void setCurveParameters(ECKey eckey) {
    method newKeyPair (line 75) | public static KeyPair newKeyPair(boolean keyEncryption) {

FILE: src/io/github/darconeous/gausskeycard/GaussKeyCard.java
  class GaussKeyCard (line 17) | public class GaussKeyCard extends Applet
    method install (line 37) | public static void
    method GaussKeyCard (line 44) | protected
    method process (line 81) | public void
    method processGetCardInfo (line 114) | private void
    method processGetPublicKey (line 129) | private void
    method processAuthenticate (line 145) | private void
Condensed preview — 7 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (28K chars).
[
  {
    "path": ".gitignore",
    "chars": 16,
    "preview": ".DS_Store\n/bin/\n"
  },
  {
    "path": ".gitmodules",
    "chars": 94,
    "preview": "[submodule \"ext/ant\"]\n\tpath = ext/ant\n\turl = https://github.com/martinpaljak/ant-javacard.git\n"
  },
  {
    "path": "LICENSE",
    "chars": 11358,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "README.md",
    "chars": 6146,
    "preview": "Gauss Key Card\n==============\n\n*Gauss Key Card* is a [Java Card][] applet that implements the minimal\nworking subset of "
  },
  {
    "path": "build.xml",
    "chars": 1008,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project name=\"Gauss Key Card Applet\" default=\"dist\" basedir=\".\">\n  <description>"
  },
  {
    "path": "src/io/github/darconeous/gausskeycard/ECP256.java",
    "chars": 3784,
    "preview": "package io.github.darconeous.gausskeycard;\n\nimport javacard.security.ECKey;\nimport javacard.security.ECPrivateKey;\nimpor"
  },
  {
    "path": "src/io/github/darconeous/gausskeycard/GaussKeyCard.java",
    "chars": 4509,
    "preview": "package io.github.darconeous.gausskeycard;\n\nimport javacard.framework.APDU;\nimport javacard.framework.Applet;\nimport jav"
  }
]

About this extraction

This page contains the full source code of the darconeous/gauss-key-card GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 7 files (26.3 KB), approximately 7.4k tokens, and a symbol index with 10 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!