javacard.security.KeyPair Java Examples

The following examples show how to use javacard.security.KeyPair. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Command.java    From ECTester with MIT License 6 votes vote down vote up
/**
 * @param keyPair   which keyPair/s (local/remote) to set curve domain parameters on
 * @param keyLength key length to choose
 * @param keyClass  key class to choose
 * @return a Command to send in order to prepare the curve on the keypairs.
 * @throws IOException if curve file cannot be found/opened
 */
public static Command prepareCurve(CardMngr cardManager, ECTesterReader.Config cfg, byte keyPair, short keyLength, byte keyClass) throws IOException {
    if (cfg.customCurve) {
        // Set custom curve (one of the SECG curves embedded applet-side)
        short domainParams = keyClass == KeyPair.ALG_EC_FP ? EC_Consts.PARAMETERS_DOMAIN_FP : EC_Consts.PARAMETERS_DOMAIN_F2M;
        return new Command.Set(cardManager, keyPair, EC_Consts.getCurve(keyLength, keyClass), domainParams, null);
    }

    EC_Curve curve = findCurve(cfg, keyLength, keyClass);
    if ((curve == null || curve.flatten() == null) && (cfg.namedCurve != null || cfg.curveFile != null)) {
        if (cfg.namedCurve != null) {
            throw new IOException("Couldn't read named curve data.");
        }
        throw new IOException("Couldn't read the curve file correctly.");
    } else if (curve == null) {
        return null;
    }
    return new Command.Set(cardManager, keyPair, EC_Consts.CURVE_external, curve.getParams(), curve.flatten());
}
 
Example #2
Source File: EC_Curve.java    From ECTester with MIT License 6 votes vote down vote up
public EllipticCurve toCurve() {
    ECField field;
    if (this.field == KeyPair.ALG_EC_FP) {
        field = new ECFieldFp(new BigInteger(1, getData(0)));
    } else {
        byte[][] fieldData = getParam(EC_Consts.PARAMETER_F2M);
        int m = ByteUtil.getShort(fieldData[0], 0);
        int e1 = ByteUtil.getShort(fieldData[1], 0);
        int e2 = ByteUtil.getShort(fieldData[2], 0);
        int e3 = ByteUtil.getShort(fieldData[3], 0);
        int[] powers;
        if (e2 == 0 && e3 == 0) {
            powers = new int[]{e1};
        } else {
            powers = new int[]{e1, e2, e3};
        }
        field = new ECFieldF2m(m, powers);
    }

    BigInteger a = new BigInteger(1, getParam(EC_Consts.PARAMETER_A)[0]);
    BigInteger b = new BigInteger(1, getParam(EC_Consts.PARAMETER_B)[0]);

    return new EllipticCurve(field, a, b);
}
 
Example #3
Source File: FIDOCCImplementation.java    From CCU2F with Apache License 2.0 5 votes vote down vote up
public FIDOCCImplementation() {
	
	random = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
	
    scratch = JCSystem.makeTransientByteArray((short)128, JCSystem.CLEAR_ON_DESELECT);
    //seed = new byte[64];
    
    keyPair = new KeyPair(
        (ECPublicKey)KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PUBLIC, KeyBuilder.LENGTH_EC_FP_256, false),
        (ECPrivateKey)KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false));
    Secp256r1.setCommonCurveParameters((ECKey)keyPair.getPrivate());
    Secp256r1.setCommonCurveParameters((ECKey)keyPair.getPublic());
            
    // Initialize the unique seed for DRNG function 
    //random.generateData(seed, (short)0, (short)64);
    
    // Initialize the unique seed for DRNG function       
    drngSeed1 = (AESKey)KeyBuilderX.buildKey(KeyBuilderX.TYPE_AES_STATIC, KeyBuilder.LENGTH_AES_256, false);
    drngSeed2 = (AESKey)KeyBuilderX.buildKey(KeyBuilderX.TYPE_AES_STATIC, KeyBuilder.LENGTH_AES_256, false);
    random.generateData(scratch, (short)0, (short)32);
    drngSeed1.setKey(scratch, (short)0);
    random.generateData(scratch, (short)0, (short)32);
    drngSeed2.setKey(scratch, (short)0);
 
    sha256 = MessageDigest.getInstance(MessageDigest.ALG_SHA_256, false);
            
    // Initialize the unique keys for MAC function
    macKey1 = (AESKey)KeyBuilderX.buildKey(KeyBuilderX.TYPE_AES_STATIC, KeyBuilder.LENGTH_AES_128, false);
    macKey2 = (AESKey)KeyBuilderX.buildKey(KeyBuilderX.TYPE_AES_STATIC, KeyBuilder.LENGTH_AES_128, false);
    random.generateData(scratch, (short)0, (short)16);
    macKey1.setKey(scratch, (short)0);
    random.generateData(scratch, (short)0, (short)16);
    macKey2.setKey(scratch, (short)0);
    
    // Initialize ecMultiplier 
    ecMultiplyHelper = KeyAgreementX.getInstance(KeyAgreementX.ALG_EC_SVDP_DH_PLAIN_XY, false);
}
 
Example #4
Source File: Gpg.java    From OpenPGP-Card with GNU General Public License v3.0 5 votes vote down vote up
private KeyPair getKey(byte type) {
  switch (type) {
    case (byte) 0xB6:
      return signatureKey;
    case (byte) 0xB8:
      return confidentialityKey;
    case (byte) 0xA4:
      return authenticationKey;
  }
  ISOException.throwIt(ISO7816.SW_DATA_INVALID);
  return signatureKey;  // Make the compiler happy.
}
 
Example #5
Source File: CardDefaultSuite.java    From ECTester with MIT License 5 votes vote down vote up
@Override
protected void runTests() throws Exception {
    if (cfg.primeField) {
        runDefault(KeyPair.ALG_EC_FP);
    }
    if (cfg.binaryField) {
        runDefault(KeyPair.ALG_EC_F2M);
    }
}
 
Example #6
Source File: CardCompressionSuite.java    From ECTester with MIT License 5 votes vote down vote up
@Override
protected void runTests() throws Exception {
    //iterate over default curve sizes
    // for Fp
    //   - allocate, set custom curve, generate keypairs, -> export generated.
    //   - test ecdh with local and remote simply(no compression)
    //   - test local privkey, remote pubkey (compressed)
    //   - test local privkey, remote pubkey (hybrid)
    //   - test local privkey, remote pubkey (hybrid with wrong y)
    //   - test local privkey, remote pubkey (point at infinity)
    if (cfg.primeField) {
        runCompression(KeyPair.ALG_EC_FP);
    }
    // for F2m
    //   - allocate, set custom curve, generate keypairs, -> export generated.
    //   - test ecdh with local and remote simply(no compression)
    //   - test local privkey, remote pubkey (compressed)
    //   - test local privkey, remote pubkey (hybrid)
    //   - test local privkey, remote pubkey (hybrid with wrong y)
    //   - test local privkey, remote pubkey (point at infinity)
    if (cfg.binaryField) {
        runCompression(KeyPair.ALG_EC_F2M);
    }

    // Now, do ECDH over SECG curves and give the implementation a compressed key that is not a quadratic residue in
    // decompression.
    runNonResidue();
}
 
Example #7
Source File: Gpg.java    From OpenPGP-Card with GNU General Public License v3.0 5 votes vote down vote up
private short addKeyPart(byte part, byte[] data, short offset, KeyPair key) {
  short size = Util.getShort(commandChainingBuffer, TEMP_PUT_KEY_EXPECTED_CHUNK_SIZE);
  short nextSize = RSA_KEY_HALF_LENGTH_BYTES;
  switch (part) {
    case KEY_PART_E:
      ((RSAPublicKey) key.getPublic()).setExponent(data, offset, size);
      break;
    case KEY_PART_PRIME_P:
      ((RSAPrivateCrtKey) key.getPrivate()).setP(data, offset, size);
      break;
    case KEY_PART_PRIME_Q:
      ((RSAPrivateCrtKey) key.getPrivate()).setQ(data, offset, size);
      break;
    case KEY_PART_PARAM_PQ:
      ((RSAPrivateCrtKey) key.getPrivate()).setPQ(data, offset, size);
      break;
    case KEY_PART_PARAM_DP1:
      ((RSAPrivateCrtKey) key.getPrivate()).setDP1(data, offset, size);
      break;
    case KEY_PART_PARAM_DQ1:
      ((RSAPrivateCrtKey) key.getPrivate()).setDQ1(data, offset, size);
      nextSize = RSA_KEY_LENGTH_BYTES;
      break;

    case KEY_PART_N:
      ((RSAPublicKey) key.getPublic()).setModulus(data, offset, RSA_KEY_LENGTH_BYTES);
      if (!key.getPrivate().isInitialized() ||
          !key.getPublic().isInitialized()) {
        ISOException.throwIt(ISO7816.SW_DATA_INVALID);
      }
      return (short) (offset + RSA_KEY_LENGTH_BYTES);
  }
  Util.setShort(commandChainingBuffer, TEMP_PUT_KEY_EXPECTED_CHUNK_SIZE, nextSize);
  return (short) (offset + size);
}
 
Example #8
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
@Override
public String getDescription() {
    String field = keyClass == KeyPair.ALG_EC_FP ? "ALG_EC_FP" : "ALG_EC_F2M";
    String key;
    if (keyPair == ECTesterApplet.KEYPAIR_BOTH) {
        key = "both keypairs";
    } else {
        key = ((keyPair == ECTesterApplet.KEYPAIR_LOCAL) ? "local" : "remote") + " keypair";
    }
    return String.format("Allocate %s %db %s", key, keyLength, field);
}
 
Example #9
Source File: CardUtil.java    From ECTester with MIT License 5 votes vote down vote up
public static String getKeyTypeString(byte keyClass) {
    switch (keyClass) {
        case KeyPair.ALG_EC_FP:
            return "ALG_EC_FP";
        case KeyPair.ALG_EC_F2M:
            return "ALG_EC_F2M";
        default:
            return "";
    }
}
 
Example #10
Source File: Gpg.java    From OpenPGP-Card with GNU General Public License v3.0 4 votes vote down vote up
/**
 * GENERATE KEY APDU implementation.
 */
private void generateAsymetricKey(APDU apdu) {
  byte[] buffer = apdu.getBuffer();
  if (apdu.setIncomingAndReceive() != 2) {
    ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
  }
  KeyPair key = getKey(buffer[ISO7816.OFFSET_CDATA]);
  if (buffer[ISO7816.OFFSET_P1] == (byte) 0x81) {
    if (!(key.getPublic()).isInitialized()) {
      ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
    }
  } else {
    if (!pins[PIN_INDEX_PW3].isValidated()) {
      ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }
    JCSystem.beginTransaction();
    key.genKeyPair();
    if (buffer[ISO7816.OFFSET_CDATA] == (byte)0xB6) {
      signatureCounter[0] = 0;
      signatureCounter[1] = 0;
      signatureCounter[2] = 0;
    }
    JCSystem.commitTransaction();
  }
  // Send the TLV data and public exponent using the APDU buffer.
  buffer[ISO7816.OFFSET_CDATA] = 0x7F;
  buffer[(short) (ISO7816.OFFSET_CDATA + 1)] = 0x49;
  buffer[(short) (ISO7816.OFFSET_CDATA + 2)] = (byte) 0x82;
  buffer[(short) (ISO7816.OFFSET_CDATA + 5)] = (byte) 0x82;
  short length = ((RSAPublicKey) key.getPublic()).getExponent(
      buffer, (short) (ISO7816.OFFSET_CDATA + 7));
  buffer[(short) (ISO7816.OFFSET_CDATA + 6)] = (byte) length;
  short pos = (short) (ISO7816.OFFSET_CDATA + 7 + length);
  buffer[pos] = (byte) 0x81;
  buffer[(short) (pos + 1)] = (byte) 0x82;
  Util.setShort(buffer, (short) (pos + 2), RSA_KEY_LENGTH_BYTES);
  Util.setShort(buffer, (short) (ISO7816.OFFSET_CDATA + 3),
                (short) (pos + RSA_KEY_LENGTH_BYTES - ISO7816.OFFSET_CDATA - 1));
  apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, (short) (length + 11));

  // And the modulus using get response.
  Util.setShort(commandChainingBuffer, TEMP_GET_RESPONSE_LENGTH, RSA_KEY_LENGTH_BYTES);
  ((RSAPublicKey) key.getPublic()).getModulus(commandChainingBuffer, TEMP_GET_RESPONSE_DATA);
  // Skip leading zero byte.
  if (commandChainingBuffer[TEMP_GET_RESPONSE_DATA] == 0) {
    Util.setShort(commandChainingBuffer, TEMP_GET_RESPONSE_OFFSET,
                  (short) (TEMP_GET_RESPONSE_DATA + 1));
  } else {
    Util.setShort(commandChainingBuffer, TEMP_GET_RESPONSE_OFFSET, TEMP_GET_RESPONSE_DATA);
  }
  commandChainingBuffer[TEMP_INS] = buffer[ISO7816.OFFSET_INS];
  ISOException.throwIt(ISO7816.SW_BYTES_REMAINING_00);
}
 
Example #11
Source File: Bignat_Helper.java    From JCMathLib with MIT License 4 votes vote down vote up
void initialize(short modRSAEngineMaxBits, short multRSAEngineMaxBits) {
    MODULO_RSA_ENGINE_MAX_LENGTH_BITS = modRSAEngineMaxBits;
    MULT_RSA_ENGINE_MAX_LENGTH_BITS = multRSAEngineMaxBits;
    
    fnc_deep_resize_tmp = rm.helper_BN_array1;
    fnc_mult_resultArray1 = rm.helper_BN_array1;
    fnc_mult_resultArray2 = rm.helper_BN_array2;

    fnc_same_value_array1 = rm.helper_BN_array1;
    fnc_same_value_hash = rm.helper_BN_array2;
    
    fnc_shift_bytes_right_tmp = rm.helper_BN_array1;
    
    // BN below are just reassigned allocated helper_BN_? so that same helper_BN_? is not used in parallel (checked by lock() unlock())
    fnc_mod_add_tmp = rm.helper_BN_A;

    fnc_mod_sub_tmpThis = rm.helper_BN_A;
    fnc_mod_sub_tmp = rm.helper_BN_B;
    fnc_mod_sub_tmpOther = rm.helper_BN_C;

    fnc_mult_mod_tmpThis = rm.helper_BN_A;
    fnc_mult_mod_tmp_mod = rm.helper_BN_B;
    fnc_mult_mod_tmp_x = rm.helper_BN_C;

    fnc_exponentiation_tmp = rm.helper_BN_A;
    fnc_exponentiation_i = rm.helper_BN_B;

    fnc_mod_minus_2 = rm.helper_BN_B;

    fnc_negate_tmp = rm.helper_BN_B;

    fnc_sqrt_S = rm.helper_BN_A;
    fnc_sqrt_exp = rm.helper_BN_A;
    fnc_sqrt_p_1 = rm.helper_BN_B;
    fnc_sqrt_Q = rm.helper_BN_C;
    fnc_sqrt_tmp = rm.helper_BN_D;
    fnc_sqrt_z = rm.helper_BN_E;

    fnc_mod_mult_tmpThis = rm.helper_BN_E; // mod_mult is called from  fnc_sqrt => requires helper_BN_E not being locked in fnc_sqrt when mod_mult is called

    fnc_divide_tmpThis = rm.helper_BN_E; // divide is called from  fnc_sqrt => requires helper_BN_E not being locked  in fnc_sqrt when divide is called

    fnc_mod_exp_modBN = rm.helper_BN_F;  // mod_exp is called from  fnc_sqrt => requires helper_BN_F not being locked  in fnc_sqrt when mod_exp is called

    fnc_int_add_tmpMag = rm.helper_BN_A;
    fnc_int_multiply_mod = rm.helper_BN_A;
    fnc_int_multiply_tmpThis = rm.helper_BN_B;
    fnc_int_divide_tmpThis = rm.helper_BN_A;        
    
    
    // Allocate BN constants always in EEPROM (only reading)
    ONE = new Bignat((short) 1, JCSystem.MEMORY_TYPE_PERSISTENT, this);
    ONE.one();
    TWO = new Bignat((short) 1, JCSystem.MEMORY_TYPE_PERSISTENT, this);
    TWO.two();
    THREE = new Bignat((short) 1, JCSystem.MEMORY_TYPE_PERSISTENT, this);
    THREE.three();

    tmp_array_short = rm.memAlloc.allocateByteArray((short) 2, JCSystem.MEMORY_TYPE_TRANSIENT_RESET); // only 2b RAM for faster add(short)
    fnc_NmodE_cipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false);
    fnc_NmodE_pubKey = (RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, MODULO_RSA_ENGINE_MAX_LENGTH_BITS, false);

    // Speedup for fast multiplication
    fnc_mult_keypair = new KeyPair(KeyPair.ALG_RSA_CRT, MULT_RSA_ENGINE_MAX_LENGTH_BITS);
    fnc_mult_keypair.genKeyPair();
    fnc_mult_pubkey_pow2 = (RSAPublicKey) fnc_mult_keypair.getPublic();
    //mult_privkey_pow2 = (RSAPrivateCrtKey) mult_keypair.getPrivate();
    fnc_mult_pubkey_pow2.setExponent(CONST_TWO, (short) 0, (short) CONST_TWO.length);
    fnc_mult_cipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false);

    hashEngine = rm.hashEngine;

    FLAG_FAST_MULT_VIA_RSA = false; // set true only if succesfully allocated and tested below
    try { // Subsequent code may fail on some real (e.g., Infineon CJTOP80K) cards - catch exception
        fnc_mult_cipher.init(fnc_mult_pubkey_pow2, Cipher.MODE_ENCRYPT);
        // Try operation - if doesn't work, exception SW_CANTALLOCATE_BIGNAT is emitted
        Util.arrayFillNonAtomic(fnc_mult_resultArray1, (short) 0, (short) fnc_mult_resultArray1.length, (byte) 6);
        fnc_mult_cipher.doFinal(fnc_mult_resultArray1, (short) 0, (short) fnc_mult_resultArray1.length, fnc_mult_resultArray1, (short) 0);
        FLAG_FAST_MULT_VIA_RSA = true;
    } catch (Exception ignored) {
    } // discard exception                
}
 
Example #12
Source File: Gpg.java    From OpenPGP-Card with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Only this class's install method should create the applet object.
 */
protected Gpg(byte[] parameters, short offset, byte length) {
  pinLength = new byte[3];
  pins = new OwnerPIN[3];
  pins[PIN_INDEX_PW1] = new OwnerPIN(MAX_TRIES_PIN1, MAX_PIN_LENGTH);
  pins[PIN_INDEX_PW1].update(defaultPIN, (short) 0, MIN_PIN1_LENGTH);
  pinLength[PIN_INDEX_PW1] = MIN_PIN1_LENGTH;
  pins[PIN_INDEX_PW3] = new OwnerPIN(MAX_TRIES_PIN3, MAX_PIN_LENGTH);
  pins[PIN_INDEX_PW3].update(defaultPIN, (short) 0, MIN_PIN3_LENGTH);
  pinLength[PIN_INDEX_PW3] = MIN_PIN3_LENGTH;
  // The resetting code is disabled by default.
  pins[PIN_INDEX_RC] = new OwnerPIN(MAX_TRIES_RC, MAX_PIN_LENGTH);
  pinLength[PIN_INDEX_RC] = 0;
  pinSubmitted = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);

  commandChainingBuffer =
      JCSystem.makeTransientByteArray((short) (TEMP_PUT_KEY_ACCUMULATOR + RSA_KEY_LENGTH_BYTES),
                                      JCSystem.CLEAR_ON_DESELECT);

  privateDO1 = new byte[255];
  privateDO2 = new byte[255];
  privateDO3 = new byte[255];
  privateDO4 = new byte[255];

  loginData = new byte[(short) 255];
  url = new byte[(short) 255];
  name = new byte[(short) 40];
  language = new byte[(short) 9];
  sex = new byte[(short) 1];
  fingerprints = new byte[(short) 60];
  caFingerprints = new byte[(short) 60];
  generationDates = new byte[(short) 12];
  signatureCounter = new byte[(short) 3];
  pinValidForMultipleSignatures = (byte) 0;

  signatureKey = new KeyPair(KeyPair.ALG_RSA_CRT, (short) 2048);
  confidentialityKey = new KeyPair(KeyPair.ALG_RSA_CRT, (short) 2048);
  authenticationKey = new KeyPair(KeyPair.ALG_RSA_CRT, (short) 2048);
  cipherRSA = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
  randomData = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);

  register();
}
 
Example #13
Source File: AppletUtil.java    From ECTester with MIT License 4 votes vote down vote up
public static short keypairCheck(KeyPair keyPair) {
    return nullCheck(keyPair, AppletBase.SW_KEYPAIR_NULL);
}
 
Example #14
Source File: EC_Consts.java    From ECTester with MIT License 4 votes vote down vote up
public static byte getCurveType(byte curve) {
    return curve <= FP_CURVES ? KeyPair.ALG_EC_FP : KeyPair.ALG_EC_F2M;
}
 
Example #15
Source File: EC_Consts.java    From ECTester with MIT License 4 votes vote down vote up
public static byte getCurve(short keyLength, byte keyClass) {
    if (keyClass == KeyPair.ALG_EC_FP) {
        switch (keyLength) {
            case (short) 112:
                return CURVE_secp112r1;
            case (short) 128:
                return CURVE_secp128r1;
            case (short) 160:
                return CURVE_secp160r1;
            case (short) 192:
                return CURVE_secp192r1;
            case (short) 224:
                return CURVE_secp224r1;
            case (short) 256:
                return CURVE_secp256r1;
            case (short) 384:
                return CURVE_secp384r1;
            case (short) 521:
                return CURVE_secp521r1;
            default:
                ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
        }
    } else if (keyClass == KeyPair.ALG_EC_F2M) {
        switch (keyLength) {
            case (short) 163:
                return CURVE_sect163r1;
            case (short) 233:
                return CURVE_sect233r1;
            case (short) 283:
                return CURVE_sect283r1;
            case (short) 409:
                return CURVE_sect409r1;
            case (short) 571:
                return CURVE_sect571r1;
            default:
                ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
        }
    } else {
        ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
    }
    return 0;
}
 
Example #16
Source File: EC_Curve.java    From ECTester with MIT License 4 votes vote down vote up
public static EC_Curve fromSpec(ECParameterSpec spec) {
    EllipticCurve curve = spec.getCurve();
    ECField field = curve.getField();

    short bits = (short) field.getFieldSize();
    byte[][] params;
    int paramIndex = 0;
    byte fieldType;
    if (field instanceof ECFieldFp) {
        ECFieldFp primeField = (ECFieldFp) field;
        params = new byte[7][];
        params[paramIndex++] = primeField.getP().toByteArray();
        fieldType = KeyPair.ALG_EC_FP;
    } else if (field instanceof ECFieldF2m) {
        ECFieldF2m binaryField = (ECFieldF2m) field;
        params = new byte[10][];
        params[paramIndex] = new byte[2];
        ByteUtil.setShort(params[paramIndex++], 0, (short) binaryField.getM());
        int[] powers = binaryField.getMidTermsOfReductionPolynomial();
        for (int i = 0; i < 3; ++i) {
            params[paramIndex] = new byte[2];
            short power = (i < powers.length) ? (short) powers[i] : 0;
            ByteUtil.setShort(params[paramIndex++], 0, power);
        }
        fieldType = KeyPair.ALG_EC_F2M;
    } else {
        throw new IllegalArgumentException("ECParameterSpec with an unknown field.");
    }

    ECPoint generator = spec.getGenerator();

    params[paramIndex++] = curve.getA().toByteArray();
    params[paramIndex++] = curve.getB().toByteArray();

    params[paramIndex++] = generator.getAffineX().toByteArray();
    params[paramIndex++] = generator.getAffineY().toByteArray();

    params[paramIndex++] = spec.getOrder().toByteArray();
    params[paramIndex] = new byte[2];
    ByteUtil.setShort(params[paramIndex], 0, (short) spec.getCofactor());

    EC_Curve result = new EC_Curve(bits, fieldType);
    result.readByteArray(params);
    return result;
}
 
Example #17
Source File: EC_Curve.java    From ECTester with MIT License 4 votes vote down vote up
@Override
public String toString() {
    return "<" + getId() + "> " + (field == KeyPair.ALG_EC_FP ? "Prime" : "Binary") + " field Elliptic curve (" + String.valueOf(bits) + "b)" + (desc == null ? "" : ": " + desc) + System.lineSeparator() + super.toString();
}
 
Example #18
Source File: EC_Curve.java    From ECTester with MIT License 4 votes vote down vote up
/**
 * @param bits
 * @param field KeyPair.ALG_EC_FP or KeyPair.ALG_EC_F2M
 */
public EC_Curve(short bits, byte field) {
    super(field == KeyPair.ALG_EC_FP ? EC_Consts.PARAMETERS_DOMAIN_FP : EC_Consts.PARAMETERS_DOMAIN_F2M);
    this.bits = bits;
    this.field = field;
}
 
Example #19
Source File: CardCompressionSuite.java    From ECTester with MIT License 4 votes vote down vote up
private void runCompression(byte field) throws Exception {
    short[] keySizes = field == KeyPair.ALG_EC_FP ? EC_Consts.FP_SIZES : EC_Consts.F2M_SIZES;
    short domain = field == KeyPair.ALG_EC_FP ? EC_Consts.PARAMETERS_DOMAIN_FP : EC_Consts.PARAMETERS_DOMAIN_F2M;

    for (short keyLength : keySizes) {
        String spec = keyLength + "b " + CardUtil.getKeyTypeString(field);
        byte curveId = EC_Consts.getCurve(keyLength, field);

        Test allocateFirst = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, keyLength, field), Result.ExpectedValue.SUCCESS));
        if (!allocateFirst.ok()) {
            doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "No support for compression test on " + spec + ".", allocateFirst));
            continue;
        }

        List<Test> compressionTests = new LinkedList<>();
        compressionTests.add(allocateFirst);
        Test setCustom = runTest(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, curveId, domain, null), Result.ExpectedValue.SUCCESS));
        Test genCustom = runTest(CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_BOTH), Result.ExpectedValue.SUCCESS));
        compressionTests.add(setCustom);
        compressionTests.add(genCustom);

        Response.Export key = new Command.Export(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.KEY_PUBLIC, EC_Consts.PARAMETER_W).send();
        byte[] pubkey = key.getParameter(ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.KEY_PUBLIC);
        EC_Curve secgCurve = EC_Store.getInstance().getObject(EC_Curve.class, "secg", CardUtil.getCurveName(curveId));
        ECPoint pub;
        try {
            pub = ECUtil.fromX962(pubkey, secgCurve.toCurve());
        } catch (IllegalArgumentException iae) {
            doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "", compressionTests.toArray(new Test[0])));
            continue;
        }

        List<Test> kaTests = new LinkedList<>();
        for (byte kaType : EC_Consts.KA_TYPES) {
            List<Test> thisTests = new LinkedList<>();
            Test allocate = runTest(CommandTest.expect(new Command.AllocateKeyAgreement(this.card, kaType), Result.ExpectedValue.SUCCESS));
            if (allocate.ok()) {
                Test ka = runTest(CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, kaType), Result.ExpectedValue.SUCCESS));

                thisTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "KeyAgreement setup and basic test.", allocate, ka));
                if (ka.ok()) {
                    // tests of the good stuff
                    Test kaCompressed = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_COMPRESS, kaType), Result.ExpectedValue.SUCCESS);
                    Test kaHybrid = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_COMPRESS_HYBRID, kaType), Result.ExpectedValue.SUCCESS);
                    thisTests.add(CompoundTest.any(Result.ExpectedValue.SUCCESS, "Tests of compressed and hybrid form.", kaCompressed, kaHybrid));

                    // tests the bad stuff here
                    byte[] pubHybrid = ECUtil.toX962Hybrid(pub, keyLength);
                    pubHybrid[pubHybrid.length - 1] ^= 1;
                    byte[] pubHybridEncoded = ByteUtil.prependLength(pubHybrid);
                    Test kaBadHybrid = CommandTest.expect(new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, kaType, pubHybridEncoded), Result.ExpectedValue.FAILURE);

                    byte[] pubInfinityEncoded = {0x01, 0x00};
                    Test kaBadInfinity = CommandTest.expect(new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, kaType, pubInfinityEncoded), Result.ExpectedValue.FAILURE);
                    thisTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests of corrupted hybrid form and infinity.", kaBadHybrid, kaBadInfinity));
                }
                kaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "KeyAgreement tests of " + CardUtil.getKATypeString(kaType) + ".", thisTests.toArray(new Test[0])));
            }
        }
        compressionTests.addAll(kaTests);
        if (cfg.cleanup) {
            compressionTests.add(CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY));
        }

        doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Compression test of " + spec + ".", compressionTests.toArray(new Test[0])));
    }
}
 
Example #20
Source File: CRTKeyFile.java    From GidsApplet with GNU General Public License v3.0 4 votes vote down vote up
public KeyPair GetKey() {
    return keyPair;
}
 
Example #21
Source File: CRTKeyFile.java    From GidsApplet with GNU General Public License v3.0 4 votes vote down vote up
public void SaveKey(KeyPair kp) {
    clearContents();
    keyPair = kp;
}