Exemple #1
0
  public void init(int key_size) throws Exception {
    String name = null;
    if (key_size == 256) name = "secp256r1";
    else if (key_size == 384) name = "secp384r1";
    else if (key_size == 521) name = "secp521r1";
    else throw new JSchException("unsupported key size: " + key_size);

    for (int i = 0; i < 1000; i++) {
      KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
      ECGenParameterSpec ecsp = new ECGenParameterSpec(name);
      kpg.initialize(ecsp);
      KeyPair kp = kpg.genKeyPair();
      prvKey = (ECPrivateKey) kp.getPrivate();
      pubKey = (ECPublicKey) kp.getPublic();
      params = pubKey.getParams();
      d = ((ECPrivateKey) prvKey).getS().toByteArray();
      ECPoint w = pubKey.getW();
      r = w.getAffineX().toByteArray();
      s = w.getAffineY().toByteArray();

      if (r.length != s.length) continue;
      if (key_size == 256 && r.length == 32) break;
      if (key_size == 384 && r.length == 48) break;
      if (key_size == 521 && r.length == 66) break;
    }
    if (d.length < r.length) {
      d = insert0(d);
    }
  }
Exemple #2
0
  public static ECPublicKey PrivateKeytoECPublicKey(byte[] privateKey)
      throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException {
    KeyPairGenerator kpg = null;
    kpg = KeyPairGenerator.getInstance("EC");

    ECGenParameterSpec gps = new ECGenParameterSpec("secp256k1"); // NIST P-256
    kpg.initialize(gps);
    KeyPair apair = kpg.generateKeyPair();
    ECPublicKey apub = (ECPublicKey) apair.getPublic();
    ECParameterSpec aspec = apub.getParams();

    byte[] publicKeyb = Address.privateKeyToPublicKey(Utils.toHex(privateKey), false);

    byte[] publicKeybx = new byte[32];
    byte[] publicKeyby = new byte[32];
    System.arraycopy(publicKeyb, 1, publicKeybx, 0, 32);
    System.arraycopy(publicKeyb, 33, publicKeyby, 0, 32);
    BigInteger x = new BigInteger(1, publicKeybx);
    BigInteger y = new BigInteger(1, publicKeyby);

    java.security.spec.ECPoint cpoint = new java.security.spec.ECPoint(x, y);
    ECPublicKeySpec cpubs = new ECPublicKeySpec(cpoint, aspec);
    ECPublicKey cpub = null;
    KeyFactory kfa = null;
    kfa = KeyFactory.getInstance("EC");
    return cpub = (ECPublicKey) kfa.generatePublic(cpubs);
  }
  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }

    if (o instanceof OpenSSLECPublicKey) {
      OpenSSLECPublicKey other = (OpenSSLECPublicKey) o;
      return key.equals(other.key);
    }

    if (!(o instanceof ECPublicKey)) {
      return false;
    }

    final ECPublicKey other = (ECPublicKey) o;
    if (!getPublicKey().equals(other.getW())) {
      return false;
    }

    final ECParameterSpec spec = getParams();
    final ECParameterSpec otherSpec = other.getParams();

    return spec.getCurve().equals(otherSpec.getCurve())
        && spec.getGenerator().equals(otherSpec.getGenerator())
        && spec.getOrder().equals(otherSpec.getOrder())
        && spec.getCofactor() == otherSpec.getCofactor();
  }
  protected void assertsEcdsaKey(ECPublicKey pubKey) {
    final String x =
        "48439561293906451759052585252797914202762949526041747995844080717082404635286";
    final String y =
        "36134250956749795798585127919587881956611106672985015071877198253568414405109";

    Assert.assertEquals(new BigInteger(x), pubKey.getParams().getGenerator().getAffineX());
    Assert.assertEquals(new BigInteger(y), pubKey.getParams().getGenerator().getAffineY());
  }
  protected void assertsEcdsaKey521(ECPublicKey pubKey) {
    final String x =
        "2661740802050217063228768716723360960729859168756973147706671368418802944"
            + "996427808491545080627771902352094241225065558662157113545570916814161637315895999846";
    final String y =
        "3757180025770020463545507224491183603594455134769762486694567779615544477"
            + "440556316691234405012945539562144444537289428522585666729196580810124344277578376784";

    Assert.assertEquals(new BigInteger(x), pubKey.getParams().getGenerator().getAffineX());
    Assert.assertEquals(new BigInteger(y), pubKey.getParams().getGenerator().getAffineY());
  }
  protected void assertsEcdsaKey384(ECPublicKey pubKey) {
    final String x =
        "26247035095799689268623156744566981891852923491109213387815615900925"
            + "518854738050089022388053975719786650872476732087";
    final String y =
        "83257109614890299855467512895201081792878530488613155947092059024805"
            + "03199884419224438643760392947333078086511627871";

    Assert.assertEquals(new BigInteger(x), pubKey.getParams().getGenerator().getAffineX());
    Assert.assertEquals(new BigInteger(y), pubKey.getParams().getGenerator().getAffineY());
  }
 public static OpenSSLKey getInstance(ECPublicKey ecPublicKey) throws InvalidKeyException {
   try {
     OpenSSLECGroupContext group = OpenSSLECGroupContext.getInstance(ecPublicKey.getParams());
     OpenSSLECPointContext pubKey =
         OpenSSLECPointContext.getInstance(
             NativeCrypto.get_EC_GROUP_type(group.getNativeRef()), group, ecPublicKey.getW());
     return new OpenSSLKey(
         NativeCrypto.EVP_PKEY_new_EC_KEY(group.getNativeRef(), pubKey.getNativeRef(), null));
   } catch (Exception e) {
     throw new InvalidKeyException(e);
   }
 }
  /**
   * The ServerKeyExchange message is sent by the server only when the server {@link
   * CertificateMessage} (if sent) does not contain enough data to allow the client to exchange a
   * premaster secret. Used when the key exchange is ECDH. The client tries to verify the server's
   * signature and on success prepares the ECDH key agreement.
   *
   * @param message the server's {@link ServerKeyExchange} message.
   * @throws HandshakeException if the message can't be verified.
   */
  private void receivedServerKeyExchange(ECDHServerKeyExchange message) throws HandshakeException {
    if (serverKeyExchange != null
        && (serverKeyExchange.getMessageSeq() == message.getMessageSeq())) {
      // discard duplicate message
      return;
    }

    serverKeyExchange = message;
    message.verifySignature(serverPublicKey, clientRandom, serverRandom);

    // get the curve parameter spec by the named curve id
    ECParameterSpec params = ECDHServerKeyExchange.NAMED_CURVE_PARAMETERS.get(message.getCurveId());
    if (params == null) {
      AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
      throw new HandshakeException("Server used unsupported elliptic curve for ECDH", alert);
    }

    ephemeralServerPublicKey = message.getPublicKey(params);
    ecdhe = new ECDHECryptography(ephemeralServerPublicKey.getParams());
  }
Exemple #9
0
  public static ECPrivateKey PrivateKeytoECPrivateKey(byte[] privateKey)
      throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException {
    KeyPairGenerator kpg = null;
    kpg = KeyPairGenerator.getInstance("EC");

    ECGenParameterSpec gps = new ECGenParameterSpec("secp256k1"); // NIST P-256
    kpg.initialize(gps);
    KeyPair apair = kpg.generateKeyPair();
    ECPublicKey apub = (ECPublicKey) apair.getPublic();
    ECParameterSpec aspec = apub.getParams();
    // could serialize aspec for later use (in compatible JRE)
    //
    // for test only reuse bogus pubkey, for real substitute values
    KeyFactory kfa = null;
    kfa = KeyFactory.getInstance("EC");
    ECPrivateKey bpriv = null;
    ECPrivateKeySpec pkeys = new ECPrivateKeySpec(new BigInteger(1, privateKey), aspec);

    return bpriv = (ECPrivateKey) kfa.generatePrivate(pkeys);
  }
  public PublicKeyDataObject getPublicKeyDataObject(
      ASN1ObjectIdentifier usage, PublicKey publicKey) {
    if (publicKey instanceof java.security.interfaces.RSAPublicKey) {
      java.security.interfaces.RSAPublicKey pubKey =
          (java.security.interfaces.RSAPublicKey) publicKey;

      return new RSAPublicKey(usage, pubKey.getModulus(), pubKey.getPublicExponent());
    } else {
      ECPublicKey pubKey = (ECPublicKey) publicKey;
      java.security.spec.ECParameterSpec params = pubKey.getParams();

      return new ECDSAPublicKey(
          usage,
          ((ECFieldFp) params.getCurve().getField()).getP(),
          params.getCurve().getA(),
          params.getCurve().getB(),
          convertPoint(convertCurve(params.getCurve()), params.getGenerator()).getEncoded(),
          params.getOrder(),
          convertPoint(convertCurve(params.getCurve()), pubKey.getW()).getEncoded(),
          params.getCofactor());
    }
  }
Exemple #11
0
  /**
   * Perform CA (Chip Authentication) part of EAC (version 1). For details see TR-03110 ver. 1.11.
   * In short, we authenticate the chip with (EC)DH key agreement protocol and create new secure
   * messaging keys.
   *
   * @param keyId passport's public key id (stored in DG14), -1 if none
   * @param publicKey passport's public key (stored in DG14)
   * @return the chip authentication result
   * @throws CardServiceException if CA failed or some error occurred
   */
  public synchronized ChipAuthenticationResult doCA(BigInteger keyId, PublicKey publicKey)
      throws CardServiceException {
    if (publicKey == null) {
      throw new IllegalArgumentException("Public key is null");
    }
    try {
      String agreementAlg = Util.inferKeyAgreementAlgorithm(publicKey);
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(agreementAlg);
      AlgorithmParameterSpec params = null;
      if ("DH".equals(agreementAlg)) {
        DHPublicKey dhPublicKey = (DHPublicKey) publicKey;
        params = dhPublicKey.getParams();
      } else if ("ECDH".equals(agreementAlg)) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        params = ecPublicKey.getParams();
      } else {
        throw new IllegalStateException("Unsupported algorithm \"" + agreementAlg + "\"");
      }
      keyPairGenerator.initialize(params);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      KeyAgreement agreement = KeyAgreement.getInstance(agreementAlg);
      agreement.init(keyPair.getPrivate());
      agreement.doPhase(publicKey, true);

      byte[] secret = agreement.generateSecret();

      // TODO: this SHA1ing may have to be removed?
      // TODO: this hashing is needed for our Java Card passport applet implementation
      // byte[] secret = md.digest(secret);

      byte[] keyData = null;
      byte[] idData = null;
      byte[] keyHash = new byte[0];
      if ("DH".equals(agreementAlg)) {
        DHPublicKey dhPublicKey = (DHPublicKey) keyPair.getPublic();
        keyData = dhPublicKey.getY().toByteArray();
        // TODO: this is probably wrong, what should be hashed?
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md = MessageDigest.getInstance("SHA1");
        keyHash = md.digest(keyData);
      } else if ("ECDH".equals(agreementAlg)) {
        org.bouncycastle.jce.interfaces.ECPublicKey ecPublicKey =
            (org.bouncycastle.jce.interfaces.ECPublicKey) keyPair.getPublic();
        keyData = ecPublicKey.getQ().getEncoded();
        byte[] t = Util.i2os(ecPublicKey.getQ().getX().toBigInteger());
        keyHash =
            Util.alignKeyDataToSize(t, ecPublicKey.getParameters().getCurve().getFieldSize() / 8);
      }
      keyData = Util.wrapDO((byte) 0x91, keyData);
      if (keyId.compareTo(BigInteger.ZERO) >= 0) {
        byte[] keyIdBytes = keyId.toByteArray();
        idData = Util.wrapDO((byte) 0x84, keyIdBytes);
      }
      sendMSEKAT(wrapper, keyData, idData);

      SecretKey ksEnc = Util.deriveKey(secret, Util.ENC_MODE);
      SecretKey ksMac = Util.deriveKey(secret, Util.MAC_MODE);
      long ssc = 0;

      wrapper = new DESedeSecureMessagingWrapper(ksEnc, ksMac, ssc);
      state = CA_AUTHENTICATED_STATE;
      return new ChipAuthenticationResult(keyId, publicKey, keyHash, keyPair);
    } catch (GeneralSecurityException e) {
      throw new CardServiceException(e.toString());
    }
  }