Merge pull request #2186 from open-keychain/apdu-refactor
Refactor OpenPGP applet communication code
This commit is contained in:
@@ -1,605 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
|
|
||||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
|
||||||
*
|
|
||||||
* This code is free software; you can redistribute it and/or modify it
|
|
||||||
* under the terms of the GNU General Public License version 2 only, as
|
|
||||||
* published by the Free Software Foundation. Oracle designates this
|
|
||||||
* particular file as subject to the "Classpath" exception as provided
|
|
||||||
* by Oracle in the LICENSE file that accompanied this code.
|
|
||||||
*
|
|
||||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
|
||||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
||||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
||||||
* version 2 for more details (a copy is included in the LICENSE file that
|
|
||||||
* accompanied this code).
|
|
||||||
*
|
|
||||||
* You should have received a copy of the GNU General Public License version
|
|
||||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
|
||||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
||||||
*
|
|
||||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
|
||||||
* or visit www.oracle.com if you need additional information or have any
|
|
||||||
* questions.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package javax.smartcardio;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A command APDU following the structure defined in ISO/IEC 7816-4.
|
|
||||||
* It consists of a four byte header and a conditional body of variable length.
|
|
||||||
* This class does not attempt to verify that the APDU encodes a semantically
|
|
||||||
* valid command.
|
|
||||||
*
|
|
||||||
* <p>Note that when the expected length of the response APDU is specified
|
|
||||||
* in the {@linkplain #CommandAPDU(int,int,int,int,int) constructors},
|
|
||||||
* the actual length (Ne) must be specified, not its
|
|
||||||
* encoded form (Le). Similarly, {@linkplain #getNe} returns the actual
|
|
||||||
* value Ne. In other words, a value of 0 means "no data in the response APDU"
|
|
||||||
* rather than "maximum length."
|
|
||||||
*
|
|
||||||
* <p>This class supports both the short and extended forms of length
|
|
||||||
* encoding for Ne and Nc. However, note that not all terminals and Smart Cards
|
|
||||||
* are capable of accepting APDUs that use the extended form.
|
|
||||||
*
|
|
||||||
* <p>For the header bytes CLA, INS, P1, and P2 the Java type <code>int</code>
|
|
||||||
* is used to represent the 8 bit unsigned values. In the constructors, only
|
|
||||||
* the 8 lowest bits of the <code>int</code> value specified by the application
|
|
||||||
* are significant. The accessor methods always return the byte as an unsigned
|
|
||||||
* value between 0 and 255.
|
|
||||||
*
|
|
||||||
* <p>Instances of this class are immutable. Where data is passed in or out
|
|
||||||
* via byte arrays, defensive cloning is performed.
|
|
||||||
*
|
|
||||||
* @see ResponseAPDU
|
|
||||||
*
|
|
||||||
* @since 1.6
|
|
||||||
* @author Andreas Sterbenz
|
|
||||||
* @author JSR 268 Expert Group
|
|
||||||
*/
|
|
||||||
public final class CommandAPDU implements java.io.Serializable {
|
|
||||||
|
|
||||||
private static final long serialVersionUID = 398698301286670877L;
|
|
||||||
|
|
||||||
private static final int MAX_APDU_SIZE = 65544;
|
|
||||||
|
|
||||||
/** @serial */
|
|
||||||
private byte[] apdu;
|
|
||||||
|
|
||||||
// value of nc
|
|
||||||
private transient int nc;
|
|
||||||
|
|
||||||
// value of ne
|
|
||||||
private transient int ne;
|
|
||||||
|
|
||||||
// index of start of data within the apdu array
|
|
||||||
private transient int dataOffset;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a CommandAPDU from a byte array containing the complete
|
|
||||||
* APDU contents (header and body).
|
|
||||||
*
|
|
||||||
* <p>Note that the apdu bytes are copied to protect against
|
|
||||||
* subsequent modification.
|
|
||||||
*
|
|
||||||
* @param apdu the complete command APDU
|
|
||||||
*
|
|
||||||
* @throws NullPointerException if apdu is null
|
|
||||||
* @throws IllegalArgumentException if apdu does not contain a valid
|
|
||||||
* command APDU
|
|
||||||
*/
|
|
||||||
public CommandAPDU(byte[] apdu) {
|
|
||||||
this.apdu = apdu.clone();
|
|
||||||
parse();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a CommandAPDU from a byte array containing the complete
|
|
||||||
* APDU contents (header and body). The APDU starts at the index
|
|
||||||
* <code>apduOffset</code> in the byte array and is <code>apduLength</code>
|
|
||||||
* bytes long.
|
|
||||||
*
|
|
||||||
* <p>Note that the apdu bytes are copied to protect against
|
|
||||||
* subsequent modification.
|
|
||||||
*
|
|
||||||
* @param apdu the complete command APDU
|
|
||||||
* @param apduOffset the offset in the byte array at which the apdu
|
|
||||||
* data begins
|
|
||||||
* @param apduLength the length of the APDU
|
|
||||||
*
|
|
||||||
* @throws NullPointerException if apdu is null
|
|
||||||
* @throws IllegalArgumentException if apduOffset or apduLength are
|
|
||||||
* negative or if apduOffset + apduLength are greater than apdu.length,
|
|
||||||
* or if the specified bytes are not a valid APDU
|
|
||||||
*/
|
|
||||||
public CommandAPDU(byte[] apdu, int apduOffset, int apduLength) {
|
|
||||||
checkArrayBounds(apdu, apduOffset, apduLength);
|
|
||||||
this.apdu = new byte[apduLength];
|
|
||||||
System.arraycopy(apdu, apduOffset, this.apdu, 0, apduLength);
|
|
||||||
parse();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void checkArrayBounds(byte[] b, int ofs, int len) {
|
|
||||||
if ((ofs < 0) || (len < 0)) {
|
|
||||||
throw new IllegalArgumentException
|
|
||||||
("Offset and length must not be negative");
|
|
||||||
}
|
|
||||||
if (b == null) {
|
|
||||||
if ((ofs != 0) && (len != 0)) {
|
|
||||||
throw new IllegalArgumentException
|
|
||||||
("offset and length must be 0 if array is null");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (ofs > b.length - len) {
|
|
||||||
throw new IllegalArgumentException
|
|
||||||
("Offset plus length exceed array size");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a CommandAPDU from the ByteBuffer containing the complete APDU
|
|
||||||
* contents (header and body).
|
|
||||||
* The buffer's <code>position</code> must be set to the start of the APDU,
|
|
||||||
* its <code>limit</code> to the end of the APDU. Upon return, the buffer's
|
|
||||||
* <code>position</code> is equal to its limit; its limit remains unchanged.
|
|
||||||
*
|
|
||||||
* <p>Note that the data in the ByteBuffer is copied to protect against
|
|
||||||
* subsequent modification.
|
|
||||||
*
|
|
||||||
* @param apdu the ByteBuffer containing the complete APDU
|
|
||||||
*
|
|
||||||
* @throws NullPointerException if apdu is null
|
|
||||||
* @throws IllegalArgumentException if apdu does not contain a valid
|
|
||||||
* command APDU
|
|
||||||
*/
|
|
||||||
public CommandAPDU(ByteBuffer apdu) {
|
|
||||||
this.apdu = new byte[apdu.remaining()];
|
|
||||||
apdu.get(this.apdu);
|
|
||||||
parse();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a CommandAPDU from the four header bytes. This is case 1
|
|
||||||
* in ISO 7816, no command body.
|
|
||||||
*
|
|
||||||
* @param cla the class byte CLA
|
|
||||||
* @param ins the instruction byte INS
|
|
||||||
* @param p1 the parameter byte P1
|
|
||||||
* @param p2 the parameter byte P2
|
|
||||||
*/
|
|
||||||
public CommandAPDU(int cla, int ins, int p1, int p2) {
|
|
||||||
this(cla, ins, p1, p2, null, 0, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a CommandAPDU from the four header bytes and the expected
|
|
||||||
* response data length. This is case 2 in ISO 7816, empty command data
|
|
||||||
* field with Ne specified. If Ne is 0, the APDU is encoded as ISO 7816
|
|
||||||
* case 1.
|
|
||||||
*
|
|
||||||
* @param cla the class byte CLA
|
|
||||||
* @param ins the instruction byte INS
|
|
||||||
* @param p1 the parameter byte P1
|
|
||||||
* @param p2 the parameter byte P2
|
|
||||||
* @param ne the maximum number of expected data bytes in a response APDU
|
|
||||||
*
|
|
||||||
* @throws IllegalArgumentException if ne is negative or greater than
|
|
||||||
* 65536
|
|
||||||
*/
|
|
||||||
public CommandAPDU(int cla, int ins, int p1, int p2, int ne) {
|
|
||||||
this(cla, ins, p1, p2, null, 0, 0, ne);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a CommandAPDU from the four header bytes and command data.
|
|
||||||
* This is case 3 in ISO 7816, command data present and Ne absent. The
|
|
||||||
* value Nc is taken as data.length. If <code>data</code> is null or
|
|
||||||
* its length is 0, the APDU is encoded as ISO 7816 case 1.
|
|
||||||
*
|
|
||||||
* <p>Note that the data bytes are copied to protect against
|
|
||||||
* subsequent modification.
|
|
||||||
*
|
|
||||||
* @param cla the class byte CLA
|
|
||||||
* @param ins the instruction byte INS
|
|
||||||
* @param p1 the parameter byte P1
|
|
||||||
* @param p2 the parameter byte P2
|
|
||||||
* @param data the byte array containing the data bytes of the command body
|
|
||||||
*
|
|
||||||
* @throws IllegalArgumentException if data.length is greater than 65535
|
|
||||||
*/
|
|
||||||
public CommandAPDU(int cla, int ins, int p1, int p2, byte[] data) {
|
|
||||||
this(cla, ins, p1, p2, data, 0, arrayLength(data), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a CommandAPDU from the four header bytes and command data.
|
|
||||||
* This is case 3 in ISO 7816, command data present and Ne absent. The
|
|
||||||
* value Nc is taken as dataLength. If <code>dataLength</code>
|
|
||||||
* is 0, the APDU is encoded as ISO 7816 case 1.
|
|
||||||
*
|
|
||||||
* <p>Note that the data bytes are copied to protect against
|
|
||||||
* subsequent modification.
|
|
||||||
*
|
|
||||||
* @param cla the class byte CLA
|
|
||||||
* @param ins the instruction byte INS
|
|
||||||
* @param p1 the parameter byte P1
|
|
||||||
* @param p2 the parameter byte P2
|
|
||||||
* @param data the byte array containing the data bytes of the command body
|
|
||||||
* @param dataOffset the offset in the byte array at which the data
|
|
||||||
* bytes of the command body begin
|
|
||||||
* @param dataLength the number of the data bytes in the command body
|
|
||||||
*
|
|
||||||
* @throws NullPointerException if data is null and dataLength is not 0
|
|
||||||
* @throws IllegalArgumentException if dataOffset or dataLength are
|
|
||||||
* negative or if dataOffset + dataLength are greater than data.length
|
|
||||||
* or if dataLength is greater than 65535
|
|
||||||
*/
|
|
||||||
public CommandAPDU(int cla, int ins, int p1, int p2, byte[] data,
|
|
||||||
int dataOffset, int dataLength) {
|
|
||||||
this(cla, ins, p1, p2, data, dataOffset, dataLength, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a CommandAPDU from the four header bytes, command data,
|
|
||||||
* and expected response data length. This is case 4 in ISO 7816,
|
|
||||||
* command data and Ne present. The value Nc is taken as data.length
|
|
||||||
* if <code>data</code> is non-null and as 0 otherwise. If Ne or Nc
|
|
||||||
* are zero, the APDU is encoded as case 1, 2, or 3 per ISO 7816.
|
|
||||||
*
|
|
||||||
* <p>Note that the data bytes are copied to protect against
|
|
||||||
* subsequent modification.
|
|
||||||
*
|
|
||||||
* @param cla the class byte CLA
|
|
||||||
* @param ins the instruction byte INS
|
|
||||||
* @param p1 the parameter byte P1
|
|
||||||
* @param p2 the parameter byte P2
|
|
||||||
* @param data the byte array containing the data bytes of the command body
|
|
||||||
* @param ne the maximum number of expected data bytes in a response APDU
|
|
||||||
*
|
|
||||||
* @throws IllegalArgumentException if data.length is greater than 65535
|
|
||||||
* or if ne is negative or greater than 65536
|
|
||||||
*/
|
|
||||||
public CommandAPDU(int cla, int ins, int p1, int p2, byte[] data, int ne) {
|
|
||||||
this(cla, ins, p1, p2, data, 0, arrayLength(data), ne);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int arrayLength(byte[] b) {
|
|
||||||
return (b != null) ? b.length : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Command APDU encoding options:
|
|
||||||
*
|
|
||||||
* case 1: |CLA|INS|P1 |P2 | len = 4
|
|
||||||
* case 2s: |CLA|INS|P1 |P2 |LE | len = 5
|
|
||||||
* case 3s: |CLA|INS|P1 |P2 |LC |...BODY...| len = 6..260
|
|
||||||
* case 4s: |CLA|INS|P1 |P2 |LC |...BODY...|LE | len = 7..261
|
|
||||||
* case 2e: |CLA|INS|P1 |P2 |00 |LE1|LE2| len = 7
|
|
||||||
* case 3e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...| len = 8..65542
|
|
||||||
* case 4e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...|LE1|LE2| len =10..65544
|
|
||||||
*
|
|
||||||
* LE, LE1, LE2 may be 0x00.
|
|
||||||
* LC must not be 0x00 and LC1|LC2 must not be 0x00|0x00
|
|
||||||
*/
|
|
||||||
private void parse() {
|
|
||||||
if (apdu.length < 4) {
|
|
||||||
throw new IllegalArgumentException("apdu must be at least 4 bytes long");
|
|
||||||
}
|
|
||||||
if (apdu.length == 4) {
|
|
||||||
// case 1
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
int l1 = apdu[4] & 0xff;
|
|
||||||
if (apdu.length == 5) {
|
|
||||||
// case 2s
|
|
||||||
this.ne = (l1 == 0) ? 256 : l1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (l1 != 0) {
|
|
||||||
if (apdu.length == 4 + 1 + l1) {
|
|
||||||
// case 3s
|
|
||||||
this.nc = l1;
|
|
||||||
this.dataOffset = 5;
|
|
||||||
return;
|
|
||||||
} else if (apdu.length == 4 + 2 + l1) {
|
|
||||||
// case 4s
|
|
||||||
this.nc = l1;
|
|
||||||
this.dataOffset = 5;
|
|
||||||
int l2 = apdu[apdu.length - 1] & 0xff;
|
|
||||||
this.ne = (l2 == 0) ? 256 : l2;
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
throw new IllegalArgumentException
|
|
||||||
("Invalid APDU: length=" + apdu.length + ", b1=" + l1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (apdu.length < 7) {
|
|
||||||
throw new IllegalArgumentException
|
|
||||||
("Invalid APDU: length=" + apdu.length + ", b1=" + l1);
|
|
||||||
}
|
|
||||||
int l2 = ((apdu[5] & 0xff) << 8) | (apdu[6] & 0xff);
|
|
||||||
if (apdu.length == 7) {
|
|
||||||
// case 2e
|
|
||||||
this.ne = (l2 == 0) ? 65536 : l2;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (l2 == 0) {
|
|
||||||
throw new IllegalArgumentException("Invalid APDU: length="
|
|
||||||
+ apdu.length + ", b1=" + l1 + ", b2||b3=" + l2);
|
|
||||||
}
|
|
||||||
if (apdu.length == 4 + 3 + l2) {
|
|
||||||
// case 3e
|
|
||||||
this.nc = l2;
|
|
||||||
this.dataOffset = 7;
|
|
||||||
return;
|
|
||||||
} else if (apdu.length == 4 + 5 + l2) {
|
|
||||||
// case 4e
|
|
||||||
this.nc = l2;
|
|
||||||
this.dataOffset = 7;
|
|
||||||
int leOfs = apdu.length - 2;
|
|
||||||
int l3 = ((apdu[leOfs] & 0xff) << 8) | (apdu[leOfs + 1] & 0xff);
|
|
||||||
this.ne = (l3 == 0) ? 65536 : l3;
|
|
||||||
} else {
|
|
||||||
throw new IllegalArgumentException("Invalid APDU: length="
|
|
||||||
+ apdu.length + ", b1=" + l1 + ", b2||b3=" + l2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a CommandAPDU from the four header bytes, command data,
|
|
||||||
* and expected response data length. This is case 4 in ISO 7816,
|
|
||||||
* command data and Le present. The value Nc is taken as
|
|
||||||
* <code>dataLength</code>.
|
|
||||||
* If Ne or Nc
|
|
||||||
* are zero, the APDU is encoded as case 1, 2, or 3 per ISO 7816.
|
|
||||||
*
|
|
||||||
* <p>Note that the data bytes are copied to protect against
|
|
||||||
* subsequent modification.
|
|
||||||
*
|
|
||||||
* @param cla the class byte CLA
|
|
||||||
* @param ins the instruction byte INS
|
|
||||||
* @param p1 the parameter byte P1
|
|
||||||
* @param p2 the parameter byte P2
|
|
||||||
* @param data the byte array containing the data bytes of the command body
|
|
||||||
* @param dataOffset the offset in the byte array at which the data
|
|
||||||
* bytes of the command body begin
|
|
||||||
* @param dataLength the number of the data bytes in the command body
|
|
||||||
* @param ne the maximum number of expected data bytes in a response APDU
|
|
||||||
*
|
|
||||||
* @throws NullPointerException if data is null and dataLength is not 0
|
|
||||||
* @throws IllegalArgumentException if dataOffset or dataLength are
|
|
||||||
* negative or if dataOffset + dataLength are greater than data.length,
|
|
||||||
* or if ne is negative or greater than 65536,
|
|
||||||
* or if dataLength is greater than 65535
|
|
||||||
*/
|
|
||||||
public CommandAPDU(int cla, int ins, int p1, int p2, byte[] data,
|
|
||||||
int dataOffset, int dataLength, int ne) {
|
|
||||||
checkArrayBounds(data, dataOffset, dataLength);
|
|
||||||
if (dataLength > 65535) {
|
|
||||||
throw new IllegalArgumentException("dataLength is too large");
|
|
||||||
}
|
|
||||||
if (ne < 0) {
|
|
||||||
throw new IllegalArgumentException("ne must not be negative");
|
|
||||||
}
|
|
||||||
if (ne > 65536) {
|
|
||||||
throw new IllegalArgumentException("ne is too large");
|
|
||||||
}
|
|
||||||
this.ne = ne;
|
|
||||||
this.nc = dataLength;
|
|
||||||
if (dataLength == 0) {
|
|
||||||
if (ne == 0) {
|
|
||||||
// case 1
|
|
||||||
this.apdu = new byte[4];
|
|
||||||
setHeader(cla, ins, p1, p2);
|
|
||||||
} else {
|
|
||||||
// case 2s or 2e
|
|
||||||
if (ne <= 256) {
|
|
||||||
// case 2s
|
|
||||||
// 256 is encoded as 0x00
|
|
||||||
byte len = (ne != 256) ? (byte)ne : 0;
|
|
||||||
this.apdu = new byte[5];
|
|
||||||
setHeader(cla, ins, p1, p2);
|
|
||||||
this.apdu[4] = len;
|
|
||||||
} else {
|
|
||||||
// case 2e
|
|
||||||
byte l1, l2;
|
|
||||||
// 65536 is encoded as 0x00 0x00
|
|
||||||
if (ne == 65536) {
|
|
||||||
l1 = 0;
|
|
||||||
l2 = 0;
|
|
||||||
} else {
|
|
||||||
l1 = (byte)(ne >> 8);
|
|
||||||
l2 = (byte)ne;
|
|
||||||
}
|
|
||||||
this.apdu = new byte[7];
|
|
||||||
setHeader(cla, ins, p1, p2);
|
|
||||||
this.apdu[5] = l1;
|
|
||||||
this.apdu[6] = l2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (ne == 0) {
|
|
||||||
// case 3s or 3e
|
|
||||||
if (dataLength <= 255) {
|
|
||||||
// case 3s
|
|
||||||
apdu = new byte[4 + 1 + dataLength];
|
|
||||||
setHeader(cla, ins, p1, p2);
|
|
||||||
apdu[4] = (byte)dataLength;
|
|
||||||
this.dataOffset = 5;
|
|
||||||
System.arraycopy(data, dataOffset, apdu, 5, dataLength);
|
|
||||||
} else {
|
|
||||||
// case 3e
|
|
||||||
apdu = new byte[4 + 3 + dataLength];
|
|
||||||
setHeader(cla, ins, p1, p2);
|
|
||||||
apdu[4] = 0;
|
|
||||||
apdu[5] = (byte)(dataLength >> 8);
|
|
||||||
apdu[6] = (byte)dataLength;
|
|
||||||
this.dataOffset = 7;
|
|
||||||
System.arraycopy(data, dataOffset, apdu, 7, dataLength);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// case 4s or 4e
|
|
||||||
if ((dataLength <= 255) && (ne <= 256)) {
|
|
||||||
// case 4s
|
|
||||||
apdu = new byte[4 + 2 + dataLength];
|
|
||||||
setHeader(cla, ins, p1, p2);
|
|
||||||
apdu[4] = (byte)dataLength;
|
|
||||||
this.dataOffset = 5;
|
|
||||||
System.arraycopy(data, dataOffset, apdu, 5, dataLength);
|
|
||||||
apdu[apdu.length - 1] = (ne != 256) ? (byte)ne : 0;
|
|
||||||
} else {
|
|
||||||
// case 4e
|
|
||||||
apdu = new byte[4 + 5 + dataLength];
|
|
||||||
setHeader(cla, ins, p1, p2);
|
|
||||||
apdu[4] = 0;
|
|
||||||
apdu[5] = (byte)(dataLength >> 8);
|
|
||||||
apdu[6] = (byte)dataLength;
|
|
||||||
this.dataOffset = 7;
|
|
||||||
System.arraycopy(data, dataOffset, apdu, 7, dataLength);
|
|
||||||
if (ne != 65536) {
|
|
||||||
int leOfs = apdu.length - 2;
|
|
||||||
apdu[leOfs] = (byte)(ne >> 8);
|
|
||||||
apdu[leOfs + 1] = (byte)ne;
|
|
||||||
} // else le == 65536: no need to fill in, encoded as 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setHeader(int cla, int ins, int p1, int p2) {
|
|
||||||
apdu[0] = (byte)cla;
|
|
||||||
apdu[1] = (byte)ins;
|
|
||||||
apdu[2] = (byte)p1;
|
|
||||||
apdu[3] = (byte)p2;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the class byte CLA.
|
|
||||||
*
|
|
||||||
* @return the value of the class byte CLA.
|
|
||||||
*/
|
|
||||||
public int getCLA() {
|
|
||||||
return apdu[0] & 0xff;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the instruction byte INS.
|
|
||||||
*
|
|
||||||
* @return the value of the instruction byte INS.
|
|
||||||
*/
|
|
||||||
public int getINS() {
|
|
||||||
return apdu[1] & 0xff;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the parameter byte P1.
|
|
||||||
*
|
|
||||||
* @return the value of the parameter byte P1.
|
|
||||||
*/
|
|
||||||
public int getP1() {
|
|
||||||
return apdu[2] & 0xff;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the parameter byte P2.
|
|
||||||
*
|
|
||||||
* @return the value of the parameter byte P2.
|
|
||||||
*/
|
|
||||||
public int getP2() {
|
|
||||||
return apdu[3] & 0xff;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the number of data bytes in the command body (Nc) or 0 if this
|
|
||||||
* APDU has no body. This call is equivalent to
|
|
||||||
* <code>getData().length</code>.
|
|
||||||
*
|
|
||||||
* @return the number of data bytes in the command body or 0 if this APDU
|
|
||||||
* has no body.
|
|
||||||
*/
|
|
||||||
public int getNc() {
|
|
||||||
return nc;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a copy of the data bytes in the command body. If this APDU as
|
|
||||||
* no body, this method returns a byte array with length zero.
|
|
||||||
*
|
|
||||||
* @return a copy of the data bytes in the command body or the empty
|
|
||||||
* byte array if this APDU has no body.
|
|
||||||
*/
|
|
||||||
public byte[] getData() {
|
|
||||||
byte[] data = new byte[nc];
|
|
||||||
System.arraycopy(apdu, dataOffset, data, 0, nc);
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the maximum number of expected data bytes in a response
|
|
||||||
* APDU (Ne).
|
|
||||||
*
|
|
||||||
* @return the maximum number of expected data bytes in a response APDU.
|
|
||||||
*/
|
|
||||||
public int getNe() {
|
|
||||||
return ne;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a copy of the bytes in this APDU.
|
|
||||||
*
|
|
||||||
* @return a copy of the bytes in this APDU.
|
|
||||||
*/
|
|
||||||
public byte[] getBytes() {
|
|
||||||
return apdu.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a string representation of this command APDU.
|
|
||||||
*
|
|
||||||
* @return a String representation of this command APDU.
|
|
||||||
*/
|
|
||||||
public String toString() {
|
|
||||||
return "CommmandAPDU: " + apdu.length + " bytes, nc=" + nc + ", ne=" + ne;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compares the specified object with this command APDU for equality.
|
|
||||||
* Returns true if the given object is also a CommandAPDU and its bytes are
|
|
||||||
* identical to the bytes in this CommandAPDU.
|
|
||||||
*
|
|
||||||
* @param obj the object to be compared for equality with this command APDU
|
|
||||||
* @return true if the specified object is equal to this command APDU
|
|
||||||
*/
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (this == obj) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (obj instanceof CommandAPDU == false) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
CommandAPDU other = (CommandAPDU)obj;
|
|
||||||
return Arrays.equals(this.apdu, other.apdu);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the hash code value for this command APDU.
|
|
||||||
*
|
|
||||||
* @return the hash code value for this command APDU.
|
|
||||||
*/
|
|
||||||
public int hashCode() {
|
|
||||||
return Arrays.hashCode(apdu);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void readObject(java.io.ObjectInputStream in)
|
|
||||||
throws java.io.IOException, ClassNotFoundException {
|
|
||||||
apdu = (byte[])in.readUnshared();
|
|
||||||
// initialize transient fields
|
|
||||||
parse();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,184 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
|
|
||||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
|
||||||
*
|
|
||||||
* This code is free software; you can redistribute it and/or modify it
|
|
||||||
* under the terms of the GNU General Public License version 2 only, as
|
|
||||||
* published by the Free Software Foundation. Oracle designates this
|
|
||||||
* particular file as subject to the "Classpath" exception as provided
|
|
||||||
* by Oracle in the LICENSE file that accompanied this code.
|
|
||||||
*
|
|
||||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
|
||||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
||||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
||||||
* version 2 for more details (a copy is included in the LICENSE file that
|
|
||||||
* accompanied this code).
|
|
||||||
*
|
|
||||||
* You should have received a copy of the GNU General Public License version
|
|
||||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
|
||||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
||||||
*
|
|
||||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
|
||||||
* or visit www.oracle.com if you need additional information or have any
|
|
||||||
* questions.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package javax.smartcardio;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A response APDU as defined in ISO/IEC 7816-4. It consists of a conditional
|
|
||||||
* body and a two byte trailer.
|
|
||||||
* This class does not attempt to verify that the APDU encodes a semantically
|
|
||||||
* valid response.
|
|
||||||
*
|
|
||||||
* <p>Instances of this class are immutable. Where data is passed in or out
|
|
||||||
* via byte arrays, defensive cloning is performed.
|
|
||||||
*
|
|
||||||
* @see CommandAPDU
|
|
||||||
*
|
|
||||||
* @since 1.6
|
|
||||||
* @author Andreas Sterbenz
|
|
||||||
* @author JSR 268 Expert Group
|
|
||||||
*/
|
|
||||||
public final class ResponseAPDU implements java.io.Serializable {
|
|
||||||
|
|
||||||
private static final long serialVersionUID = 6962744978375594225L;
|
|
||||||
|
|
||||||
/** @serial */
|
|
||||||
private byte[] apdu;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a ResponseAPDU from a byte array containing the complete
|
|
||||||
* APDU contents (conditional body and trailed).
|
|
||||||
*
|
|
||||||
* <p>Note that the byte array is cloned to protect against subsequent
|
|
||||||
* modification.
|
|
||||||
*
|
|
||||||
* @param apdu the complete response APDU
|
|
||||||
*
|
|
||||||
* @throws NullPointerException if apdu is null
|
|
||||||
* @throws IllegalArgumentException if apdu.length is less than 2
|
|
||||||
*/
|
|
||||||
public ResponseAPDU(byte[] apdu) {
|
|
||||||
apdu = apdu.clone();
|
|
||||||
check(apdu);
|
|
||||||
this.apdu = apdu;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void check(byte[] apdu) {
|
|
||||||
if (apdu.length < 2) {
|
|
||||||
throw new IllegalArgumentException("apdu must be at least 2 bytes long");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the number of data bytes in the response body (Nr) or 0 if this
|
|
||||||
* APDU has no body. This call is equivalent to
|
|
||||||
* <code>getData().length</code>.
|
|
||||||
*
|
|
||||||
* @return the number of data bytes in the response body or 0 if this APDU
|
|
||||||
* has no body.
|
|
||||||
*/
|
|
||||||
public int getNr() {
|
|
||||||
return apdu.length - 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a copy of the data bytes in the response body. If this APDU as
|
|
||||||
* no body, this method returns a byte array with a length of zero.
|
|
||||||
*
|
|
||||||
* @return a copy of the data bytes in the response body or the empty
|
|
||||||
* byte array if this APDU has no body.
|
|
||||||
*/
|
|
||||||
public byte[] getData() {
|
|
||||||
byte[] data = new byte[apdu.length - 2];
|
|
||||||
System.arraycopy(apdu, 0, data, 0, data.length);
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the status byte SW1 as a value between 0 and 255.
|
|
||||||
*
|
|
||||||
* @return the value of the status byte SW1 as a value between 0 and 255.
|
|
||||||
*/
|
|
||||||
public int getSW1() {
|
|
||||||
return apdu[apdu.length - 2] & 0xff;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the status byte SW2 as a value between 0 and 255.
|
|
||||||
*
|
|
||||||
* @return the value of the status byte SW2 as a value between 0 and 255.
|
|
||||||
*/
|
|
||||||
public int getSW2() {
|
|
||||||
return apdu[apdu.length - 1] & 0xff;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the status bytes SW1 and SW2 as a single
|
|
||||||
* status word SW.
|
|
||||||
* It is defined as
|
|
||||||
* <code>(getSW1() << 8) | getSW2()</code>.
|
|
||||||
*
|
|
||||||
* @return the value of the status word SW.
|
|
||||||
*/
|
|
||||||
public int getSW() {
|
|
||||||
return (getSW1() << 8) | getSW2();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a copy of the bytes in this APDU.
|
|
||||||
*
|
|
||||||
* @return a copy of the bytes in this APDU.
|
|
||||||
*/
|
|
||||||
public byte[] getBytes() {
|
|
||||||
return apdu.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a string representation of this response APDU.
|
|
||||||
*
|
|
||||||
* @return a String representation of this response APDU.
|
|
||||||
*/
|
|
||||||
public String toString() {
|
|
||||||
return "ResponseAPDU: " + apdu.length + " bytes, SW="
|
|
||||||
+ Integer.toHexString(getSW());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compares the specified object with this response APDU for equality.
|
|
||||||
* Returns true if the given object is also a ResponseAPDU and its bytes are
|
|
||||||
* identical to the bytes in this ResponseAPDU.
|
|
||||||
*
|
|
||||||
* @param obj the object to be compared for equality with this response APDU
|
|
||||||
* @return true if the specified object is equal to this response APDU
|
|
||||||
*/
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (this == obj) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (obj instanceof ResponseAPDU == false) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
ResponseAPDU other = (ResponseAPDU)obj;
|
|
||||||
return Arrays.equals(this.apdu, other.apdu);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the hash code value for this response APDU.
|
|
||||||
*
|
|
||||||
* @return the hash code value for this response APDU.
|
|
||||||
*/
|
|
||||||
public int hashCode() {
|
|
||||||
return Arrays.hashCode(apdu);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void readObject(java.io.ObjectInputStream in)
|
|
||||||
throws java.io.IOException, ClassNotFoundException {
|
|
||||||
apdu = (byte[])in.readUnshared();
|
|
||||||
check(apdu);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -21,7 +21,8 @@ import org.sufficientlysecure.keychain.securitytoken.usb.UsbTransportException;
|
|||||||
|
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
|
|
||||||
public class CardCapabilities {
|
@SuppressWarnings("WeakerAccess")
|
||||||
|
class CardCapabilities {
|
||||||
private static final int MASK_CHAINING = 1 << 7;
|
private static final int MASK_CHAINING = 1 << 7;
|
||||||
private static final int MASK_EXTENDED = 1 << 6;
|
private static final int MASK_EXTENDED = 1 << 6;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2016 Vincent Breitmoser <look@my.amazin.horse>
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import com.google.auto.value.AutoValue;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A command APDU following the structure defined in ISO/IEC 7816-4.
|
||||||
|
* It consists of a four byte header and a conditional body of variable length.
|
||||||
|
*/
|
||||||
|
@AutoValue
|
||||||
|
public abstract class CommandApdu {
|
||||||
|
public abstract int getCLA();
|
||||||
|
public abstract int getINS();
|
||||||
|
public abstract int getP1();
|
||||||
|
public abstract int getP2();
|
||||||
|
public abstract byte[] getData();
|
||||||
|
public abstract int getNe();
|
||||||
|
|
||||||
|
public static CommandApdu create(byte[] apdu, int apduOffset, int apduLength) {
|
||||||
|
return fromBytes(Arrays.copyOfRange(apdu, apduOffset, apduOffset + apduLength));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandApdu create(int cla, int ins, int p1, int p2) {
|
||||||
|
return create(cla, ins, p1, p2, null, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandApdu create(int cla, int ins, int p1, int p2, int ne) {
|
||||||
|
return create(cla, ins, p1, p2, null, ne);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandApdu create(int cla, int ins, int p1, int p2, byte[] data) {
|
||||||
|
return create(cla, ins, p1, p2, data, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandApdu create(int cla, int ins, int p1, int p2, byte[] data, int dataOffset, int dataLength) {
|
||||||
|
if (data != null) {
|
||||||
|
data = Arrays.copyOfRange(data, dataOffset, dataOffset + dataLength);
|
||||||
|
}
|
||||||
|
return create(cla, ins, p1, p2, data, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandApdu create(int cla, int ins, int p1, int p2, byte[] data, int dataOffset, int dataLength,
|
||||||
|
int ne) {
|
||||||
|
if (data != null) {
|
||||||
|
data = Arrays.copyOfRange(data, dataOffset, dataOffset + dataLength);
|
||||||
|
}
|
||||||
|
return create(cla, ins, p1, p2, data, ne);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandApdu create(int cla, int ins, int p1, int p2, byte[] data, int ne) {
|
||||||
|
if (ne < 0) {
|
||||||
|
throw new IllegalArgumentException("ne must not be negative");
|
||||||
|
}
|
||||||
|
if (ne > 65536) {
|
||||||
|
throw new IllegalArgumentException("ne is too large");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data == null) {
|
||||||
|
data = new byte[0];
|
||||||
|
}
|
||||||
|
return new AutoValue_CommandApdu(cla, ins, p1, p2, data, ne);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandApdu fromBytes(byte[] apdu, int offset, int length) {
|
||||||
|
return fromBytes(Arrays.copyOfRange(apdu, offset, offset + length));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command APDU encoding options:
|
||||||
|
* <p>
|
||||||
|
* case 1: |CLA|INS|P1 |P2 | len = 4
|
||||||
|
* case 2s: |CLA|INS|P1 |P2 |LE | len = 5
|
||||||
|
* case 3s: |CLA|INS|P1 |P2 |LC |...BODY...| len = 6..260
|
||||||
|
* case 4s: |CLA|INS|P1 |P2 |LC |...BODY...|LE | len = 7..261
|
||||||
|
* case 2e: |CLA|INS|P1 |P2 |00 |LE1|LE2| len = 7
|
||||||
|
* case 3e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...| len = 8..65542
|
||||||
|
* case 4e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...|LE1|LE2| len =10..65544
|
||||||
|
* <p>
|
||||||
|
* LE, LE1, LE2 may be 0x00.
|
||||||
|
* LC must not be 0x00 and LC1|LC2 must not be 0x00|0x00
|
||||||
|
*/
|
||||||
|
public static CommandApdu fromBytes(byte[] apdu) {
|
||||||
|
if (apdu.length < 4) {
|
||||||
|
throw new IllegalArgumentException("apdu must be at least 4 bytes long");
|
||||||
|
}
|
||||||
|
|
||||||
|
int cla = apdu[0] & 0xff;
|
||||||
|
int ins = apdu[1] & 0xff;
|
||||||
|
int p1 = apdu[2] & 0xff;
|
||||||
|
int p2 = apdu[3] & 0xff;
|
||||||
|
final Integer dataOffset;
|
||||||
|
final Integer dataLength;
|
||||||
|
final int ne;
|
||||||
|
|
||||||
|
if (apdu.length == 4) {
|
||||||
|
// case 1
|
||||||
|
dataOffset = null;
|
||||||
|
dataLength = null;
|
||||||
|
ne = 0;
|
||||||
|
} else if (apdu.length == 5) {
|
||||||
|
// case 2s
|
||||||
|
dataOffset = null;
|
||||||
|
dataLength = null;
|
||||||
|
ne = (apdu[4] == 0) ? 256 : (apdu[4] & 0xff);
|
||||||
|
} else if (apdu[4] != 0) {
|
||||||
|
dataOffset = 5;
|
||||||
|
dataLength = apdu[4] & 0xff;
|
||||||
|
|
||||||
|
if (apdu.length == 4 + 1 + dataLength) {
|
||||||
|
// case 3s
|
||||||
|
ne = 0;
|
||||||
|
} else {
|
||||||
|
// case 4s
|
||||||
|
int l2 = apdu[apdu.length - 1] & 0xff;
|
||||||
|
ne = (l2 == 0) ? 256 : l2;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
int l2 = ((apdu[5] & 0xff) << 8) | (apdu[6] & 0xff);
|
||||||
|
if (apdu.length == 7) {
|
||||||
|
// case 2e
|
||||||
|
dataOffset = null;
|
||||||
|
dataLength = null;
|
||||||
|
ne = (l2 == 0) ? 65536 : l2;
|
||||||
|
} else {
|
||||||
|
dataOffset = 7;
|
||||||
|
dataLength = l2;
|
||||||
|
|
||||||
|
if (apdu.length == 4 + 3 + l2) {
|
||||||
|
// case 3e
|
||||||
|
ne = 0;
|
||||||
|
} else {
|
||||||
|
// case 4e
|
||||||
|
int leOfs = apdu.length - 2;
|
||||||
|
int le = ((apdu[leOfs] & 0xff) << 8) | (apdu[leOfs + 1] & 0xff);
|
||||||
|
ne = (le == 0) ? 65536 : le;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] data;
|
||||||
|
if (dataOffset != null) {
|
||||||
|
data = Arrays.copyOfRange(apdu, dataOffset, dataOffset + dataLength);
|
||||||
|
} else {
|
||||||
|
data = new byte[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return new AutoValue_CommandApdu(cla, ins, p1, p2, data, ne);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] toBytes() {
|
||||||
|
final byte[] apdu;
|
||||||
|
|
||||||
|
byte[] data = getData();
|
||||||
|
int ne = getNe();
|
||||||
|
if (data.length == 0) {
|
||||||
|
if (ne == 0) {
|
||||||
|
// case 1
|
||||||
|
apdu = new byte[4];
|
||||||
|
} else {
|
||||||
|
// case 2s or 2e
|
||||||
|
if (ne <= 256) {
|
||||||
|
// case 2s
|
||||||
|
apdu = new byte[5];
|
||||||
|
apdu[4] = (ne != 256) ? (byte) ne : 0;
|
||||||
|
} else {
|
||||||
|
// case 2e
|
||||||
|
apdu = new byte[7];
|
||||||
|
if (ne != 65536) {
|
||||||
|
apdu[5] = (byte) (ne >> 8);
|
||||||
|
apdu[6] = (byte) ne;
|
||||||
|
} else {
|
||||||
|
apdu[5] = 0;
|
||||||
|
apdu[6] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (ne == 0) {
|
||||||
|
// case 3s or 3e
|
||||||
|
if (data.length <= 255) {
|
||||||
|
// case 3s
|
||||||
|
apdu = new byte[4 + 1 + data.length];
|
||||||
|
apdu[4] = (byte) data.length;
|
||||||
|
System.arraycopy(data, 0, apdu, 5, data.length);
|
||||||
|
} else {
|
||||||
|
// case 3e
|
||||||
|
apdu = new byte[4 + 3 + data.length];
|
||||||
|
apdu[4] = 0;
|
||||||
|
apdu[5] = (byte) (data.length >> 8);
|
||||||
|
apdu[6] = (byte) data.length;
|
||||||
|
System.arraycopy(data, 0, apdu, 7, data.length);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (data.length <= 255 && ne <= 256) {
|
||||||
|
// case 4s
|
||||||
|
apdu = new byte[4 + 2 + data.length];
|
||||||
|
apdu[4] = (byte) data.length;
|
||||||
|
System.arraycopy(data, 0, apdu, 5, data.length);
|
||||||
|
apdu[apdu.length - 1] = (ne != 256) ? (byte) ne : 0;
|
||||||
|
} else {
|
||||||
|
// case 4e
|
||||||
|
apdu = new byte[4 + 5 + data.length];
|
||||||
|
apdu[4] = 0;
|
||||||
|
apdu[5] = (byte) (data.length >> 8);
|
||||||
|
apdu[6] = (byte) data.length;
|
||||||
|
System.arraycopy(data, 0, apdu, 7, data.length);
|
||||||
|
if (ne != 65536) {
|
||||||
|
apdu[apdu.length - 2] = (byte) (ne >> 8);
|
||||||
|
apdu[apdu.length - 1] = (byte) ne;
|
||||||
|
} else {
|
||||||
|
apdu[apdu.length - 2] = 0;
|
||||||
|
apdu[apdu.length - 1] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
apdu[0] = (byte) getCLA();
|
||||||
|
apdu[1] = (byte) getINS();
|
||||||
|
apdu[2] = (byte) getP1();
|
||||||
|
apdu[3] = (byte) getP2();
|
||||||
|
|
||||||
|
return apdu;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,18 +25,18 @@ import org.sufficientlysecure.keychain.ui.CreateSecurityTokenAlgorithmFragment;
|
|||||||
|
|
||||||
public abstract class KeyFormat {
|
public abstract class KeyFormat {
|
||||||
|
|
||||||
public enum KeyFormatType {
|
enum KeyFormatType {
|
||||||
RSAKeyFormatType,
|
RSAKeyFormatType,
|
||||||
ECKeyFormatType
|
ECKeyFormatType
|
||||||
};
|
}
|
||||||
|
|
||||||
private final KeyFormatType mKeyFormatType;
|
private final KeyFormatType mKeyFormatType;
|
||||||
|
|
||||||
public KeyFormat(final KeyFormatType keyFormatType) {
|
KeyFormat(final KeyFormatType keyFormatType) {
|
||||||
mKeyFormatType = keyFormatType;
|
mKeyFormatType = keyFormatType;
|
||||||
}
|
}
|
||||||
|
|
||||||
public final KeyFormatType keyFormatType() {
|
final KeyFormatType keyFormatType() {
|
||||||
return mKeyFormatType;
|
return mKeyFormatType;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,9 +18,10 @@
|
|||||||
package org.sufficientlysecure.keychain.securitytoken;
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
import android.nfc.Tag;
|
import android.nfc.Tag;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
import javax.smartcardio.CommandAPDU;
|
import org.bouncycastle.util.encoders.Hex;
|
||||||
import javax.smartcardio.ResponseAPDU;
|
import org.sufficientlysecure.keychain.Constants;
|
||||||
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
|
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -45,8 +46,18 @@ public class NfcTransport implements Transport {
|
|||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public ResponseAPDU transceive(final CommandAPDU data) throws IOException {
|
public ResponseApdu transceive(final CommandApdu data) throws IOException {
|
||||||
return new ResponseAPDU(mIsoCard.transceive(data.getBytes()));
|
byte[] rawCommand = data.toBytes();
|
||||||
|
if (Constants.DEBUG) {
|
||||||
|
Log.d(Constants.TAG, "nfc out: " + Hex.toHexString(rawCommand));
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] rawResponse = mIsoCard.transceive(rawCommand);
|
||||||
|
if (Constants.DEBUG) {
|
||||||
|
Log.d(Constants.TAG, "nfc in: " + Hex.toHexString(rawResponse));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseApdu.fromBytes(rawResponse);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -21,12 +21,12 @@ import java.io.IOException;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public class OpenPgpCapabilities {
|
@SuppressWarnings("unused") // just expose all included data
|
||||||
|
class OpenPgpCapabilities {
|
||||||
private final static int MASK_SM = 1 << 7;
|
private final static int MASK_SM = 1 << 7;
|
||||||
private final static int MASK_KEY_IMPORT = 1 << 5;
|
private final static int MASK_KEY_IMPORT = 1 << 5;
|
||||||
private final static int MASK_ATTRIBUTES_CHANGABLE = 1 << 2;
|
private final static int MASK_ATTRIBUTES_CHANGABLE = 1 << 2;
|
||||||
|
|
||||||
private boolean mPw1ValidForMultipleSignatures;
|
|
||||||
private byte[] mAid;
|
private byte[] mAid;
|
||||||
private byte[] mHistoricalBytes;
|
private byte[] mHistoricalBytes;
|
||||||
|
|
||||||
@@ -39,13 +39,15 @@ public class OpenPgpCapabilities {
|
|||||||
private int mMaxRspLen;
|
private int mMaxRspLen;
|
||||||
|
|
||||||
private Map<KeyType, KeyFormat> mKeyFormats;
|
private Map<KeyType, KeyFormat> mKeyFormats;
|
||||||
|
private byte[] mFingerprints;
|
||||||
|
private byte[] mPwStatusBytes;
|
||||||
|
|
||||||
public OpenPgpCapabilities(byte[] data) throws IOException {
|
OpenPgpCapabilities(byte[] data) throws IOException {
|
||||||
mKeyFormats = new HashMap<>();
|
mKeyFormats = new HashMap<>();
|
||||||
updateWithData(data);
|
updateWithData(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateWithData(byte[] data) throws IOException {
|
void updateWithData(byte[] data) throws IOException {
|
||||||
Iso7816TLV[] tlvs = Iso7816TLV.readList(data, true);
|
Iso7816TLV[] tlvs = Iso7816TLV.readList(data, true);
|
||||||
if (tlvs.length == 1 && tlvs[0].mT == 0x6E) {
|
if (tlvs.length == 1 && tlvs[0].mT == 0x6E) {
|
||||||
tlvs = ((Iso7816TLV.Iso7816CompositeTLV) tlvs[0]).mSubs;
|
tlvs = ((Iso7816TLV.Iso7816CompositeTLV) tlvs[0]).mSubs;
|
||||||
@@ -75,7 +77,10 @@ public class OpenPgpCapabilities {
|
|||||||
mKeyFormats.put(KeyType.AUTH, KeyFormat.fromBytes(tlv.mV));
|
mKeyFormats.put(KeyType.AUTH, KeyFormat.fromBytes(tlv.mV));
|
||||||
break;
|
break;
|
||||||
case 0xC4:
|
case 0xC4:
|
||||||
mPw1ValidForMultipleSignatures = tlv.mV[0] == 1;
|
mPwStatusBytes = tlv.mV;
|
||||||
|
break;
|
||||||
|
case 0xC5:
|
||||||
|
mFingerprints = tlv.mV;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -97,7 +102,10 @@ public class OpenPgpCapabilities {
|
|||||||
mKeyFormats.put(KeyType.AUTH, KeyFormat.fromBytes(tlv.mV));
|
mKeyFormats.put(KeyType.AUTH, KeyFormat.fromBytes(tlv.mV));
|
||||||
break;
|
break;
|
||||||
case 0xC4:
|
case 0xC4:
|
||||||
mPw1ValidForMultipleSignatures = tlv.mV[0] == 1;
|
mPwStatusBytes = tlv.mV;
|
||||||
|
break;
|
||||||
|
case 0xC5:
|
||||||
|
mFingerprints = tlv.mV;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -114,47 +122,55 @@ public class OpenPgpCapabilities {
|
|||||||
mMaxRspLen = (v[8] << 8) + v[9];
|
mMaxRspLen = (v[8] << 8) + v[9];
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isPw1ValidForMultipleSignatures() {
|
byte[] getAid() {
|
||||||
return mPw1ValidForMultipleSignatures;
|
|
||||||
}
|
|
||||||
|
|
||||||
public byte[] getAid() {
|
|
||||||
return mAid;
|
return mAid;
|
||||||
}
|
}
|
||||||
|
|
||||||
public byte[] getHistoricalBytes() {
|
byte[] getPwStatusBytes() {
|
||||||
|
return mPwStatusBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isPw1ValidForMultipleSignatures() {
|
||||||
|
return mPwStatusBytes[0] == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] getHistoricalBytes() {
|
||||||
return mHistoricalBytes;
|
return mHistoricalBytes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isHasSM() {
|
boolean isHasSM() {
|
||||||
return mHasSM;
|
return mHasSM;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isAttributesChangable() {
|
boolean isAttributesChangable() {
|
||||||
return mAttriburesChangable;
|
return mAttriburesChangable;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isHasKeyImport() {
|
boolean isHasKeyImport() {
|
||||||
return mHasKeyImport;
|
return mHasKeyImport;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isHasAESSM() {
|
boolean isHasAESSM() {
|
||||||
return isHasSM() && ((mSMType == 1) || (mSMType == 2));
|
return isHasSM() && ((mSMType == 1) || (mSMType == 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isHasSCP11bSM() {
|
boolean isHasSCP11bSM() {
|
||||||
return isHasSM() && (mSMType == 3);
|
return isHasSM() && (mSMType == 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getMaxCmdLen() {
|
int getMaxCmdLen() {
|
||||||
return mMaxCmdLen;
|
return mMaxCmdLen;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getMaxRspLen() {
|
int getMaxRspLen() {
|
||||||
return mMaxRspLen;
|
return mMaxRspLen;
|
||||||
}
|
}
|
||||||
|
|
||||||
public KeyFormat getFormatForKeyType(KeyType keyType) {
|
KeyFormat getFormatForKeyType(KeyType keyType) {
|
||||||
return mKeyFormats.get(keyType);
|
return mKeyFormats.get(keyType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public byte[] getFingerprints() {
|
||||||
|
return mFingerprints;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import android.support.annotation.NonNull;
|
||||||
|
|
||||||
|
import org.bouncycastle.util.Arrays;
|
||||||
|
import org.bouncycastle.util.encoders.Hex;
|
||||||
|
|
||||||
|
|
||||||
|
class OpenPgpCommandApduFactory {
|
||||||
|
private static final int MAX_APDU_NC = 255;
|
||||||
|
private static final int MAX_APDU_NC_EXT = 65535;
|
||||||
|
|
||||||
|
private static final int MAX_APDU_NE = 256;
|
||||||
|
private static final int MAX_APDU_NE_EXT = 65536;
|
||||||
|
|
||||||
|
private static final int CLA = 0x00;
|
||||||
|
private static final int MASK_CLA_CHAINING = 1 << 4;
|
||||||
|
|
||||||
|
private static final int INS_SELECT_FILE = 0xA4;
|
||||||
|
private static final int P1_SELECT_FILE = 0x04;
|
||||||
|
private static final byte[] AID_SELECT_FILE_OPENPGP = Hex.decode("D27600012401");
|
||||||
|
|
||||||
|
private static final int INS_ACTIVATE_FILE = 0x44;
|
||||||
|
private static final int INS_TERMINATE_DF = 0xE6;
|
||||||
|
private static final int INS_GET_RESPONSE = 0xC0;
|
||||||
|
|
||||||
|
private static final int INS_INTERNAL_AUTHENTICATE = 0x88;
|
||||||
|
private static final int P1_INTERNAL_AUTH_SECURE_MESSAGING = 0x01;
|
||||||
|
|
||||||
|
private static final int INS_VERIFY = 0x20;
|
||||||
|
private static final int P2_VERIFY_PW1_SIGN = 0x81;
|
||||||
|
private static final int P2_VERIFY_PW1_OTHER = 0x82;
|
||||||
|
private static final int P2_VERIFY_PW3 = 0x83;
|
||||||
|
|
||||||
|
private static final int INS_CHANGE_REFERENCE_DATA = 0x24;
|
||||||
|
private static final int P2_CHANGE_REFERENCE_DATA_PW1 = 0x81;
|
||||||
|
private static final int P2_CHANGE_REFERENCE_DATA_PW3 = 0x83;
|
||||||
|
|
||||||
|
private static final int INS_RESET_RETRY_COUNTER = 0x2C;
|
||||||
|
private static final int P1_RESET_RETRY_COUNTER_NEW_PW = 0x02;
|
||||||
|
private static final int P2_RESET_RETRY_COUNTER = 0x81;
|
||||||
|
|
||||||
|
private static final int INS_PERFORM_SECURITY_OPERATION = 0x2A;
|
||||||
|
private static final int P1_PSO_DECIPHER = 0x80;
|
||||||
|
private static final int P1_PSO_COMPUTE_DIGITAL_SIGNATURE = 0x9E;
|
||||||
|
private static final int P2_PSO_DECIPHER = 0x86;
|
||||||
|
private static final int P2_PSO_COMPUTE_DIGITAL_SIGNATURE = 0x9A;
|
||||||
|
|
||||||
|
private static final int INS_SELECT_DATA = 0xA5;
|
||||||
|
private static final int P1_SELECT_DATA_FOURTH = 0x03;
|
||||||
|
private static final int P2_SELECT_DATA = 0x04;
|
||||||
|
private static final byte[] CP_SELECT_DATA_CARD_HOLDER_CERT = Hex.decode("60045C027F21");
|
||||||
|
|
||||||
|
private static final int INS_GET_DATA = 0xCA;
|
||||||
|
private static final int P1_GET_DATA_CARD_HOLDER_CERT = 0x7F;
|
||||||
|
private static final int P2_GET_DATA_CARD_HOLDER_CERT = 0x21;
|
||||||
|
|
||||||
|
private static final int INS_PUT_DATA = 0xDA;
|
||||||
|
|
||||||
|
private static final int INS_PUT_DATA_ODD = 0xDB;
|
||||||
|
private static final int P1_PUT_DATA_ODD_KEY = 0x3F;
|
||||||
|
private static final int P2_PUT_DATA_ODD_KEY = 0xFF;
|
||||||
|
|
||||||
|
private static final int INS_GENERATE_ASYMMETRIC_KEY_PAIR = 0x47;
|
||||||
|
private static final int P1_GAKP_GENERATE = 0x80;
|
||||||
|
private static final int P1_GAKP_READ_PUBKEY_TEMPLATE = 0x81;
|
||||||
|
private static final byte[] CRT_GAKP_SECURE_MESSAGING = Hex.decode("A600");
|
||||||
|
|
||||||
|
private static final int P1_EMPTY = 0x00;
|
||||||
|
private static final int P2_EMPTY = 0x00;
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createPutDataCommand(int dataObject, byte[] data) {
|
||||||
|
return CommandApdu.create(CLA, INS_PUT_DATA, (dataObject & 0xFF00) >> 8, dataObject & 0xFF, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createPutKeyCommand(byte[] keyBytes) {
|
||||||
|
// the odd PUT DATA INS is for compliance with ISO 7816-8. This is used only to put key data on the card
|
||||||
|
return CommandApdu.create(CLA, INS_PUT_DATA_ODD, P1_PUT_DATA_ODD_KEY, P2_PUT_DATA_ODD_KEY, keyBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createComputeDigitalSignatureCommand(byte[] data) {
|
||||||
|
return CommandApdu.create(CLA, INS_PERFORM_SECURITY_OPERATION, P1_PSO_COMPUTE_DIGITAL_SIGNATURE,
|
||||||
|
P2_PSO_COMPUTE_DIGITAL_SIGNATURE, data, MAX_APDU_NE_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createDecipherCommand(byte[] data) {
|
||||||
|
return CommandApdu.create(CLA, INS_PERFORM_SECURITY_OPERATION, P1_PSO_DECIPHER, P2_PSO_DECIPHER, data,
|
||||||
|
MAX_APDU_NE_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createChangePw3Command(byte[] adminPin, byte[] newAdminPin) {
|
||||||
|
return CommandApdu.create(CLA, INS_CHANGE_REFERENCE_DATA, P1_EMPTY,
|
||||||
|
P2_CHANGE_REFERENCE_DATA_PW3, Arrays.concatenate(adminPin, newAdminPin));
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createResetPw1Command(byte[] newPin) {
|
||||||
|
return CommandApdu.create(CLA, INS_RESET_RETRY_COUNTER, P1_RESET_RETRY_COUNTER_NEW_PW,
|
||||||
|
P2_RESET_RETRY_COUNTER, newPin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createGetDataCommand(int p1, int p2) {
|
||||||
|
return CommandApdu.create(CLA, INS_GET_DATA, p1, p2, MAX_APDU_NE_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createGetResponseCommand(int lastResponseSw2) {
|
||||||
|
return CommandApdu.create(CLA, INS_GET_RESPONSE, P1_EMPTY, P2_EMPTY, lastResponseSw2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createVerifyPw1ForSignatureCommand(byte[] pin) {
|
||||||
|
return CommandApdu.create(CLA, INS_VERIFY, P1_EMPTY, P2_VERIFY_PW1_SIGN, pin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createVerifyPw1ForOtherCommand(byte[] pin) {
|
||||||
|
return CommandApdu.create(CLA, INS_VERIFY, P1_EMPTY, P2_VERIFY_PW1_OTHER, pin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createVerifyPw3Command(byte[] pin) {
|
||||||
|
return CommandApdu.create(CLA, INS_VERIFY, P1_EMPTY, P2_VERIFY_PW3, pin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createSelectFileOpenPgpCommand() {
|
||||||
|
return CommandApdu.create(CLA, INS_SELECT_FILE, P1_SELECT_FILE, P2_EMPTY, AID_SELECT_FILE_OPENPGP);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createSelectFileCommand(String fileAid) {
|
||||||
|
return CommandApdu.create(CLA, INS_SELECT_FILE, P1_SELECT_FILE, P2_EMPTY, Hex.decode(fileAid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createReactivate2Command() {
|
||||||
|
return CommandApdu.create(CLA, INS_ACTIVATE_FILE, P1_EMPTY, P2_EMPTY);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createReactivate1Command() {
|
||||||
|
return CommandApdu.create(CLA, INS_TERMINATE_DF, P1_EMPTY, P2_EMPTY);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createInternalAuthForSecureMessagingCommand(byte[] authData) {
|
||||||
|
return CommandApdu.create(CLA, INS_INTERNAL_AUTHENTICATE, P1_INTERNAL_AUTH_SECURE_MESSAGING, P2_EMPTY, authData,
|
||||||
|
MAX_APDU_NE_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createGenerateKeyCommand(int slot) {
|
||||||
|
return CommandApdu.create(CLA, INS_GENERATE_ASYMMETRIC_KEY_PAIR,
|
||||||
|
P1_GAKP_GENERATE, P2_EMPTY, new byte[] { (byte) slot, 0x00 }, MAX_APDU_NE_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createRetrieveSecureMessagingPublicKeyCommand() {
|
||||||
|
// see https://github.com/ANSSI-FR/SmartPGP/blob/master/secure_messaging/smartpgp_sm.pdf
|
||||||
|
return CommandApdu.create(CLA, INS_GENERATE_ASYMMETRIC_KEY_PAIR, P1_GAKP_READ_PUBKEY_TEMPLATE, P2_EMPTY,
|
||||||
|
CRT_GAKP_SECURE_MESSAGING, MAX_APDU_NE_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createSelectSecureMessagingCertificateCommand() {
|
||||||
|
// see https://github.com/ANSSI-FR/SmartPGP/blob/master/secure_messaging/smartpgp_sm.pdf
|
||||||
|
// this command selects the fourth occurence of data tag 7F21
|
||||||
|
return CommandApdu.create(CLA, INS_SELECT_DATA, P1_SELECT_DATA_FOURTH, P2_SELECT_DATA,
|
||||||
|
CP_SELECT_DATA_CARD_HOLDER_CERT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createGetDataCardHolderCertCommand() {
|
||||||
|
return createGetDataCommand(P1_GET_DATA_CARD_HOLDER_CERT, P2_GET_DATA_CARD_HOLDER_CERT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
CommandApdu createShortApdu(CommandApdu apdu) {
|
||||||
|
int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
|
||||||
|
return CommandApdu.create(apdu.getCLA(), apdu.getINS(), apdu.getP1(), apdu.getP2(), apdu.getData(), ne);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
List<CommandApdu> createChainedApdus(CommandApdu apdu) {
|
||||||
|
ArrayList<CommandApdu> result = new ArrayList<>();
|
||||||
|
|
||||||
|
int offset = 0;
|
||||||
|
byte[] data = apdu.getData();
|
||||||
|
int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
|
||||||
|
while (offset < data.length) {
|
||||||
|
int curLen = Math.min(MAX_APDU_NC, data.length - offset);
|
||||||
|
boolean last = offset + curLen >= data.length;
|
||||||
|
int cla = apdu.getCLA() + (last ? 0 : MASK_CLA_CHAINING);
|
||||||
|
|
||||||
|
CommandApdu cmd =
|
||||||
|
CommandApdu.create(cla, apdu.getINS(), apdu.getP1(), apdu.getP2(), data, offset, curLen, ne);
|
||||||
|
result.add(cmd);
|
||||||
|
|
||||||
|
offset += curLen;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSuitableForShortApdu(CommandApdu apdu) {
|
||||||
|
return apdu.getData().length <= MAX_APDU_NC;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2016 Vincent Breitmoser <look@my.amazin.horse>
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import com.google.auto.value.AutoValue;
|
||||||
|
|
||||||
|
|
||||||
|
/** A response APDU as defined in ISO/IEC 7816-4. */
|
||||||
|
@AutoValue
|
||||||
|
@SuppressWarnings("WeakerAccess")
|
||||||
|
public abstract class ResponseApdu {
|
||||||
|
private static final int APDU_SW_SUCCESS = 0x9000;
|
||||||
|
|
||||||
|
public abstract byte[] getData();
|
||||||
|
public abstract int getSw1();
|
||||||
|
public abstract int getSw2();
|
||||||
|
|
||||||
|
public static ResponseApdu fromBytes(byte[] apdu) {
|
||||||
|
if (apdu.length < 2) {
|
||||||
|
throw new IllegalArgumentException("Response apdu must be 2 bytes or larger!");
|
||||||
|
}
|
||||||
|
byte[] data = Arrays.copyOfRange(apdu, 0, apdu.length - 2);
|
||||||
|
int sw1 = apdu[apdu.length -2] & 0xff;
|
||||||
|
int sw2 = apdu[apdu.length -1] & 0xff;
|
||||||
|
return new AutoValue_ResponseApdu(data, sw1, sw2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSw() {
|
||||||
|
return (getSw1() << 8) | getSw2();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isSuccess() {
|
||||||
|
return getSw() == APDU_SW_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] toBytes() {
|
||||||
|
byte[] data = getData();
|
||||||
|
byte[] bytes = new byte[data.length + 2];
|
||||||
|
System.arraycopy(data, 0, bytes, 0, data.length);
|
||||||
|
|
||||||
|
bytes[bytes.length -2] = (byte) getSw1();
|
||||||
|
bytes[bytes.length -1] = (byte) getSw2();
|
||||||
|
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,17 +17,6 @@
|
|||||||
|
|
||||||
package org.sufficientlysecure.keychain.securitytoken;
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
import android.content.Context;
|
|
||||||
import android.support.annotation.NonNull;
|
|
||||||
|
|
||||||
import org.bouncycastle.asn1.nist.NISTNamedCurves;
|
|
||||||
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
|
|
||||||
import org.bouncycastle.asn1.x9.X9ECParameters;
|
|
||||||
import org.bouncycastle.math.ec.ECCurve;
|
|
||||||
import org.bouncycastle.math.ec.ECPoint;
|
|
||||||
import org.bouncycastle.util.Arrays;
|
|
||||||
import org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthoritiesActivity;
|
|
||||||
import org.sufficientlysecure.keychain.util.Preferences;
|
|
||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
@@ -65,6 +54,9 @@ import java.security.spec.InvalidKeySpecException;
|
|||||||
import java.security.spec.InvalidParameterSpecException;
|
import java.security.spec.InvalidParameterSpecException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.support.annotation.NonNull;
|
||||||
|
|
||||||
import javax.crypto.BadPaddingException;
|
import javax.crypto.BadPaddingException;
|
||||||
import javax.crypto.Cipher;
|
import javax.crypto.Cipher;
|
||||||
import javax.crypto.IllegalBlockSizeException;
|
import javax.crypto.IllegalBlockSizeException;
|
||||||
@@ -74,14 +66,19 @@ import javax.crypto.NoSuchPaddingException;
|
|||||||
import javax.crypto.SecretKey;
|
import javax.crypto.SecretKey;
|
||||||
import javax.crypto.spec.IvParameterSpec;
|
import javax.crypto.spec.IvParameterSpec;
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
import javax.smartcardio.CommandAPDU;
|
import org.bouncycastle.asn1.nist.NISTNamedCurves;
|
||||||
import javax.smartcardio.ResponseAPDU;
|
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
|
||||||
|
import org.bouncycastle.asn1.x9.X9ECParameters;
|
||||||
|
import org.bouncycastle.math.ec.ECCurve;
|
||||||
|
import org.bouncycastle.math.ec.ECPoint;
|
||||||
|
import org.bouncycastle.util.Arrays;
|
||||||
|
import org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthoritiesActivity;
|
||||||
|
import org.sufficientlysecure.keychain.util.Preferences;
|
||||||
|
|
||||||
|
|
||||||
class SCP11bSecureMessaging implements SecureMessaging {
|
class SCP11bSecureMessaging implements SecureMessaging {
|
||||||
|
|
||||||
private static final byte OPENPGP_SECURE_MESSAGING_CLA_MASK = (byte)0x04;
|
private static final byte OPENPGP_SECURE_MESSAGING_CLA_MASK = (byte)0x04;
|
||||||
private static final byte[] OPENPGP_SECURE_MESSAGING_KEY_CRT = new byte[] { (byte)0xA6, (byte)0 };
|
|
||||||
private static final byte OPENPGP_SECURE_MESSAGING_KEY_ATTRIBUTES_TAG = (byte)0xD4;
|
private static final byte OPENPGP_SECURE_MESSAGING_KEY_ATTRIBUTES_TAG = (byte)0xD4;
|
||||||
|
|
||||||
private static final int AES_BLOCK_SIZE = 128 / 8;
|
private static final int AES_BLOCK_SIZE = 128 / 8;
|
||||||
@@ -152,7 +149,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
&& (mMacChaining != null);
|
&& (mMacChaining != null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final ECParameterSpec getAlgorithmParameterSpec(final ECKeyFormat kf)
|
private static ECParameterSpec getAlgorithmParameterSpec(final ECKeyFormat kf)
|
||||||
throws NoSuchProviderException, NoSuchAlgorithmException, InvalidParameterSpecException {
|
throws NoSuchProviderException, NoSuchAlgorithmException, InvalidParameterSpecException {
|
||||||
final AlgorithmParameters algoParams = AlgorithmParameters.getInstance(SCP11B_KEY_AGREEMENT_KEY_ALGO, PROVIDER);
|
final AlgorithmParameters algoParams = AlgorithmParameters.getInstance(SCP11B_KEY_AGREEMENT_KEY_ALGO, PROVIDER);
|
||||||
|
|
||||||
@@ -275,20 +272,19 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static void establish(final SecurityTokenHelper t, final Context ctx)
|
static void establish(final SecurityTokenConnection t, final Context ctx, OpenPgpCommandApduFactory commandFactory)
|
||||||
throws SecureMessagingException, IOException {
|
throws SecureMessagingException, IOException {
|
||||||
|
|
||||||
CommandAPDU cmd;
|
CommandApdu cmd;
|
||||||
ResponseAPDU resp;
|
ResponseApdu resp;
|
||||||
Iso7816TLV[] tlvs;
|
Iso7816TLV[] tlvs;
|
||||||
|
|
||||||
t.clearSecureMessaging();
|
t.clearSecureMessaging();
|
||||||
|
|
||||||
// retrieving key algorithm
|
// retrieving key algorithm
|
||||||
cmd = new CommandAPDU(0, (byte)0xCA, (byte)0x00,
|
cmd = commandFactory.createGetDataCommand(0x00, OPENPGP_SECURE_MESSAGING_KEY_ATTRIBUTES_TAG);
|
||||||
OPENPGP_SECURE_MESSAGING_KEY_ATTRIBUTES_TAG, SecurityTokenHelper.MAX_APDU_NE_EXT);
|
|
||||||
resp = t.communicate(cmd);
|
resp = t.communicate(cmd);
|
||||||
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
|
if (!resp.isSuccess()) {
|
||||||
throw new SecureMessagingException("failed to retrieve secure messaging key attributes");
|
throw new SecureMessagingException("failed to retrieve secure messaging key attributes");
|
||||||
}
|
}
|
||||||
tlvs = Iso7816TLV.readList(resp.getData(), true);
|
tlvs = Iso7816TLV.readList(resp.getData(), true);
|
||||||
@@ -317,26 +313,23 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
|
|
||||||
if (prefs != null && prefs.getExperimentalSmartPGPAuthoritiesEnable()) {
|
if (prefs != null && prefs.getExperimentalSmartPGPAuthoritiesEnable()) {
|
||||||
// retrieving certificate
|
// retrieving certificate
|
||||||
cmd = new CommandAPDU(0, (byte) 0xA5, (byte) 0x03, (byte) 0x04,
|
cmd = commandFactory.createSelectSecureMessagingCertificateCommand();
|
||||||
new byte[]{(byte) 0x60, (byte) 0x04, (byte) 0x5C, (byte) 0x02, (byte) 0x7F, (byte) 0x21});
|
|
||||||
resp = t.communicate(cmd);
|
resp = t.communicate(cmd);
|
||||||
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
|
if (!resp.isSuccess()) {
|
||||||
throw new SecureMessagingException("failed to select secure messaging certificate");
|
throw new SecureMessagingException("failed to select secure messaging certificate");
|
||||||
}
|
}
|
||||||
cmd = new CommandAPDU(0, (byte) 0xCA, (byte) 0x7F, (byte) 0x21, SecurityTokenHelper.MAX_APDU_NE_EXT);
|
cmd = commandFactory.createGetDataCardHolderCertCommand();
|
||||||
resp = t.communicate(cmd);
|
resp = t.communicate(cmd);
|
||||||
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
|
if (!resp.isSuccess()) {
|
||||||
throw new SecureMessagingException("failed to retrieve secure messaging certificate");
|
throw new SecureMessagingException("failed to retrieve secure messaging certificate");
|
||||||
}
|
}
|
||||||
|
|
||||||
pkcard = verifyCertificate(ctx, eckf, resp.getData());
|
pkcard = verifyCertificate(ctx, eckf, resp.getData());
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
// retrieving public key
|
cmd = commandFactory.createRetrieveSecureMessagingPublicKeyCommand();
|
||||||
cmd = new CommandAPDU(0, (byte) 0x47, (byte) 0x81, (byte) 0x00,
|
|
||||||
OPENPGP_SECURE_MESSAGING_KEY_CRT, SecurityTokenHelper.MAX_APDU_NE_EXT);
|
|
||||||
resp = t.communicate(cmd);
|
resp = t.communicate(cmd);
|
||||||
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
|
if (!resp.isSuccess()) {
|
||||||
throw new SecureMessagingException("failed to retrieve secure messaging public key");
|
throw new SecureMessagingException("failed to retrieve secure messaging public key");
|
||||||
}
|
}
|
||||||
tlvs = Iso7816TLV.readList(resp.getData(), true);
|
tlvs = Iso7816TLV.readList(resp.getData(), true);
|
||||||
@@ -394,11 +387,9 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
pkout.writeTo(bout);
|
pkout.writeTo(bout);
|
||||||
pkout = bout;
|
pkout = bout;
|
||||||
|
|
||||||
// internal authenticate
|
cmd = commandFactory.createInternalAuthForSecureMessagingCommand(pkout.toByteArray());
|
||||||
cmd = new CommandAPDU(0, (byte)0x88, (byte)0x01, (byte)0x0, pkout.toByteArray(),
|
|
||||||
SecurityTokenHelper.MAX_APDU_NE_EXT);
|
|
||||||
resp = t.communicate(cmd);
|
resp = t.communicate(cmd);
|
||||||
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
|
if (!resp.isSuccess()) {
|
||||||
throw new SecureMessagingException("failed to initiate internal authenticate");
|
throw new SecureMessagingException("failed to initiate internal authenticate");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -509,7 +500,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public CommandAPDU encryptAndSign(CommandAPDU apdu)
|
public CommandApdu encryptAndSign(CommandApdu apdu)
|
||||||
throws SecureMessagingException {
|
throws SecureMessagingException {
|
||||||
|
|
||||||
if (!isEstablished()) {
|
if (!isEstablished()) {
|
||||||
@@ -587,7 +578,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
}
|
}
|
||||||
odata[ooff++] = (byte) 0;
|
odata[ooff++] = (byte) 0;
|
||||||
|
|
||||||
apdu = new CommandAPDU(odata, 0, ooff);
|
apdu = CommandApdu.fromBytes(odata, 0, ooff);
|
||||||
|
|
||||||
Arrays.fill(odata, (byte)0);
|
Arrays.fill(odata, (byte)0);
|
||||||
|
|
||||||
@@ -612,7 +603,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ResponseAPDU verifyAndDecrypt(ResponseAPDU apdu)
|
public ResponseApdu verifyAndDecrypt(ResponseApdu apdu)
|
||||||
throws SecureMessagingException {
|
throws SecureMessagingException {
|
||||||
|
|
||||||
if (!isEstablished()) {
|
if (!isEstablished()) {
|
||||||
@@ -621,10 +612,9 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
|
|
||||||
byte[] data = apdu.getData();
|
byte[] data = apdu.getData();
|
||||||
|
|
||||||
if ((data.length == 0) &&
|
if ((data.length == 0) && !apdu.isSuccess() &&
|
||||||
(apdu.getSW() != 0x9000) &&
|
(apdu.getSw1() != 0x62) &&
|
||||||
(apdu.getSW1() != 0x62) &&
|
(apdu.getSw1() != 0x63)) {
|
||||||
(apdu.getSW1() != 0x63)) {
|
|
||||||
return apdu;
|
return apdu;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -641,8 +631,8 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
if ((data.length - SCP11_MAC_LENGTH) > 0) {
|
if ((data.length - SCP11_MAC_LENGTH) > 0) {
|
||||||
mac.update(data, 0, data.length - SCP11_MAC_LENGTH);
|
mac.update(data, 0, data.length - SCP11_MAC_LENGTH);
|
||||||
}
|
}
|
||||||
mac.update((byte) apdu.getSW1());
|
mac.update((byte) apdu.getSw1());
|
||||||
mac.update((byte) apdu.getSW2());
|
mac.update((byte) apdu.getSw2());
|
||||||
|
|
||||||
final byte[] sig = mac.doFinal();
|
final byte[] sig = mac.doFinal();
|
||||||
|
|
||||||
@@ -682,19 +672,19 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
|||||||
|
|
||||||
final byte[] datasw = new byte[i + 2];
|
final byte[] datasw = new byte[i + 2];
|
||||||
System.arraycopy(data, 0, datasw, 0, i);
|
System.arraycopy(data, 0, datasw, 0, i);
|
||||||
datasw[datasw.length - 2] = (byte) apdu.getSW1();
|
datasw[datasw.length - 2] = (byte) apdu.getSw1();
|
||||||
datasw[datasw.length - 1] = (byte) apdu.getSW2();
|
datasw[datasw.length - 1] = (byte) apdu.getSw2();
|
||||||
|
|
||||||
Arrays.fill(data, (byte) 0);
|
Arrays.fill(data, (byte) 0);
|
||||||
|
|
||||||
data = datasw;
|
data = datasw;
|
||||||
} else {
|
} else {
|
||||||
data = new byte[2];
|
data = new byte[2];
|
||||||
data[0] = (byte) apdu.getSW1();
|
data[0] = (byte) apdu.getSw1();
|
||||||
data[1] = (byte) apdu.getSW2();
|
data[1] = (byte) apdu.getSw2();
|
||||||
}
|
}
|
||||||
|
|
||||||
apdu = new ResponseAPDU(data);
|
apdu = ResponseApdu.fromBytes(data);
|
||||||
|
|
||||||
return apdu;
|
return apdu;
|
||||||
|
|
||||||
|
|||||||
@@ -17,10 +17,6 @@
|
|||||||
|
|
||||||
package org.sufficientlysecure.keychain.securitytoken;
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import javax.smartcardio.CommandAPDU;
|
|
||||||
import javax.smartcardio.ResponseAPDU;
|
|
||||||
|
|
||||||
public interface SecureMessaging {
|
public interface SecureMessaging {
|
||||||
|
|
||||||
@@ -28,7 +24,7 @@ public interface SecureMessaging {
|
|||||||
|
|
||||||
boolean isEstablished();
|
boolean isEstablished();
|
||||||
|
|
||||||
CommandAPDU encryptAndSign(CommandAPDU apdu) throws SecureMessagingException;
|
CommandApdu encryptAndSign(CommandApdu apdu) throws SecureMessagingException;
|
||||||
|
|
||||||
ResponseAPDU verifyAndDecrypt(ResponseAPDU apdu) throws SecureMessagingException;
|
ResponseApdu verifyAndDecrypt(ResponseApdu apdu) throws SecureMessagingException;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ package org.sufficientlysecure.keychain.securitytoken;
|
|||||||
|
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.support.annotation.NonNull;
|
import android.support.annotation.NonNull;
|
||||||
|
import android.support.annotation.VisibleForTesting;
|
||||||
|
|
||||||
import org.bouncycastle.asn1.ASN1Encodable;
|
import org.bouncycastle.asn1.ASN1Encodable;
|
||||||
import org.bouncycastle.asn1.ASN1Integer;
|
import org.bouncycastle.asn1.ASN1Integer;
|
||||||
@@ -46,8 +47,6 @@ import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
|
|||||||
import javax.crypto.Cipher;
|
import javax.crypto.Cipher;
|
||||||
import javax.crypto.NoSuchPaddingException;
|
import javax.crypto.NoSuchPaddingException;
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
import javax.smartcardio.CommandAPDU;
|
|
||||||
import javax.smartcardio.ResponseAPDU;
|
|
||||||
|
|
||||||
import org.sufficientlysecure.keychain.securitytoken.usb.UsbTransportException;
|
import org.sufficientlysecure.keychain.securitytoken.usb.UsbTransportException;
|
||||||
import org.sufficientlysecure.keychain.util.Log;
|
import org.sufficientlysecure.keychain.util.Log;
|
||||||
@@ -64,53 +63,55 @@ import java.security.NoSuchAlgorithmException;
|
|||||||
import java.security.interfaces.ECPrivateKey;
|
import java.security.interfaces.ECPrivateKey;
|
||||||
import java.security.interfaces.ECPublicKey;
|
import java.security.interfaces.ECPublicKey;
|
||||||
import java.security.interfaces.RSAPrivateCrtKey;
|
import java.security.interfaces.RSAPrivateCrtKey;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class provides a communication interface to OpenPGP applications on ISO SmartCard compliant
|
* This class provides a communication interface to OpenPGP applications on ISO SmartCard compliant
|
||||||
* devices.
|
* devices.
|
||||||
* For the full specs, see http://g10code.com/docs/openpgp-card-2.0.pdf
|
* For the full specs, see http://g10code.com/docs/openpgp-card-2.0.pdf
|
||||||
*/
|
*/
|
||||||
public class SecurityTokenHelper {
|
public class SecurityTokenConnection {
|
||||||
private static final int MAX_APDU_NC = 255;
|
|
||||||
private static final int MAX_APDU_NC_EXT = 65535;
|
|
||||||
|
|
||||||
private static final int MAX_APDU_NE = 256;
|
|
||||||
static final int MAX_APDU_NE_EXT = 65536;
|
|
||||||
|
|
||||||
static final int APDU_SW_SUCCESS = 0x9000;
|
|
||||||
private static final int APDU_SW1_RESPONSE_AVAILABLE = 0x61;
|
private static final int APDU_SW1_RESPONSE_AVAILABLE = 0x61;
|
||||||
|
|
||||||
private static final int MASK_CLA_CHAINING = 1 << 4;
|
|
||||||
|
|
||||||
// Fidesmo constants
|
// Fidesmo constants
|
||||||
private static final String FIDESMO_APPS_AID_PREFIX = "A000000617";
|
private static final String FIDESMO_APPS_AID_PREFIX = "A000000617";
|
||||||
|
|
||||||
private static final byte[] BLANK_FINGERPRINT = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
|
private static final byte[] BLANK_FINGERPRINT = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
|
||||||
|
|
||||||
|
private static SecurityTokenConnection sCachedInstance;
|
||||||
|
|
||||||
private final JcaKeyFingerprintCalculator fingerprintCalculator = new JcaKeyFingerprintCalculator();
|
private final JcaKeyFingerprintCalculator fingerprintCalculator = new JcaKeyFingerprintCalculator();
|
||||||
|
|
||||||
private Transport mTransport;
|
@NonNull
|
||||||
|
private final Transport mTransport;
|
||||||
|
@NonNull
|
||||||
|
private final Passphrase mPin;
|
||||||
|
private final OpenPgpCommandApduFactory commandFactory;
|
||||||
|
|
||||||
private CardCapabilities mCardCapabilities;
|
private CardCapabilities mCardCapabilities;
|
||||||
private OpenPgpCapabilities mOpenPgpCapabilities;
|
private OpenPgpCapabilities mOpenPgpCapabilities;
|
||||||
private SecureMessaging mSecureMessaging;
|
private SecureMessaging mSecureMessaging;
|
||||||
|
|
||||||
private Passphrase mPin;
|
|
||||||
private Passphrase mAdminPin;
|
|
||||||
private boolean mPw1ValidatedForSignature;
|
private boolean mPw1ValidatedForSignature;
|
||||||
private boolean mPw1ValidatedForDecrypt; // Mode 82 does other things; consider renaming?
|
private boolean mPw1ValidatedForDecrypt; // Mode 82 does other things; consider renaming?
|
||||||
private boolean mPw3Validated;
|
private boolean mPw3Validated;
|
||||||
|
|
||||||
private SecurityTokenHelper() {
|
public static SecurityTokenConnection getInstanceForTransport(Transport transport, Passphrase pin) {
|
||||||
|
if (sCachedInstance == null || !sCachedInstance.isPersistentConnectionAllowed() ||
|
||||||
|
!sCachedInstance.isConnected() || !sCachedInstance.mTransport.equals(transport)) {
|
||||||
|
sCachedInstance = new SecurityTokenConnection(transport, pin, new OpenPgpCommandApduFactory());
|
||||||
|
}
|
||||||
|
return sCachedInstance;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static double parseOpenPgpVersion(final byte[] aid) {
|
@VisibleForTesting
|
||||||
float minv = aid[7];
|
SecurityTokenConnection(@NonNull Transport transport, @NonNull Passphrase pin,
|
||||||
while (minv > 0) minv /= 10.0;
|
OpenPgpCommandApduFactory commandFactory) {
|
||||||
return aid[6] + minv;
|
this.mTransport = transport;
|
||||||
}
|
this.mPin = pin;
|
||||||
|
|
||||||
public static SecurityTokenHelper getInstance() {
|
this.commandFactory = commandFactory;
|
||||||
return LazyHolder.SECURITY_TOKEN_HELPER;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getHolderName(byte[] name) {
|
private String getHolderName(byte[] name) {
|
||||||
@@ -126,23 +127,7 @@ public class SecurityTokenHelper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Passphrase getPin() {
|
public void changeKey(CanonicalizedSecretKey secretKey, Passphrase passphrase, Passphrase adminPin) throws IOException {
|
||||||
return mPin;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPin(final Passphrase pin) {
|
|
||||||
this.mPin = pin;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Passphrase getAdminPin() {
|
|
||||||
return mAdminPin;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAdminPin(final Passphrase adminPin) {
|
|
||||||
this.mAdminPin = adminPin;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void changeKey(CanonicalizedSecretKey secretKey, Passphrase passphrase) throws IOException {
|
|
||||||
long keyGenerationTimestamp = secretKey.getCreationTime().getTime() / 1000;
|
long keyGenerationTimestamp = secretKey.getCreationTime().getTime() / 1000;
|
||||||
byte[] timestampBytes = ByteBuffer.allocate(4).putInt((int) keyGenerationTimestamp).array();
|
byte[] timestampBytes = ByteBuffer.allocate(4).putInt((int) keyGenerationTimestamp).array();
|
||||||
KeyType keyType = KeyType.from(secretKey);
|
KeyType keyType = KeyType.from(secretKey);
|
||||||
@@ -160,9 +145,9 @@ public class SecurityTokenHelper {
|
|||||||
keyType.toString()));
|
keyType.toString()));
|
||||||
}
|
}
|
||||||
|
|
||||||
putKey(keyType, secretKey, passphrase);
|
putKey(keyType, secretKey, passphrase, adminPin);
|
||||||
putData(keyType.getFingerprintObjectId(), secretKey.getFingerprint());
|
putData(adminPin, keyType.getFingerprintObjectId(), secretKey.getFingerprint());
|
||||||
putData(keyType.getTimestampObjectId(), timestampBytes);
|
putData(adminPin, keyType.getTimestampObjectId(), timestampBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isSlotEmpty(KeyType keyType) throws IOException {
|
private boolean isSlotEmpty(KeyType keyType) throws IOException {
|
||||||
@@ -179,12 +164,19 @@ public class SecurityTokenHelper {
|
|||||||
return java.util.Arrays.equals(getKeyFingerprint(keyType), fingerprint);
|
return java.util.Arrays.equals(getKeyFingerprint(keyType), fingerprint);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void connectIfNecessary(Context context) throws IOException {
|
||||||
|
if (isConnected()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
connectToDevice(context);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connect to device and select pgp applet
|
* Connect to device and select pgp applet
|
||||||
*
|
|
||||||
* @throws IOException
|
|
||||||
*/
|
*/
|
||||||
public void connectToDevice(final Context ctx) throws IOException {
|
@VisibleForTesting
|
||||||
|
void connectToDevice(Context context) throws IOException {
|
||||||
// Connect on transport layer
|
// Connect on transport layer
|
||||||
mCardCapabilities = new CardCapabilities();
|
mCardCapabilities = new CardCapabilities();
|
||||||
|
|
||||||
@@ -192,15 +184,15 @@ public class SecurityTokenHelper {
|
|||||||
|
|
||||||
// Connect on smartcard layer
|
// Connect on smartcard layer
|
||||||
// Command APDU (page 51) for SELECT FILE command (page 29)
|
// Command APDU (page 51) for SELECT FILE command (page 29)
|
||||||
CommandAPDU select = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, Hex.decode("D27600012401"));
|
CommandApdu select = commandFactory.createSelectFileOpenPgpCommand();
|
||||||
ResponseAPDU response = communicate(select); // activate connection
|
ResponseApdu response = communicate(select); // activate connection
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new CardException("Initialization failed!", response.getSW());
|
throw new CardException("Initialization failed!", response.getSw());
|
||||||
}
|
}
|
||||||
|
|
||||||
mOpenPgpCapabilities = new OpenPgpCapabilities(getData(0x00, 0x6E));
|
OpenPgpCapabilities openPgpCapabilities = new OpenPgpCapabilities(getData(0x00, 0x6E));
|
||||||
mCardCapabilities = new CardCapabilities(mOpenPgpCapabilities.getHistoricalBytes());
|
setConnectionCapabilities(openPgpCapabilities);
|
||||||
|
|
||||||
mPw1ValidatedForSignature = false;
|
mPw1ValidatedForSignature = false;
|
||||||
mPw1ValidatedForDecrypt = false;
|
mPw1ValidatedForDecrypt = false;
|
||||||
@@ -208,21 +200,24 @@ public class SecurityTokenHelper {
|
|||||||
|
|
||||||
if (mOpenPgpCapabilities.isHasSCP11bSM()) {
|
if (mOpenPgpCapabilities.isHasSCP11bSM()) {
|
||||||
try {
|
try {
|
||||||
SCP11bSecureMessaging.establish(this, ctx);
|
SCP11bSecureMessaging.establish(this, context, commandFactory);
|
||||||
} catch (SecureMessagingException e) {
|
} catch (SecureMessagingException e) {
|
||||||
mSecureMessaging = null;
|
mSecureMessaging = null;
|
||||||
Log.e(Constants.TAG, "failed to establish secure messaging", e);
|
Log.e(Constants.TAG, "failed to establish secure messaging", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void resetPin(String newPinStr) throws IOException {
|
@VisibleForTesting
|
||||||
if (!mPw3Validated) {
|
void setConnectionCapabilities(OpenPgpCapabilities openPgpCapabilities) throws IOException {
|
||||||
verifyPin(0x83); // (Verify PW1 with mode 82 for decryption)
|
this.mOpenPgpCapabilities = openPgpCapabilities;
|
||||||
}
|
this.mCardCapabilities = new CardCapabilities(openPgpCapabilities.getHistoricalBytes());
|
||||||
|
}
|
||||||
|
|
||||||
byte[] newPin = newPinStr.getBytes();
|
public void resetPin(byte[] newPin, Passphrase adminPin) throws IOException {
|
||||||
|
if (!mPw3Validated) {
|
||||||
|
verifyAdminPin(adminPin);
|
||||||
|
}
|
||||||
|
|
||||||
final int MAX_PW1_LENGTH_INDEX = 1;
|
final int MAX_PW1_LENGTH_INDEX = 1;
|
||||||
byte[] pwStatusBytes = getPwStatusBytes();
|
byte[] pwStatusBytes = getPwStatusBytes();
|
||||||
@@ -231,52 +226,36 @@ public class SecurityTokenHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Command APDU for RESET RETRY COUNTER command (page 33)
|
// Command APDU for RESET RETRY COUNTER command (page 33)
|
||||||
CommandAPDU changePin = new CommandAPDU(0x00, 0x2C, 0x02, 0x81, newPin);
|
CommandApdu changePin = commandFactory.createResetPw1Command(newPin);
|
||||||
ResponseAPDU response = communicate(changePin);
|
ResponseApdu response = communicate(changePin);
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new CardException("Failed to change PIN", response.getSW());
|
throw new CardException("Failed to change PIN", response.getSw());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Modifies the user's PW1 or PW3. Before sending, the new PIN will be validated for
|
* Modifies the user's PW3. Before sending, the new PIN will be validated for
|
||||||
* conformance to the token's requirements for key length.
|
* conformance to the token's requirements for key length.
|
||||||
*
|
*
|
||||||
* @param pw For PW1, this is 0x81. For PW3 (Admin PIN), mode is 0x83.
|
* @param newAdminPin The new PW3.
|
||||||
* @param newPin The new PW1 or PW3.
|
|
||||||
*/
|
*/
|
||||||
public void modifyPin(int pw, byte[] newPin) throws IOException {
|
public void modifyPw3Pin(byte[] newAdminPin, Passphrase adminPin) throws IOException {
|
||||||
final int MAX_PW1_LENGTH_INDEX = 1;
|
|
||||||
final int MAX_PW3_LENGTH_INDEX = 3;
|
final int MAX_PW3_LENGTH_INDEX = 3;
|
||||||
|
|
||||||
byte[] pwStatusBytes = getPwStatusBytes();
|
byte[] pwStatusBytes = getPwStatusBytes();
|
||||||
|
|
||||||
if (pw == 0x81) {
|
if (newAdminPin.length < 8 || newAdminPin.length > pwStatusBytes[MAX_PW3_LENGTH_INDEX]) {
|
||||||
if (newPin.length < 6 || newPin.length > pwStatusBytes[MAX_PW1_LENGTH_INDEX]) {
|
throw new IOException("Invalid PIN length");
|
||||||
throw new IOException("Invalid PIN length");
|
|
||||||
}
|
|
||||||
} else if (pw == 0x83) {
|
|
||||||
if (newPin.length < 8 || newPin.length > pwStatusBytes[MAX_PW3_LENGTH_INDEX]) {
|
|
||||||
throw new IOException("Invalid PIN length");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw new IOException("Invalid PW index for modify PIN operation");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
byte[] pin;
|
byte[] pin = adminPin.toStringUnsafe().getBytes();
|
||||||
if (pw == 0x83) {
|
|
||||||
pin = mAdminPin.toStringUnsafe().getBytes();
|
|
||||||
} else {
|
|
||||||
pin = mPin.toStringUnsafe().getBytes();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Command APDU for CHANGE REFERENCE DATA command (page 32)
|
CommandApdu changePin = commandFactory.createChangePw3Command(pin, newAdminPin);
|
||||||
CommandAPDU changePin = new CommandAPDU(0x00, 0x24, 0x00, pw, Arrays.concatenate(pin, newPin));
|
ResponseApdu response = communicate(changePin);
|
||||||
ResponseAPDU response = communicate(changePin);
|
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new CardException("Failed to change PIN", response.getSW());
|
throw new CardException("Failed to change PIN", response.getSw());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,7 +272,7 @@ public class SecurityTokenHelper {
|
|||||||
final KeyFormat kf = mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT);
|
final KeyFormat kf = mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT);
|
||||||
|
|
||||||
if (!mPw1ValidatedForDecrypt) {
|
if (!mPw1ValidatedForDecrypt) {
|
||||||
verifyPin(0x82); // (Verify PW1 with mode 82 for decryption)
|
verifyPinForOther();
|
||||||
}
|
}
|
||||||
|
|
||||||
byte[] data;
|
byte[] data;
|
||||||
@@ -352,11 +331,11 @@ public class SecurityTokenHelper {
|
|||||||
throw new CardException("Unknown encryption key type!");
|
throw new CardException("Unknown encryption key type!");
|
||||||
}
|
}
|
||||||
|
|
||||||
CommandAPDU command = new CommandAPDU(0x00, 0x2A, 0x80, 0x86, data, MAX_APDU_NE_EXT);
|
CommandApdu command = commandFactory.createDecipherCommand(data);
|
||||||
ResponseAPDU response = communicate(command);
|
ResponseApdu response = communicate(command);
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new CardException("Deciphering with Security token failed on receive", response.getSW());
|
throw new CardException("Deciphering with Security token failed on receive", response.getSw());
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT).keyFormatType()) {
|
switch (mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT).keyFormatType()) {
|
||||||
@@ -416,34 +395,46 @@ public class SecurityTokenHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verifies the user's PW1 or PW3 with the appropriate mode.
|
* Verifies the user's PW1 with the appropriate mode.
|
||||||
*
|
|
||||||
* @param mode For PW1, this is 0x81 for signing, 0x82 for everything else.
|
|
||||||
* For PW3 (Admin PIN), mode is 0x83.
|
|
||||||
*/
|
*/
|
||||||
private void verifyPin(int mode) throws IOException {
|
private void verifyPinForSignature() throws IOException {
|
||||||
if (mPin != null || mode == 0x83) {
|
byte[] pin = mPin.toStringUnsafe().getBytes();
|
||||||
|
|
||||||
byte[] pin;
|
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForSignatureCommand(pin));
|
||||||
if (mode == 0x83) {
|
if (!response.isSuccess()) {
|
||||||
pin = mAdminPin.toStringUnsafe().getBytes();
|
throw new CardException("Bad PIN!", response.getSw());
|
||||||
} else {
|
|
||||||
pin = mPin.toStringUnsafe().getBytes();
|
|
||||||
}
|
|
||||||
|
|
||||||
ResponseAPDU response = tryPin(mode, pin);// login
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
|
||||||
throw new CardException("Bad PIN!", response.getSW());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mode == 0x81) {
|
|
||||||
mPw1ValidatedForSignature = true;
|
|
||||||
} else if (mode == 0x82) {
|
|
||||||
mPw1ValidatedForDecrypt = true;
|
|
||||||
} else if (mode == 0x83) {
|
|
||||||
mPw3Validated = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
mPw1ValidatedForSignature = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies the user's PW1 with the appropriate mode.
|
||||||
|
*/
|
||||||
|
private void verifyPinForOther() throws IOException {
|
||||||
|
byte[] pin = mPin.toStringUnsafe().getBytes();
|
||||||
|
|
||||||
|
// Command APDU for VERIFY command (page 32)
|
||||||
|
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForOtherCommand(pin));
|
||||||
|
if (!response.isSuccess()) {
|
||||||
|
throw new CardException("Bad PIN!", response.getSw());
|
||||||
|
}
|
||||||
|
|
||||||
|
mPw1ValidatedForDecrypt = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies the user's PW1 or PW3 with the appropriate mode.
|
||||||
|
*/
|
||||||
|
private void verifyAdminPin(Passphrase adminPin) throws IOException {
|
||||||
|
// Command APDU for VERIFY command (page 32)
|
||||||
|
ResponseApdu response =
|
||||||
|
communicate(commandFactory.createVerifyPw3Command(adminPin.toStringUnsafe().getBytes()));
|
||||||
|
if (!response.isSuccess()) {
|
||||||
|
throw new CardException("Bad PIN!", response.getSw());
|
||||||
|
}
|
||||||
|
|
||||||
|
mPw3Validated = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -454,28 +445,28 @@ public class SecurityTokenHelper {
|
|||||||
* @param dataObject The data object to be stored.
|
* @param dataObject The data object to be stored.
|
||||||
* @param data The data to store in the object
|
* @param data The data to store in the object
|
||||||
*/
|
*/
|
||||||
private void putData(int dataObject, byte[] data) throws IOException {
|
private void putData(Passphrase adminPin, int dataObject, byte[] data) throws IOException {
|
||||||
if (data.length > 254) {
|
if (data.length > 254) {
|
||||||
throw new IOException("Cannot PUT DATA with length > 254");
|
throw new IOException("Cannot PUT DATA with length > 254");
|
||||||
}
|
}
|
||||||
|
// TODO use admin pin regardless, if we have it?
|
||||||
if (dataObject == 0x0101 || dataObject == 0x0103) {
|
if (dataObject == 0x0101 || dataObject == 0x0103) {
|
||||||
if (!mPw1ValidatedForDecrypt) {
|
if (!mPw1ValidatedForDecrypt) {
|
||||||
verifyPin(0x82); // (Verify PW1 for non-signing operations)
|
verifyPinForOther();
|
||||||
}
|
}
|
||||||
} else if (!mPw3Validated) {
|
} else if (!mPw3Validated) {
|
||||||
verifyPin(0x83); // (Verify PW3)
|
verifyAdminPin(adminPin);
|
||||||
}
|
}
|
||||||
|
|
||||||
CommandAPDU command = new CommandAPDU(0x00, 0xDA, (dataObject & 0xFF00) >> 8, dataObject & 0xFF, data);
|
CommandApdu command = commandFactory.createPutDataCommand(dataObject, data);
|
||||||
ResponseAPDU response = communicate(command); // put data
|
ResponseApdu response = communicate(command); // put data
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new CardException("Failed to put data.", response.getSW());
|
throw new CardException("Failed to put data.", response.getSw());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void setKeyAttributes(Passphrase adminPin, final KeyType slot, final CanonicalizedSecretKey secretKey)
|
||||||
private void setKeyAttributes(final KeyType slot, final CanonicalizedSecretKey secretKey)
|
|
||||||
throws IOException {
|
throws IOException {
|
||||||
|
|
||||||
if (mOpenPgpCapabilities.isAttributesChangable()) {
|
if (mOpenPgpCapabilities.isAttributesChangable()) {
|
||||||
@@ -493,7 +484,7 @@ public class SecurityTokenHelper {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
putData(tag, SecurityTokenUtils.attributesFromSecretKey(slot, secretKey));
|
putData(adminPin, tag, SecurityTokenUtils.attributesFromSecretKey(slot, secretKey));
|
||||||
|
|
||||||
mOpenPgpCapabilities.updateWithData(getData(0x00, tag));
|
mOpenPgpCapabilities.updateWithData(getData(0x00, tag));
|
||||||
|
|
||||||
@@ -512,14 +503,14 @@ public class SecurityTokenHelper {
|
|||||||
* 0xB8: Decipherment Key
|
* 0xB8: Decipherment Key
|
||||||
* 0xA4: Authentication Key
|
* 0xA4: Authentication Key
|
||||||
*/
|
*/
|
||||||
private void putKey(KeyType slot, CanonicalizedSecretKey secretKey, Passphrase passphrase)
|
private void putKey(KeyType slot, CanonicalizedSecretKey secretKey, Passphrase passphrase, Passphrase adminPin)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
RSAPrivateCrtKey crtSecretKey;
|
RSAPrivateCrtKey crtSecretKey;
|
||||||
ECPrivateKey ecSecretKey;
|
ECPrivateKey ecSecretKey;
|
||||||
ECPublicKey ecPublicKey;
|
ECPublicKey ecPublicKey;
|
||||||
|
|
||||||
if (!mPw3Validated) {
|
if (!mPw3Validated) {
|
||||||
verifyPin(0x83); // (Verify PW3 with mode 83)
|
verifyAdminPin(adminPin);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Now we're ready to communicate with the token.
|
// Now we're ready to communicate with the token.
|
||||||
@@ -528,7 +519,7 @@ public class SecurityTokenHelper {
|
|||||||
try {
|
try {
|
||||||
secretKey.unlock(passphrase);
|
secretKey.unlock(passphrase);
|
||||||
|
|
||||||
setKeyAttributes(slot, secretKey);
|
setKeyAttributes(adminPin, slot, secretKey);
|
||||||
|
|
||||||
switch (mOpenPgpCapabilities.getFormatForKeyType(slot).keyFormatType()) {
|
switch (mOpenPgpCapabilities.getFormatForKeyType(slot).keyFormatType()) {
|
||||||
case RSAKeyFormatType:
|
case RSAKeyFormatType:
|
||||||
@@ -566,11 +557,11 @@ public class SecurityTokenHelper {
|
|||||||
throw new IOException(e.getMessage());
|
throw new IOException(e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
CommandAPDU apdu = new CommandAPDU(0x00, 0xDB, 0x3F, 0xFF, keyBytes);
|
CommandApdu apdu = commandFactory.createPutKeyCommand(keyBytes);
|
||||||
ResponseAPDU response = communicate(apdu);
|
ResponseApdu response = communicate(apdu);
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new CardException("Key export to Security Token failed", response.getSW());
|
throw new CardException("Key export to Security Token failed", response.getSw());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -581,29 +572,7 @@ public class SecurityTokenHelper {
|
|||||||
* @return The fingerprints of all subkeys in a contiguous byte array.
|
* @return The fingerprints of all subkeys in a contiguous byte array.
|
||||||
*/
|
*/
|
||||||
public byte[] getFingerprints() throws IOException {
|
public byte[] getFingerprints() throws IOException {
|
||||||
CommandAPDU apdu = new CommandAPDU(0x00, 0xCA, 0x00, 0x6E, MAX_APDU_NE_EXT);
|
return mOpenPgpCapabilities.getFingerprints();
|
||||||
ResponseAPDU response = communicate(apdu);
|
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
|
||||||
throw new CardException("Failed to get fingerprints", response.getSW());
|
|
||||||
}
|
|
||||||
|
|
||||||
Iso7816TLV[] tlvList = Iso7816TLV.readList(response.getData(), true);
|
|
||||||
Iso7816TLV fingerPrintTlv = null;
|
|
||||||
|
|
||||||
for (Iso7816TLV tlv : tlvList) {
|
|
||||||
Log.d(Constants.TAG, "nfcGetFingerprints() Iso7816TLV tlv data:\n" + tlv.prettyPrint());
|
|
||||||
|
|
||||||
Iso7816TLV matchingTlv = Iso7816TLV.findRecursive(tlv, 0xc5);
|
|
||||||
if (matchingTlv != null) {
|
|
||||||
fingerPrintTlv = matchingTlv;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fingerPrintTlv == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return fingerPrintTlv.mV;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -612,11 +581,11 @@ public class SecurityTokenHelper {
|
|||||||
* @return Seven bytes in fixed format, plus 0x9000 status word at the end.
|
* @return Seven bytes in fixed format, plus 0x9000 status word at the end.
|
||||||
*/
|
*/
|
||||||
private byte[] getPwStatusBytes() throws IOException {
|
private byte[] getPwStatusBytes() throws IOException {
|
||||||
return getData(0x00, 0xC4);
|
return mOpenPgpCapabilities.getPwStatusBytes();
|
||||||
}
|
}
|
||||||
|
|
||||||
public byte[] getAid() throws IOException {
|
public byte[] getAid() throws IOException {
|
||||||
return getData(0x00, 0x4F);
|
return mOpenPgpCapabilities.getAid();
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUrl() throws IOException {
|
public String getUrl() throws IOException {
|
||||||
@@ -629,9 +598,9 @@ public class SecurityTokenHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private byte[] getData(int p1, int p2) throws IOException {
|
private byte[] getData(int p1, int p2) throws IOException {
|
||||||
ResponseAPDU response = communicate(new CommandAPDU(0x00, 0xCA, p1, p2, MAX_APDU_NE_EXT));
|
ResponseApdu response = communicate(commandFactory.createGetDataCommand(p1, p2));
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new CardException("Failed to get pw status bytes", response.getSW());
|
throw new CardException("Failed to get pw status bytes", response.getSw());
|
||||||
}
|
}
|
||||||
return response.getData();
|
return response.getData();
|
||||||
}
|
}
|
||||||
@@ -644,7 +613,7 @@ public class SecurityTokenHelper {
|
|||||||
*/
|
*/
|
||||||
public byte[] calculateSignature(byte[] hash, int hashAlgo) throws IOException {
|
public byte[] calculateSignature(byte[] hash, int hashAlgo) throws IOException {
|
||||||
if (!mPw1ValidatedForSignature) {
|
if (!mPw1ValidatedForSignature) {
|
||||||
verifyPin(0x81); // (Verify PW1 with mode 81 for signing)
|
verifyPinForSignature();
|
||||||
}
|
}
|
||||||
|
|
||||||
byte[] dsi;
|
byte[] dsi;
|
||||||
@@ -711,11 +680,11 @@ public class SecurityTokenHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Command APDU for PERFORM SECURITY OPERATION: COMPUTE DIGITAL SIGNATURE (page 37)
|
// Command APDU for PERFORM SECURITY OPERATION: COMPUTE DIGITAL SIGNATURE (page 37)
|
||||||
CommandAPDU command = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, data, MAX_APDU_NE_EXT);
|
CommandApdu command = commandFactory.createComputeDigitalSignatureCommand(data);
|
||||||
ResponseAPDU response = communicate(command);
|
ResponseApdu response = communicate(command);
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new CardException("Failed to sign", response.getSW());
|
throw new CardException("Failed to sign", response.getSw());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mOpenPgpCapabilities.isPw1ValidForMultipleSignatures()) {
|
if (!mOpenPgpCapabilities.isPw1ValidForMultipleSignatures()) {
|
||||||
@@ -756,7 +725,6 @@ public class SecurityTokenHelper {
|
|||||||
return signature;
|
return signature;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Transceives APDU
|
* Transceives APDU
|
||||||
* Splits extended APDU into short APDUs and chains them if necessary
|
* Splits extended APDU into short APDUs and chains them if necessary
|
||||||
@@ -766,7 +734,7 @@ public class SecurityTokenHelper {
|
|||||||
* @return response from the card
|
* @return response from the card
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
ResponseAPDU communicate(CommandAPDU apdu) throws IOException {
|
ResponseApdu communicate(CommandApdu apdu) throws IOException {
|
||||||
if ((mSecureMessaging != null) && mSecureMessaging.isEstablished()) {
|
if ((mSecureMessaging != null) && mSecureMessaging.isEstablished()) {
|
||||||
try {
|
try {
|
||||||
apdu = mSecureMessaging.encryptAndSign(apdu);
|
apdu = mSecureMessaging.encryptAndSign(apdu);
|
||||||
@@ -776,53 +744,44 @@ public class SecurityTokenHelper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteArrayOutputStream result = new ByteArrayOutputStream();
|
ResponseApdu lastResponse = null;
|
||||||
|
|
||||||
ResponseAPDU lastResponse = null;
|
|
||||||
// Transmit
|
// Transmit
|
||||||
if (mCardCapabilities.hasExtended()) {
|
if (mCardCapabilities.hasExtended()) {
|
||||||
lastResponse = mTransport.transceive(apdu);
|
lastResponse = mTransport.transceive(apdu);
|
||||||
} else if (apdu.getData().length <= MAX_APDU_NC) {
|
} else if (commandFactory.isSuitableForShortApdu(apdu)) {
|
||||||
int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
|
CommandApdu shortApdu = commandFactory.createShortApdu(apdu);
|
||||||
lastResponse = mTransport.transceive(new CommandAPDU(apdu.getCLA(), apdu.getINS(),
|
lastResponse = mTransport.transceive(shortApdu);
|
||||||
apdu.getP1(), apdu.getP2(), apdu.getData(), ne));
|
} else if (mCardCapabilities.hasChaining()) {
|
||||||
} else if (apdu.getData().length > MAX_APDU_NC && mCardCapabilities.hasChaining()) {
|
List<CommandApdu> chainedApdus = commandFactory.createChainedApdus(apdu);
|
||||||
int offset = 0;
|
for (int i = 0, totalCommands = chainedApdus.size(); i < totalCommands; i++) {
|
||||||
byte[] data = apdu.getData();
|
CommandApdu chainedApdu = chainedApdus.get(i);
|
||||||
int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
|
lastResponse = mTransport.transceive(chainedApdu);
|
||||||
while (offset < data.length) {
|
|
||||||
int curLen = Math.min(MAX_APDU_NC, data.length - offset);
|
|
||||||
boolean last = offset + curLen >= data.length;
|
|
||||||
int cla = apdu.getCLA() + (last ? 0 : MASK_CLA_CHAINING);
|
|
||||||
|
|
||||||
lastResponse = mTransport.transceive(new CommandAPDU(cla, apdu.getINS(), apdu.getP1(),
|
boolean isLastCommand = i < totalCommands - 1;
|
||||||
apdu.getP2(), data, offset, curLen, ne));
|
if (isLastCommand && !lastResponse.isSuccess()) {
|
||||||
|
throw new UsbTransportException("Failed to chain apdu (last SW: " + lastResponse.getSw() + ")");
|
||||||
if (!last && lastResponse.getSW() != APDU_SW_SUCCESS) {
|
|
||||||
throw new UsbTransportException("Failed to chain apdu (last SW: " + lastResponse.getSW() + ")");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
offset += curLen;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (lastResponse == null) {
|
if (lastResponse == null) {
|
||||||
throw new UsbTransportException("Can't transmit command");
|
throw new UsbTransportException("Can't transmit command");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ByteArrayOutputStream result = new ByteArrayOutputStream();
|
||||||
result.write(lastResponse.getData());
|
result.write(lastResponse.getData());
|
||||||
|
|
||||||
// Receive
|
// Receive
|
||||||
while (lastResponse.getSW1() == APDU_SW1_RESPONSE_AVAILABLE) {
|
while (lastResponse.getSw1() == APDU_SW1_RESPONSE_AVAILABLE) {
|
||||||
// GET RESPONSE ISO/IEC 7816-4 par.7.6.1
|
// GET RESPONSE ISO/IEC 7816-4 par.7.6.1
|
||||||
CommandAPDU getResponse = new CommandAPDU(0x00, 0xC0, 0x00, 0x00, lastResponse.getSW2());
|
CommandApdu getResponse = commandFactory.createGetResponseCommand(lastResponse.getSw2());
|
||||||
lastResponse = mTransport.transceive(getResponse);
|
lastResponse = mTransport.transceive(getResponse);
|
||||||
result.write(lastResponse.getData());
|
result.write(lastResponse.getData());
|
||||||
}
|
}
|
||||||
|
|
||||||
result.write(lastResponse.getSW1());
|
result.write(lastResponse.getSw1());
|
||||||
result.write(lastResponse.getSW2());
|
result.write(lastResponse.getSw2());
|
||||||
|
|
||||||
lastResponse = new ResponseAPDU(result.toByteArray());
|
lastResponse = ResponseApdu.fromBytes(result.toByteArray());
|
||||||
|
|
||||||
if ((mSecureMessaging != null) && mSecureMessaging.isEstablished()) {
|
if ((mSecureMessaging != null) && mSecureMessaging.isEstablished()) {
|
||||||
try {
|
try {
|
||||||
@@ -836,22 +795,13 @@ public class SecurityTokenHelper {
|
|||||||
return lastResponse;
|
return lastResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Transport getTransport() {
|
|
||||||
return mTransport;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTransport(Transport mTransport) {
|
|
||||||
clearSecureMessaging();
|
|
||||||
this.mTransport = mTransport;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isFidesmoToken() {
|
public boolean isFidesmoToken() {
|
||||||
if (isConnected()) { // Check if we can still talk to the card
|
if (isConnected()) { // Check if we can still talk to the card
|
||||||
try {
|
try {
|
||||||
// By trying to select any apps that have the Fidesmo AID prefix we can
|
// By trying to select any apps that have the Fidesmo AID prefix we can
|
||||||
// see if it is a Fidesmo device or not
|
// see if it is a Fidesmo device or not
|
||||||
CommandAPDU apdu = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, Hex.decode(FIDESMO_APPS_AID_PREFIX));
|
CommandApdu apdu = commandFactory.createSelectFileCommand(FIDESMO_APPS_AID_PREFIX);
|
||||||
return communicate(apdu).getSW() == APDU_SW_SUCCESS;
|
return communicate(apdu).isSuccess();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
Log.e(Constants.TAG, "Card communication failed!", e);
|
Log.e(Constants.TAG, "Card communication failed!", e);
|
||||||
}
|
}
|
||||||
@@ -873,30 +823,25 @@ public class SecurityTokenHelper {
|
|||||||
* @return the public key data objects, in TLV format. For RSA this will be the public modulus
|
* @return the public key data objects, in TLV format. For RSA this will be the public modulus
|
||||||
* (0x81) and exponent (0x82). These may come out of order; proper TLV parsing is required.
|
* (0x81) and exponent (0x82). These may come out of order; proper TLV parsing is required.
|
||||||
*/
|
*/
|
||||||
public byte[] generateKey(int slot) throws IOException {
|
public byte[] generateKey(Passphrase adminPin, int slot) throws IOException {
|
||||||
if (slot != 0xB6 && slot != 0xB8 && slot != 0xA4) {
|
if (slot != 0xB6 && slot != 0xB8 && slot != 0xA4) {
|
||||||
throw new IOException("Invalid key slot");
|
throw new IOException("Invalid key slot");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mPw3Validated) {
|
if (!mPw3Validated) {
|
||||||
verifyPin(0x83); // (Verify PW3 with mode 83)
|
verifyAdminPin(adminPin);
|
||||||
}
|
}
|
||||||
|
|
||||||
CommandAPDU apdu = new CommandAPDU(0x00, 0x47, 0x80, 0x00, new byte[]{(byte) slot, 0x00}, MAX_APDU_NE_EXT);
|
CommandApdu apdu = commandFactory.createGenerateKeyCommand(slot);
|
||||||
ResponseAPDU response = communicate(apdu);
|
ResponseApdu response = communicate(apdu);
|
||||||
|
|
||||||
if (response.getSW() != APDU_SW_SUCCESS) {
|
if (!response.isSuccess()) {
|
||||||
throw new IOException("On-card key generation failed");
|
throw new IOException("On-card key generation failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.getData();
|
return response.getData();
|
||||||
}
|
}
|
||||||
|
|
||||||
private ResponseAPDU tryPin(int mode, byte[] pin) throws IOException {
|
|
||||||
// Command APDU for VERIFY command (page 32)
|
|
||||||
return communicate(new CommandAPDU(0x00, 0x20, 0x00, mode, pin));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resets security token, which deletes all keys and data objects.
|
* Resets security token, which deletes all keys and data objects.
|
||||||
* This works by entering a wrong PIN and then Admin PIN 4 times respectively.
|
* This works by entering a wrong PIN and then Admin PIN 4 times respectively.
|
||||||
@@ -906,18 +851,20 @@ public class SecurityTokenHelper {
|
|||||||
// try wrong PIN 4 times until counter goes to C0
|
// try wrong PIN 4 times until counter goes to C0
|
||||||
byte[] pin = "XXXXXX".getBytes();
|
byte[] pin = "XXXXXX".getBytes();
|
||||||
for (int i = 0; i <= 4; i++) {
|
for (int i = 0; i <= 4; i++) {
|
||||||
ResponseAPDU response = tryPin(0x81, pin);
|
// Command APDU for VERIFY command (page 32)
|
||||||
if (response.getSW() == APDU_SW_SUCCESS) { // Should NOT accept!
|
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForSignatureCommand(pin));
|
||||||
throw new CardException("Should never happen, XXXXXX has been accepted!", response.getSW());
|
if (response.isSuccess()) {
|
||||||
|
throw new CardException("Should never happen, XXXXXX has been accepted!", response.getSw());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// try wrong Admin PIN 4 times until counter goes to C0
|
// try wrong Admin PIN 4 times until counter goes to C0
|
||||||
byte[] adminPin = "XXXXXXXX".getBytes();
|
byte[] adminPin = "XXXXXXXX".getBytes();
|
||||||
for (int i = 0; i <= 4; i++) {
|
for (int i = 0; i <= 4; i++) {
|
||||||
ResponseAPDU response = tryPin(0x83, adminPin);
|
// Command APDU for VERIFY command (page 32)
|
||||||
if (response.getSW() == APDU_SW_SUCCESS) { // Should NOT accept!
|
ResponseApdu response = communicate(commandFactory.createVerifyPw3Command(adminPin));
|
||||||
throw new CardException("Should never happen, XXXXXXXX has been accepted", response.getSW());
|
if (response.isSuccess()) { // Should NOT accept!
|
||||||
|
throw new CardException("Should never happen, XXXXXXXX has been accepted", response.getSw());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -927,15 +874,15 @@ public class SecurityTokenHelper {
|
|||||||
// reactivate token!
|
// reactivate token!
|
||||||
// NOTE: keep the order here! First execute _both_ reactivate commands. Before checking _both_ responses
|
// NOTE: keep the order here! First execute _both_ reactivate commands. Before checking _both_ responses
|
||||||
// If a token is in a bad state and reactivate1 fails, it could still be reactivated with reactivate2
|
// If a token is in a bad state and reactivate1 fails, it could still be reactivated with reactivate2
|
||||||
CommandAPDU reactivate1 = new CommandAPDU(0x00, 0xE6, 0x00, 0x00);
|
CommandApdu reactivate1 = commandFactory.createReactivate1Command();
|
||||||
CommandAPDU reactivate2 = new CommandAPDU(0x00, 0x44, 0x00, 0x00);
|
CommandApdu reactivate2 = commandFactory.createReactivate2Command();
|
||||||
ResponseAPDU response1 = communicate(reactivate1);
|
ResponseApdu response1 = communicate(reactivate1);
|
||||||
ResponseAPDU response2 = communicate(reactivate2);
|
ResponseApdu response2 = communicate(reactivate2);
|
||||||
if (response1.getSW() != APDU_SW_SUCCESS) {
|
if (!response1.isSuccess()) {
|
||||||
throw new CardException("Reactivating failed!", response1.getSW());
|
throw new CardException("Reactivating failed!", response1.getSw());
|
||||||
}
|
}
|
||||||
if (response2.getSW() != APDU_SW_SUCCESS) {
|
if (!response2.isSuccess()) {
|
||||||
throw new CardException("Reactivating failed!", response2.getSW());
|
throw new CardException("Reactivating failed!", response2.getSw());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -962,14 +909,12 @@ public class SecurityTokenHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean isPersistentConnectionAllowed() {
|
public boolean isPersistentConnectionAllowed() {
|
||||||
return mTransport != null &&
|
return mTransport.isPersistentConnectionAllowed() &&
|
||||||
mTransport.isPersistentConnectionAllowed() &&
|
(mSecureMessaging == null || !mSecureMessaging.isEstablished());
|
||||||
(mSecureMessaging == null ||
|
|
||||||
!mSecureMessaging.isEstablished());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isConnected() {
|
public boolean isConnected() {
|
||||||
return mTransport != null && mTransport.isConnected();
|
return mTransport.isConnected();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void clearSecureMessaging() {
|
public void clearSecureMessaging() {
|
||||||
@@ -1006,7 +951,9 @@ public class SecurityTokenHelper {
|
|||||||
return SecurityTokenInfo.create(fingerprints, aid, userId, url, pwInfo[4], pwInfo[6]);
|
return SecurityTokenInfo.create(fingerprints, aid, userId, url, pwInfo[4], pwInfo[6]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class LazyHolder {
|
public static double parseOpenPgpVersion(final byte[] aid) {
|
||||||
private static final SecurityTokenHelper SECURITY_TOKEN_HELPER = new SecurityTokenHelper();
|
float minv = aid[7];
|
||||||
|
while (minv > 0) minv /= 10.0;
|
||||||
|
return aid[6] + minv;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -33,8 +33,8 @@ import java.security.interfaces.ECPrivateKey;
|
|||||||
import java.security.interfaces.ECPublicKey;
|
import java.security.interfaces.ECPublicKey;
|
||||||
import java.security.interfaces.RSAPrivateCrtKey;
|
import java.security.interfaces.RSAPrivateCrtKey;
|
||||||
|
|
||||||
public class SecurityTokenUtils {
|
class SecurityTokenUtils {
|
||||||
public static byte[] attributesFromSecretKey(final KeyType slot, final CanonicalizedSecretKey secretKey) throws IOException, PgpGeneralException {
|
static byte[] attributesFromSecretKey(final KeyType slot, final CanonicalizedSecretKey secretKey) throws IOException, PgpGeneralException {
|
||||||
if (secretKey.isRSA()) {
|
if (secretKey.isRSA()) {
|
||||||
final int mModulusLength = secretKey.getBitStrength();
|
final int mModulusLength = secretKey.getBitStrength();
|
||||||
final int mExponentLength = secretKey.getSecurityTokenRSASecretKey().getPublicExponent().bitLength();
|
final int mExponentLength = secretKey.getSecurityTokenRSASecretKey().getPublicExponent().bitLength();
|
||||||
@@ -46,7 +46,7 @@ public class SecurityTokenUtils {
|
|||||||
attrs[i++] = (byte) (mModulusLength & 0xff);
|
attrs[i++] = (byte) (mModulusLength & 0xff);
|
||||||
attrs[i++] = (byte) ((mExponentLength >> 8) & 0xff);
|
attrs[i++] = (byte) ((mExponentLength >> 8) & 0xff);
|
||||||
attrs[i++] = (byte) (mExponentLength & 0xff);
|
attrs[i++] = (byte) (mExponentLength & 0xff);
|
||||||
attrs[i++] = RSAKeyFormat.RSAAlgorithmFormat.CRT_WITH_MODULUS.getValue();
|
attrs[i] = RSAKeyFormat.RSAAlgorithmFormat.CRT_WITH_MODULUS.getValue();
|
||||||
|
|
||||||
return attrs;
|
return attrs;
|
||||||
} else if (secretKey.isEC()) {
|
} else if (secretKey.isEC()) {
|
||||||
@@ -70,8 +70,8 @@ public class SecurityTokenUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static byte[] createRSAPrivKeyTemplate(RSAPrivateCrtKey secretKey, KeyType slot,
|
static byte[] createRSAPrivKeyTemplate(RSAPrivateCrtKey secretKey, KeyType slot,
|
||||||
RSAKeyFormat format) throws IOException {
|
RSAKeyFormat format) throws IOException {
|
||||||
ByteArrayOutputStream stream = new ByteArrayOutputStream(),
|
ByteArrayOutputStream stream = new ByteArrayOutputStream(),
|
||||||
template = new ByteArrayOutputStream(),
|
template = new ByteArrayOutputStream(),
|
||||||
data = new ByteArrayOutputStream(),
|
data = new ByteArrayOutputStream(),
|
||||||
@@ -138,8 +138,8 @@ public class SecurityTokenUtils {
|
|||||||
return res.toByteArray();
|
return res.toByteArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static byte[] createECPrivKeyTemplate(ECPrivateKey secretKey, ECPublicKey publicKey, KeyType slot,
|
static byte[] createECPrivKeyTemplate(ECPrivateKey secretKey, ECPublicKey publicKey, KeyType slot,
|
||||||
ECKeyFormat format) throws IOException {
|
ECKeyFormat format) throws IOException {
|
||||||
ByteArrayOutputStream stream = new ByteArrayOutputStream(),
|
ByteArrayOutputStream stream = new ByteArrayOutputStream(),
|
||||||
template = new ByteArrayOutputStream(),
|
template = new ByteArrayOutputStream(),
|
||||||
data = new ByteArrayOutputStream(),
|
data = new ByteArrayOutputStream(),
|
||||||
@@ -184,7 +184,7 @@ public class SecurityTokenUtils {
|
|||||||
return res.toByteArray();
|
return res.toByteArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static byte[] encodeLength(int len) {
|
static byte[] encodeLength(int len) {
|
||||||
if (len < 0) {
|
if (len < 0) {
|
||||||
throw new IllegalArgumentException("length is negative");
|
throw new IllegalArgumentException("length is negative");
|
||||||
} else if (len >= 16777216) {
|
} else if (len >= 16777216) {
|
||||||
@@ -214,7 +214,7 @@ public class SecurityTokenUtils {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeBits(ByteArrayOutputStream stream, BigInteger value, int width) {
|
static void writeBits(ByteArrayOutputStream stream, BigInteger value, int width) {
|
||||||
if (value.signum() == -1) {
|
if (value.signum() == -1) {
|
||||||
throw new IllegalArgumentException("value is negative");
|
throw new IllegalArgumentException("value is negative");
|
||||||
} else if (width <= 0) {
|
} else if (width <= 0) {
|
||||||
|
|||||||
@@ -17,9 +17,6 @@
|
|||||||
|
|
||||||
package org.sufficientlysecure.keychain.securitytoken;
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
import javax.smartcardio.CommandAPDU;
|
|
||||||
import javax.smartcardio.ResponseAPDU;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,7 +29,7 @@ public interface Transport {
|
|||||||
* @return received data
|
* @return received data
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
ResponseAPDU transceive(CommandAPDU data) throws IOException;
|
ResponseApdu transceive(CommandApdu data) throws IOException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disconnect and release connection
|
* Disconnect and release connection
|
||||||
|
|||||||
@@ -29,8 +29,8 @@ import android.util.Pair;
|
|||||||
|
|
||||||
import org.sufficientlysecure.keychain.Constants;
|
import org.sufficientlysecure.keychain.Constants;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.Transport;
|
import org.sufficientlysecure.keychain.securitytoken.Transport;
|
||||||
import javax.smartcardio.CommandAPDU;
|
import org.sufficientlysecure.keychain.securitytoken.CommandApdu;
|
||||||
import javax.smartcardio.ResponseAPDU;
|
import org.sufficientlysecure.keychain.securitytoken.ResponseApdu;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.usb.tpdu.T1ShortApduProtocol;
|
import org.sufficientlysecure.keychain.securitytoken.usb.tpdu.T1ShortApduProtocol;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.usb.tpdu.T1TpduProtocol;
|
import org.sufficientlysecure.keychain.securitytoken.usb.tpdu.T1TpduProtocol;
|
||||||
import org.sufficientlysecure.keychain.util.Log;
|
import org.sufficientlysecure.keychain.util.Log;
|
||||||
@@ -183,8 +183,8 @@ public class UsbTransport implements Transport {
|
|||||||
* @return received data
|
* @return received data
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public ResponseAPDU transceive(CommandAPDU data) throws UsbTransportException {
|
public ResponseApdu transceive(CommandApdu data) throws UsbTransportException {
|
||||||
return new ResponseAPDU(ccidTransportProtocol.transceive(data.getBytes()));
|
return ResponseApdu.fromBytes(ccidTransportProtocol.transceive(data.toBytes()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import android.support.v4.app.TaskStackBuilder;
|
|||||||
|
|
||||||
import org.sufficientlysecure.keychain.R;
|
import org.sufficientlysecure.keychain.R;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
|
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
|
||||||
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
||||||
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
|
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
|
||||||
import org.sufficientlysecure.keychain.ui.token.ManageSecurityTokenFragment;
|
import org.sufficientlysecure.keychain.ui.token.ManageSecurityTokenFragment;
|
||||||
@@ -133,17 +134,17 @@ public class CreateKeyActivity extends BaseSecurityTokenActivity {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doSecurityTokenInBackground() throws IOException {
|
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
|
||||||
if (mCurrentFragment instanceof SecurityTokenListenerFragment) {
|
if (mCurrentFragment instanceof SecurityTokenListenerFragment) {
|
||||||
((SecurityTokenListenerFragment) mCurrentFragment).doSecurityTokenInBackground();
|
((SecurityTokenListenerFragment) mCurrentFragment).doSecurityTokenInBackground();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
tokenInfo = mSecurityTokenHelper.getTokenInfo();
|
tokenInfo = stConnection.getTokenInfo();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void onSecurityTokenPostExecute() {
|
protected void onSecurityTokenPostExecute(SecurityTokenConnection stConnection) {
|
||||||
handleTokenInfo(tokenInfo);
|
handleTokenInfo(tokenInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ import android.widget.TextView;
|
|||||||
|
|
||||||
import org.sufficientlysecure.keychain.R;
|
import org.sufficientlysecure.keychain.R;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
|
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenHelper;
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||||
import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction;
|
import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction;
|
||||||
import org.sufficientlysecure.keychain.util.Choice;
|
import org.sufficientlysecure.keychain.util.Choice;
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ public class CreateSecurityTokenAlgorithmFragment extends Fragment {
|
|||||||
choices.add(new Choice<>(SupportedKeyType.RSA_4096, getResources().getString(
|
choices.add(new Choice<>(SupportedKeyType.RSA_4096, getResources().getString(
|
||||||
R.string.rsa_4096), getResources().getString(R.string.rsa_4096_description_html)));
|
R.string.rsa_4096), getResources().getString(R.string.rsa_4096_description_html)));
|
||||||
|
|
||||||
final double version = SecurityTokenHelper.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
|
final double version = SecurityTokenConnection.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
|
||||||
|
|
||||||
if (version >= 3.0) {
|
if (version >= 3.0) {
|
||||||
choices.add(new Choice<>(SupportedKeyType.ECC_P256, getResources().getString(
|
choices.add(new Choice<>(SupportedKeyType.ECC_P256, getResources().getString(
|
||||||
|
|||||||
@@ -17,7 +17,6 @@
|
|||||||
|
|
||||||
package org.sufficientlysecure.keychain.ui;
|
package org.sufficientlysecure.keychain.ui;
|
||||||
|
|
||||||
import android.app.Activity;
|
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.os.AsyncTask;
|
import android.os.AsyncTask;
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
@@ -31,7 +30,7 @@ import android.widget.TextView;
|
|||||||
|
|
||||||
import org.sufficientlysecure.keychain.Constants;
|
import org.sufficientlysecure.keychain.Constants;
|
||||||
import org.sufficientlysecure.keychain.R;
|
import org.sufficientlysecure.keychain.R;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenHelper;
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||||
import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction;
|
import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction;
|
||||||
import org.sufficientlysecure.keychain.util.Passphrase;
|
import org.sufficientlysecure.keychain.util.Passphrase;
|
||||||
|
|
||||||
@@ -206,7 +205,7 @@ public class CreateSecurityTokenPinFragment extends Fragment {
|
|||||||
|
|
||||||
mCreateKeyActivity.mSecurityTokenPin = new Passphrase(mPin.getText().toString());
|
mCreateKeyActivity.mSecurityTokenPin = new Passphrase(mPin.getText().toString());
|
||||||
|
|
||||||
final double version = SecurityTokenHelper.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
|
final double version = SecurityTokenConnection.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
|
||||||
|
|
||||||
Fragment frag;
|
Fragment frag;
|
||||||
if (version >= 3.0) {
|
if (version >= 3.0) {
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import android.widget.ViewAnimator;
|
|||||||
import nordpol.android.NfcGuideView;
|
import nordpol.android.NfcGuideView;
|
||||||
import org.sufficientlysecure.keychain.Constants;
|
import org.sufficientlysecure.keychain.Constants;
|
||||||
import org.sufficientlysecure.keychain.R;
|
import org.sufficientlysecure.keychain.R;
|
||||||
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
||||||
import org.sufficientlysecure.keychain.service.input.SecurityTokenChangePinParcel;
|
import org.sufficientlysecure.keychain.service.input.SecurityTokenChangePinParcel;
|
||||||
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
|
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
|
||||||
@@ -138,15 +139,15 @@ public class SecurityTokenChangePinOperationActivity extends BaseSecurityTokenAc
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doSecurityTokenInBackground() throws IOException {
|
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
|
||||||
mSecurityTokenHelper.setAdminPin(new Passphrase(changePinInput.getAdminPin()));
|
Passphrase adminPin = new Passphrase(changePinInput.getAdminPin());
|
||||||
mSecurityTokenHelper.resetPin(changePinInput.getNewPin());
|
stConnection.resetPin(changePinInput.getNewPin().getBytes(), adminPin);
|
||||||
|
|
||||||
resultTokenInfo = mSecurityTokenHelper.getTokenInfo();
|
resultTokenInfo = stConnection.getTokenInfo();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected final void onSecurityTokenPostExecute() {
|
protected final void onSecurityTokenPostExecute(final SecurityTokenConnection stConnection) {
|
||||||
Intent result = new Intent();
|
Intent result = new Intent();
|
||||||
result.putExtra(RESULT_TOKEN_INFO, resultTokenInfo);
|
result.putExtra(RESULT_TOKEN_INFO, resultTokenInfo);
|
||||||
setResult(RESULT_OK, result);
|
setResult(RESULT_OK, result);
|
||||||
@@ -156,17 +157,17 @@ public class SecurityTokenChangePinOperationActivity extends BaseSecurityTokenAc
|
|||||||
|
|
||||||
nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE);
|
nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE);
|
||||||
|
|
||||||
if (mSecurityTokenHelper.isPersistentConnectionAllowed()) {
|
if (stConnection.isPersistentConnectionAllowed()) {
|
||||||
// Just close
|
// Just close
|
||||||
finish();
|
finish();
|
||||||
} else {
|
} else {
|
||||||
mSecurityTokenHelper.clearSecureMessaging();
|
stConnection.clearSecureMessaging();
|
||||||
new AsyncTask<Void, Void, Void>() {
|
new AsyncTask<Void, Void, Void>() {
|
||||||
@Override
|
@Override
|
||||||
protected Void doInBackground(Void... params) {
|
protected Void doInBackground(Void... params) {
|
||||||
// check all 200ms if Security Token has been taken away
|
// check all 200ms if Security Token has been taken away
|
||||||
while (true) {
|
while (true) {
|
||||||
if (isSecurityTokenConnected()) {
|
if (stConnection.isConnected()) {
|
||||||
try {
|
try {
|
||||||
Thread.sleep(200);
|
Thread.sleep(200);
|
||||||
} catch (InterruptedException ignored) {
|
} catch (InterruptedException ignored) {
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing;
|
|||||||
import org.sufficientlysecure.keychain.provider.KeyRepository;
|
import org.sufficientlysecure.keychain.provider.KeyRepository;
|
||||||
import org.sufficientlysecure.keychain.provider.KeychainContract;
|
import org.sufficientlysecure.keychain.provider.KeychainContract;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.KeyType;
|
import org.sufficientlysecure.keychain.securitytoken.KeyType;
|
||||||
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
||||||
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
|
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
|
||||||
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
|
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
|
||||||
@@ -185,12 +186,12 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doSecurityTokenInBackground() throws IOException {
|
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
|
||||||
|
|
||||||
switch (mRequiredInput.mType) {
|
switch (mRequiredInput.mType) {
|
||||||
case SECURITY_TOKEN_DECRYPT: {
|
case SECURITY_TOKEN_DECRYPT: {
|
||||||
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
|
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
|
||||||
mSecurityTokenHelper.getKeyFingerprint(KeyType.ENCRYPT));
|
stConnection.getKeyFingerprint(KeyType.ENCRYPT));
|
||||||
|
|
||||||
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
|
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
|
||||||
throw new IOException(getString(R.string.error_wrong_security_token));
|
throw new IOException(getString(R.string.error_wrong_security_token));
|
||||||
@@ -208,14 +209,15 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
|||||||
|
|
||||||
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
|
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
|
||||||
byte[] encryptedSessionKey = mRequiredInput.mInputData[i];
|
byte[] encryptedSessionKey = mRequiredInput.mInputData[i];
|
||||||
byte[] decryptedSessionKey = mSecurityTokenHelper.decryptSessionKey(encryptedSessionKey, publicKeyRing.getPublicKey(tokenKeyId));
|
byte[] decryptedSessionKey = stConnection
|
||||||
|
.decryptSessionKey(encryptedSessionKey, publicKeyRing.getPublicKey(tokenKeyId));
|
||||||
mInputParcel = mInputParcel.withCryptoData(encryptedSessionKey, decryptedSessionKey);
|
mInputParcel = mInputParcel.withCryptoData(encryptedSessionKey, decryptedSessionKey);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SECURITY_TOKEN_SIGN: {
|
case SECURITY_TOKEN_SIGN: {
|
||||||
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
|
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
|
||||||
mSecurityTokenHelper.getKeyFingerprint(KeyType.SIGN));
|
stConnection.getKeyFingerprint(KeyType.SIGN));
|
||||||
|
|
||||||
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
|
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
|
||||||
throw new IOException(getString(R.string.error_wrong_security_token));
|
throw new IOException(getString(R.string.error_wrong_security_token));
|
||||||
@@ -226,15 +228,13 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
|||||||
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
|
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
|
||||||
byte[] hash = mRequiredInput.mInputData[i];
|
byte[] hash = mRequiredInput.mInputData[i];
|
||||||
int algo = mRequiredInput.mSignAlgos[i];
|
int algo = mRequiredInput.mSignAlgos[i];
|
||||||
byte[] signedHash = mSecurityTokenHelper.calculateSignature(hash, algo);
|
byte[] signedHash = stConnection.calculateSignature(hash, algo);
|
||||||
mInputParcel = mInputParcel.withCryptoData(hash, signedHash);
|
mInputParcel = mInputParcel.withCryptoData(hash, signedHash);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SECURITY_TOKEN_MOVE_KEY_TO_CARD: {
|
case SECURITY_TOKEN_MOVE_KEY_TO_CARD: {
|
||||||
// TODO: assume PIN and Admin PIN to be default for this operation
|
Passphrase adminPin = new Passphrase("12345678");
|
||||||
mSecurityTokenHelper.setPin(new Passphrase("123456"));
|
|
||||||
mSecurityTokenHelper.setAdminPin(new Passphrase("12345678"));
|
|
||||||
|
|
||||||
KeyRepository keyRepository =
|
KeyRepository keyRepository =
|
||||||
KeyRepository.create(this);
|
KeyRepository.create(this);
|
||||||
@@ -256,7 +256,7 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
|||||||
long subkeyId = buf.getLong();
|
long subkeyId = buf.getLong();
|
||||||
|
|
||||||
CanonicalizedSecretKey key = secretKeyRing.getSecretKey(subkeyId);
|
CanonicalizedSecretKey key = secretKeyRing.getSecretKey(subkeyId);
|
||||||
byte[] tokenSerialNumber = Arrays.copyOf(mSecurityTokenHelper.getAid(), 16);
|
byte[] tokenSerialNumber = Arrays.copyOf(stConnection.getAid(), 16);
|
||||||
|
|
||||||
Passphrase passphrase;
|
Passphrase passphrase;
|
||||||
try {
|
try {
|
||||||
@@ -266,21 +266,21 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
|||||||
throw new IOException("Unable to get cached passphrase!");
|
throw new IOException("Unable to get cached passphrase!");
|
||||||
}
|
}
|
||||||
|
|
||||||
mSecurityTokenHelper.changeKey(key, passphrase);
|
stConnection.changeKey(key, passphrase, adminPin);
|
||||||
|
|
||||||
// TODO: Is this really used anywhere?
|
// TODO: Is this really used anywhere?
|
||||||
mInputParcel = mInputParcel.withCryptoData(subkeyBytes, tokenSerialNumber);
|
mInputParcel = mInputParcel.withCryptoData(subkeyBytes, tokenSerialNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
// change PINs afterwards
|
// change PINs afterwards
|
||||||
mSecurityTokenHelper.modifyPin(0x81, newPin);
|
stConnection.resetPin(newPin, adminPin);
|
||||||
mSecurityTokenHelper.modifyPin(0x83, newAdminPin);
|
stConnection.modifyPw3Pin(newAdminPin, adminPin);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SECURITY_TOKEN_RESET_CARD: {
|
case SECURITY_TOKEN_RESET_CARD: {
|
||||||
mSecurityTokenHelper.resetAndWipeToken();
|
stConnection.resetAndWipeToken();
|
||||||
mResultTokenInfo = mSecurityTokenHelper.getTokenInfo();
|
mResultTokenInfo = stConnection.getTokenInfo();
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -292,7 +292,7 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected final void onSecurityTokenPostExecute() {
|
protected final void onSecurityTokenPostExecute(final SecurityTokenConnection stConnection) {
|
||||||
handleResult(mInputParcel);
|
handleResult(mInputParcel);
|
||||||
|
|
||||||
// show finish
|
// show finish
|
||||||
@@ -300,17 +300,17 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
|||||||
|
|
||||||
nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE);
|
nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE);
|
||||||
|
|
||||||
if (mSecurityTokenHelper.isPersistentConnectionAllowed()) {
|
if (stConnection.isPersistentConnectionAllowed()) {
|
||||||
// Just close
|
// Just close
|
||||||
finish();
|
finish();
|
||||||
} else {
|
} else {
|
||||||
mSecurityTokenHelper.clearSecureMessaging();
|
stConnection.clearSecureMessaging();
|
||||||
new AsyncTask<Void, Void, Void>() {
|
new AsyncTask<Void, Void, Void>() {
|
||||||
@Override
|
@Override
|
||||||
protected Void doInBackground(Void... params) {
|
protected Void doInBackground(Void... params) {
|
||||||
// check all 200ms if Security Token has been taken away
|
// check all 200ms if Security Token has been taken away
|
||||||
while (true) {
|
while (true) {
|
||||||
if (isSecurityTokenConnected()) {
|
if (stConnection.isConnected()) {
|
||||||
try {
|
try {
|
||||||
Thread.sleep(200);
|
Thread.sleep(200);
|
||||||
} catch (InterruptedException ignored) {
|
} catch (InterruptedException ignored) {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import android.view.animation.DecelerateInterpolator;
|
|||||||
|
|
||||||
import org.sufficientlysecure.keychain.R;
|
import org.sufficientlysecure.keychain.R;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.NfcSweetspotData;
|
import org.sufficientlysecure.keychain.securitytoken.NfcSweetspotData;
|
||||||
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||||
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
|
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
|
||||||
|
|
||||||
|
|
||||||
@@ -88,7 +89,7 @@ public class ShowNfcSweetspotActivity extends BaseSecurityTokenActivity {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void onSecurityTokenPostExecute() {
|
protected void onSecurityTokenPostExecute(SecurityTokenConnection stConnection) {
|
||||||
Intent result = new Intent();
|
Intent result = new Intent();
|
||||||
result.putExtra(EXTRA_TOKEN_INFO, tokenInfo);
|
result.putExtra(EXTRA_TOKEN_INFO, tokenInfo);
|
||||||
setResult(Activity.RESULT_OK, result);
|
setResult(Activity.RESULT_OK, result);
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ import org.sufficientlysecure.keychain.Constants;
|
|||||||
import org.sufficientlysecure.keychain.R;
|
import org.sufficientlysecure.keychain.R;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.CardException;
|
import org.sufficientlysecure.keychain.securitytoken.CardException;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.NfcTransport;
|
import org.sufficientlysecure.keychain.securitytoken.NfcTransport;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenHelper;
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.Transport;
|
import org.sufficientlysecure.keychain.securitytoken.Transport;
|
||||||
import org.sufficientlysecure.keychain.securitytoken.UsbConnectionDispatcher;
|
import org.sufficientlysecure.keychain.securitytoken.UsbConnectionDispatcher;
|
||||||
@@ -68,12 +68,12 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
|
|
||||||
private static final String FIDESMO_APP_PACKAGE = "com.fidesmo.sec.android";
|
private static final String FIDESMO_APP_PACKAGE = "com.fidesmo.sec.android";
|
||||||
|
|
||||||
protected SecurityTokenHelper mSecurityTokenHelper = SecurityTokenHelper.getInstance();
|
|
||||||
protected TagDispatcher mNfcTagDispatcher;
|
protected TagDispatcher mNfcTagDispatcher;
|
||||||
protected UsbConnectionDispatcher mUsbDispatcher;
|
protected UsbConnectionDispatcher mUsbDispatcher;
|
||||||
private boolean mTagHandlingEnabled;
|
private boolean mTagHandlingEnabled;
|
||||||
|
|
||||||
protected SecurityTokenInfo tokenInfo;
|
protected SecurityTokenInfo tokenInfo;
|
||||||
|
private Passphrase mCachedPin;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Override to change UI before SecurityToken handling (UI thread)
|
* Override to change UI before SecurityToken handling (UI thread)
|
||||||
@@ -84,15 +84,15 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
/**
|
/**
|
||||||
* Override to implement SecurityToken operations (background thread)
|
* Override to implement SecurityToken operations (background thread)
|
||||||
*/
|
*/
|
||||||
protected void doSecurityTokenInBackground() throws IOException {
|
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
|
||||||
tokenInfo = mSecurityTokenHelper.getTokenInfo();
|
tokenInfo = stConnection.getTokenInfo();
|
||||||
Log.d(Constants.TAG, "Security Token: " + tokenInfo);
|
Log.d(Constants.TAG, "Security Token: " + tokenInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Override to handle result of SecurityToken operations (UI thread)
|
* Override to handle result of SecurityToken operations (UI thread)
|
||||||
*/
|
*/
|
||||||
protected void onSecurityTokenPostExecute() {
|
protected void onSecurityTokenPostExecute(SecurityTokenConnection stConnection) {
|
||||||
Intent intent = new Intent(this, CreateKeyActivity.class);
|
Intent intent = new Intent(this, CreateKeyActivity.class);
|
||||||
intent.putExtra(CreateKeyActivity.EXTRA_SECURITY_TOKEN_INFO, tokenInfo);
|
intent.putExtra(CreateKeyActivity.EXTRA_SECURITY_TOKEN_INFO, tokenInfo);
|
||||||
startActivity(intent);
|
startActivity(intent);
|
||||||
@@ -138,6 +138,10 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
// Actual Security Token operations are executed in doInBackground to not block the UI thread
|
// Actual Security Token operations are executed in doInBackground to not block the UI thread
|
||||||
if (!mTagHandlingEnabled)
|
if (!mTagHandlingEnabled)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
final SecurityTokenConnection stConnection =
|
||||||
|
SecurityTokenConnection.getInstanceForTransport(transport, mCachedPin);
|
||||||
|
|
||||||
new AsyncTask<Void, Void, IOException>() {
|
new AsyncTask<Void, Void, IOException>() {
|
||||||
@Override
|
@Override
|
||||||
protected void onPreExecute() {
|
protected void onPreExecute() {
|
||||||
@@ -148,7 +152,9 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
@Override
|
@Override
|
||||||
protected IOException doInBackground(Void... params) {
|
protected IOException doInBackground(Void... params) {
|
||||||
try {
|
try {
|
||||||
handleSecurityToken(transport, BaseSecurityTokenActivity.this);
|
stConnection.connectIfNecessary(getBaseContext());
|
||||||
|
|
||||||
|
handleSecurityToken(stConnection);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
@@ -161,11 +167,11 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
super.onPostExecute(exception);
|
super.onPostExecute(exception);
|
||||||
|
|
||||||
if (exception != null) {
|
if (exception != null) {
|
||||||
handleSecurityTokenError(exception);
|
handleSecurityTokenError(stConnection, exception);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
onSecurityTokenPostExecute();
|
onSecurityTokenPostExecute(stConnection);
|
||||||
}
|
}
|
||||||
}.execute();
|
}.execute();
|
||||||
}
|
}
|
||||||
@@ -223,7 +229,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
mNfcTagDispatcher.interceptIntent(intent);
|
mNfcTagDispatcher.interceptIntent(intent);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleSecurityTokenError(IOException e) {
|
private void handleSecurityTokenError(SecurityTokenConnection stConnection, IOException e) {
|
||||||
|
|
||||||
if (e instanceof TagLostException) {
|
if (e instanceof TagLostException) {
|
||||||
onSecurityTokenError(getString(R.string.security_token_error_tag_lost));
|
onSecurityTokenError(getString(R.string.security_token_error_tag_lost));
|
||||||
@@ -250,7 +256,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
|
|
||||||
SecurityTokenInfo tokeninfo = null;
|
SecurityTokenInfo tokeninfo = null;
|
||||||
try {
|
try {
|
||||||
tokeninfo = mSecurityTokenHelper.getTokenInfo();
|
tokeninfo = stConnection.getTokenInfo();
|
||||||
} catch (IOException e2) {
|
} catch (IOException e2) {
|
||||||
// don't care
|
// don't care
|
||||||
}
|
}
|
||||||
@@ -260,6 +266,8 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Log.d(Constants.TAG, "security token exception", e);
|
||||||
|
|
||||||
// Otherwise, all status codes are fixed values.
|
// Otherwise, all status codes are fixed values.
|
||||||
switch (status) {
|
switch (status) {
|
||||||
|
|
||||||
@@ -271,7 +279,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
case 0x6982: {
|
case 0x6982: {
|
||||||
SecurityTokenInfo tokeninfo = null;
|
SecurityTokenInfo tokeninfo = null;
|
||||||
try {
|
try {
|
||||||
tokeninfo = mSecurityTokenHelper.getTokenInfo();
|
tokeninfo = stConnection.getTokenInfo();
|
||||||
} catch (IOException e2) {
|
} catch (IOException e2) {
|
||||||
// don't care
|
// don't care
|
||||||
}
|
}
|
||||||
@@ -325,7 +333,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
}
|
}
|
||||||
// 6A82 app not installed on security token!
|
// 6A82 app not installed on security token!
|
||||||
case 0x6A82: {
|
case 0x6A82: {
|
||||||
if (mSecurityTokenHelper.isFidesmoToken()) {
|
if (stConnection.isFidesmoToken()) {
|
||||||
// Check if the Fidesmo app is installed
|
// Check if the Fidesmo app is installed
|
||||||
if (isAndroidAppInstalled(FIDESMO_APP_PACKAGE)) {
|
if (isAndroidAppInstalled(FIDESMO_APP_PACKAGE)) {
|
||||||
promptFidesmoPgpInstall();
|
promptFidesmoPgpInstall();
|
||||||
@@ -391,12 +399,11 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected void obtainSecurityTokenPin(RequiredInputParcel requiredInput) {
|
protected void obtainSecurityTokenPin(RequiredInputParcel requiredInput) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Passphrase passphrase = PassphraseCacheService.getCachedPassphrase(this,
|
Passphrase passphrase = PassphraseCacheService.getCachedPassphrase(this,
|
||||||
requiredInput.getMasterKeyId(), requiredInput.getSubKeyId());
|
requiredInput.getMasterKeyId(), requiredInput.getSubKeyId());
|
||||||
if (passphrase != null) {
|
if (passphrase != null) {
|
||||||
mSecurityTokenHelper.setPin(passphrase);
|
mCachedPin = passphrase;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -421,7 +428,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
CryptoInputParcel input = data.getParcelableExtra(PassphraseDialogActivity.RESULT_CRYPTO_INPUT);
|
CryptoInputParcel input = data.getParcelableExtra(PassphraseDialogActivity.RESULT_CRYPTO_INPUT);
|
||||||
mSecurityTokenHelper.setPin(input.getPassphrase());
|
mCachedPin = input.getPassphrase();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -429,19 +436,8 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void handleSecurityToken(Transport transport, Context ctx) throws IOException {
|
protected void handleSecurityToken(SecurityTokenConnection stConnection) throws IOException {
|
||||||
// Don't reconnect if device was already connected
|
doSecurityTokenInBackground(stConnection);
|
||||||
if (!(mSecurityTokenHelper.isPersistentConnectionAllowed()
|
|
||||||
&& mSecurityTokenHelper.isConnected()
|
|
||||||
&& mSecurityTokenHelper.getTransport().equals(transport))) {
|
|
||||||
mSecurityTokenHelper.setTransport(transport);
|
|
||||||
mSecurityTokenHelper.connectToDevice(ctx);
|
|
||||||
}
|
|
||||||
doSecurityTokenInBackground();
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isSecurityTokenConnected() {
|
|
||||||
return mSecurityTokenHelper.isConnected();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class IsoDepNotSupportedException extends IOException {
|
public static class IsoDepNotSupportedException extends IOException {
|
||||||
@@ -500,10 +496,6 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
|||||||
mUsbDispatcher.onStart();
|
mUsbDispatcher.onStart();
|
||||||
}
|
}
|
||||||
|
|
||||||
public SecurityTokenHelper getSecurityTokenHelper() {
|
|
||||||
return mSecurityTokenHelper;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run Security Token routines if last used token is connected and supports
|
* Run Security Token routines if last used token is connected and supports
|
||||||
* persistent connections
|
* persistent connections
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ import org.sufficientlysecure.keychain.provider.KeyRepository;
|
|||||||
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
|
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
|
||||||
import org.sufficientlysecure.keychain.provider.KeychainContract;
|
import org.sufficientlysecure.keychain.provider.KeychainContract;
|
||||||
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
|
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
|
||||||
|
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||||
import org.sufficientlysecure.keychain.service.ChangeUnlockParcel;
|
import org.sufficientlysecure.keychain.service.ChangeUnlockParcel;
|
||||||
import org.sufficientlysecure.keychain.service.ImportKeyringParcel;
|
import org.sufficientlysecure.keychain.service.ImportKeyringParcel;
|
||||||
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
|
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
|
||||||
@@ -619,8 +620,8 @@ public class ViewKeyActivity extends BaseSecurityTokenActivity implements
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void onSecurityTokenPostExecute() {
|
protected void onSecurityTokenPostExecute(SecurityTokenConnection stConnection) {
|
||||||
super.onSecurityTokenPostExecute();
|
super.onSecurityTokenPostExecute(stConnection);
|
||||||
finish();
|
finish();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
|
|
||||||
|
import org.bouncycastle.util.encoders.Hex;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.sufficientlysecure.keychain.KeychainTestRunner;
|
||||||
|
|
||||||
|
import static junit.framework.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
|
|
||||||
|
@SuppressWarnings("WeakerAccess")
|
||||||
|
@RunWith(KeychainTestRunner.class)
|
||||||
|
public class CommandApduTest {
|
||||||
|
static final byte[] DATA_LONG = new byte[500];
|
||||||
|
static final byte[] DATA_SHORT = { 1, 2, 3 };
|
||||||
|
static final int CLA = 1;
|
||||||
|
static final int INS = 2;
|
||||||
|
static final int P1 = 3;
|
||||||
|
static final int P2 = 4;
|
||||||
|
static final int NE_SHORT = 5;
|
||||||
|
static final int NE_LONG = 500;
|
||||||
|
static final int NE_SPECIAL = 256;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase1() throws Exception {
|
||||||
|
CommandApdu commandApdu = CommandApdu.create(CLA, INS, P1, P2);
|
||||||
|
|
||||||
|
assertParsesCorrectly(commandApdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase2s() throws Exception {
|
||||||
|
CommandApdu commandApdu = CommandApdu.create(CLA, INS, P1, P2, NE_SHORT);
|
||||||
|
|
||||||
|
assertEquals(5, commandApdu.toBytes().length);
|
||||||
|
|
||||||
|
assertParsesCorrectly(commandApdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase2e() throws Exception {
|
||||||
|
CommandApdu commandApdu = CommandApdu.create(CLA, INS, P1, P2, NE_LONG);
|
||||||
|
|
||||||
|
assertEquals(7, commandApdu.toBytes().length);
|
||||||
|
|
||||||
|
assertParsesCorrectly(commandApdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase2e_specialNe() throws Exception {
|
||||||
|
CommandApdu commandApdu = CommandApdu.create(CLA, INS, P1, P2, NE_SPECIAL);
|
||||||
|
|
||||||
|
assertEquals(5, commandApdu.toBytes().length);
|
||||||
|
|
||||||
|
assertParsesCorrectly(commandApdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase3s() throws Exception {
|
||||||
|
CommandApdu commandApdu = CommandApdu.create(CLA, INS, P1, P2, DATA_SHORT);
|
||||||
|
|
||||||
|
assertEquals(4 + 1 + DATA_SHORT.length, commandApdu.toBytes().length);
|
||||||
|
|
||||||
|
assertParsesCorrectly(commandApdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase3e() throws Exception {
|
||||||
|
CommandApdu commandApdu = CommandApdu.create(CLA, INS, P1, P2, DATA_LONG);
|
||||||
|
|
||||||
|
assertEquals(4 + 3 + DATA_LONG.length, commandApdu.toBytes().length);
|
||||||
|
|
||||||
|
assertParsesCorrectly(commandApdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase4s() throws Exception {
|
||||||
|
CommandApdu commandApdu = CommandApdu.create(CLA, INS, P1, P2, DATA_SHORT, 5);
|
||||||
|
|
||||||
|
assertArrayEquals(Hex.decode("010203040301020305"), commandApdu.toBytes());
|
||||||
|
|
||||||
|
assertParsesCorrectly(commandApdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase4e() throws Exception {
|
||||||
|
CommandApdu commandApdu = CommandApdu.create(CLA, INS, P1, P2, DATA_LONG, 5);
|
||||||
|
|
||||||
|
assertEquals(4 + 5 + DATA_LONG.length, commandApdu.toBytes().length);
|
||||||
|
|
||||||
|
assertParsesCorrectly(commandApdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertParsesCorrectly(CommandApdu commandApdu) {
|
||||||
|
byte[] bytes = commandApdu.toBytes();
|
||||||
|
CommandApdu parsedCommandApdu = CommandApdu.fromBytes(bytes);
|
||||||
|
assertEquals(commandApdu, parsedCommandApdu);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package org.sufficientlysecure.keychain.securitytoken;
|
||||||
|
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.bouncycastle.util.encoders.Hex;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.InOrder;
|
||||||
|
import org.robolectric.RuntimeEnvironment;
|
||||||
|
import org.robolectric.shadows.ShadowLog;
|
||||||
|
import org.sufficientlysecure.keychain.KeychainTestRunner;
|
||||||
|
import org.sufficientlysecure.keychain.util.Passphrase;
|
||||||
|
|
||||||
|
import static org.mockito.Matchers.eq;
|
||||||
|
import static org.mockito.Mockito.inOrder;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
|
||||||
|
@RunWith(KeychainTestRunner.class)
|
||||||
|
public class SecurityTokenConnectionTest {
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
ShadowLog.stream = System.out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test_connectToDevice() throws Exception {
|
||||||
|
Transport transport = mock(Transport.class);
|
||||||
|
SecurityTokenConnection securityTokenConnection =
|
||||||
|
new SecurityTokenConnection(transport, new Passphrase("123456"), new OpenPgpCommandApduFactory());
|
||||||
|
|
||||||
|
String[] dialog = { "00a4040006d27600012401", "9000",
|
||||||
|
"00ca006e00",
|
||||||
|
"6e81de4f10d27600012401020000060364311500005f520f0073000080000000000000000000007381b7c00af" +
|
||||||
|
"00000ff04c000ff00ffc106010800001103c206010800001103c306010800001103c407007f7f7f03030" +
|
||||||
|
"3c53c4ec5fee25c4e89654d58cad8492510a89d3c3d8468da7b24e15bfc624c6a792794f15b7599915f7" +
|
||||||
|
"03aab55ed25424d60b17026b7b06c6ad4b9be30a3c63c000000000000000000000000000000000000000" +
|
||||||
|
"000000000000000000000000000000000000000000000000000000000000000000000000000000000cd0" +
|
||||||
|
"c59cd0f2a59cd0af059cd0c959000"
|
||||||
|
};
|
||||||
|
expect(transport, dialog);
|
||||||
|
|
||||||
|
|
||||||
|
securityTokenConnection.connectToDevice(RuntimeEnvironment.application);
|
||||||
|
|
||||||
|
|
||||||
|
verify(transport).connect();
|
||||||
|
verifyDialog(transport, dialog);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test_getTokenInfo() throws Exception {
|
||||||
|
Transport transport = mock(Transport.class);
|
||||||
|
SecurityTokenConnection securityTokenConnection =
|
||||||
|
new SecurityTokenConnection(transport, new Passphrase("123456"), new OpenPgpCommandApduFactory());
|
||||||
|
OpenPgpCapabilities openPgpCapabilities = new OpenPgpCapabilities(
|
||||||
|
Hex.decode(
|
||||||
|
"6e81de4f10d27600012401020000060364311500005f520f0073000080000000000000000000007381b7c00af" +
|
||||||
|
"00000ff04c000ff00ffc106010800001103c206010800001103c306010800001103c407007f7f7f03" +
|
||||||
|
"0303c53c4ec5fee25c4e89654d58cad8492510a89d3c3d8468da7b24e15bfc624c6a792794f15b759" +
|
||||||
|
"9915f703aab55ed25424d60b17026b7b06c6ad4b9be30a3c63c000000000000000000000000000000" +
|
||||||
|
"000000000000000000000000000000000000000000000000000000000000000000000000000000000" +
|
||||||
|
"000000000cd0c59cd0f2a59cd0af059cd0c95"
|
||||||
|
));
|
||||||
|
securityTokenConnection.setConnectionCapabilities(openPgpCapabilities);
|
||||||
|
|
||||||
|
String[] dialog = {
|
||||||
|
"00ca006500",
|
||||||
|
"65095b005f2d005f3501399000",
|
||||||
|
"00ca5f5000",
|
||||||
|
"9000",
|
||||||
|
};
|
||||||
|
expect(transport, dialog);
|
||||||
|
|
||||||
|
|
||||||
|
securityTokenConnection.getTokenInfo();
|
||||||
|
|
||||||
|
|
||||||
|
verifyDialog(transport, dialog);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void expect(Transport transport, String... dialog) throws IOException {
|
||||||
|
for (int i = 0; i < dialog.length; i += 2) {
|
||||||
|
CommandApdu command = CommandApdu.fromBytes(Hex.decode(dialog[i]));
|
||||||
|
ResponseApdu response = ResponseApdu.fromBytes(Hex.decode(dialog[i + 1]));
|
||||||
|
when(transport.transceive(eq(command))).thenReturn(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void verifyDialog(Transport transport, String... dialog) throws IOException {
|
||||||
|
InOrder inOrder = inOrder(transport);
|
||||||
|
for (int i = 0; i < dialog.length; i += 2) {
|
||||||
|
CommandApdu command = CommandApdu.fromBytes(Hex.decode(dialog[i]));
|
||||||
|
inOrder.verify(transport).transceive(eq(command));
|
||||||
|
}
|
||||||
|
inOrder.verifyNoMoreInteractions();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user