protected void generateEphemeralClientKeyExchange(DHParameters dhParams, OutputStream os)
      throws IOException {
    AsymmetricCipherKeyPair dhAgreeClientKeyPair = generateDHKeyPair(dhParams);
    this.dhAgreeClientPrivateKey = (DHPrivateKeyParameters) dhAgreeClientKeyPair.getPrivate();

    BigInteger Yc = ((DHPublicKeyParameters) dhAgreeClientKeyPair.getPublic()).getY();
    byte[] keData = BigIntegers.asUnsignedByteArray(Yc);
    TlsUtils.writeUint24(keData.length + 2, os);
    TlsUtils.writeOpaque16(keData, os);
  }
  protected CipherParameters keyGen(AsymmetricCipherKeyPair masterKey, Element... ids) {
    UHIBELW11SecretKeyGenerator generator = new UHIBELW11SecretKeyGenerator();
    generator.init(
        new UHIBELW11SecretKeyGenerationParameters(
            (UHIBELW11MasterSecretKeyParameters) masterKey.getPrivate(),
            (UHIBELW11PublicKeyParameters) masterKey.getPublic(),
            ids));

    return generator.generateKey();
  }
示例#3
0
  /**
   * Test Sign & Verify with test parameters see:
   * http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
   * gostR3410-2001-TestParamSet P.46
   */
  private void ecGOST3410_TestParam() {
    SecureRandom random = new SecureRandom();

    BigInteger mod_p =
        new BigInteger(
            "57896044618658097711785492504343953926634992332820282019728792003956564821041"); // p

    ECCurve.Fp curve =
        new ECCurve.Fp(
            mod_p, // p
            new BigInteger("7"), // a
            new BigInteger(
                "43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b

    ECDomainParameters params =
        new ECDomainParameters(
            curve,
            new ECPoint.Fp(
                curve,
                new ECFieldElement.Fp(mod_p, new BigInteger("2")), // x
                new ECFieldElement.Fp(
                    mod_p,
                    new BigInteger(
                        "4018974056539037503335449422937059775635739389905545080690979365213431566280"))), // y
            new BigInteger(
                "57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q

    ECKeyPairGenerator pGen = new ECKeyPairGenerator();
    ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(params, random);

    pGen.init(genParam);

    AsymmetricCipherKeyPair pair = pGen.generateKeyPair();

    ParametersWithRandom param = new ParametersWithRandom(pair.getPrivate(), random);

    ECGOST3410Signer ecgost3410 = new ECGOST3410Signer();

    ecgost3410.init(true, param);

    // get hash message using the digest GOST3411.
    byte[] message = "Message for sign".getBytes();
    GOST3411Digest gost3411 = new GOST3411Digest();
    gost3411.update(message, 0, message.length);
    byte[] hashmessage = new byte[gost3411.getDigestSize()];
    gost3411.doFinal(hashmessage, 0);

    BigInteger[] sig = ecgost3410.generateSignature(hashmessage);

    ecgost3410.init(false, pair.getPublic());

    if (!ecgost3410.verifySignature(hashmessage, sig[0], sig[1])) {
      fail("signature fails");
    }
  }
示例#4
0
  /**
   * Test Sign & Verify with B parameters see:
   * http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
   * gostR3410-2001-CryptoPro-B-ParamSet P.47-48
   */
  private void ecGOST3410_BParam() {
    SecureRandom random = new SecureRandom();

    BigInteger mod_p =
        new BigInteger(
            "57896044618658097711785492504343953926634992332820282019728792003956564823193"); // p

    ECCurve.Fp curve =
        new ECCurve.Fp(
            mod_p, // p
            new BigInteger(
                "57896044618658097711785492504343953926634992332820282019728792003956564823190"), // a
            new BigInteger(
                "28091019353058090096996979000309560759124368558014865957655842872397301267595")); // b

    ECDomainParameters params =
        new ECDomainParameters(
            curve,
            new ECPoint.Fp(
                curve,
                new ECFieldElement.Fp(mod_p, new BigInteger("1")), // x
                new ECFieldElement.Fp(
                    mod_p,
                    new BigInteger(
                        "28792665814854611296992347458380284135028636778229113005756334730996303888124"))), // y
            new BigInteger(
                "57896044618658097711785492504343953927102133160255826820068844496087732066703")); // q

    ECKeyPairGenerator pGen = new ECKeyPairGenerator();
    ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(params, random);

    pGen.init(genParam);

    AsymmetricCipherKeyPair pair = pGen.generateKeyPair();

    ParametersWithRandom param = new ParametersWithRandom(pair.getPrivate(), random);

    ECGOST3410Signer ecgost3410 = new ECGOST3410Signer();

    ecgost3410.init(true, param);

    BigInteger[] sig = ecgost3410.generateSignature(hashmessage);

    ecgost3410.init(false, pair.getPublic());

    if (!ecgost3410.verifySignature(hashmessage, sig[0], sig[1])) {
      fail("signature fails");
    }
  }
示例#5
0
  /**
   * Test Sign & Verify with C parameters see:
   * http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
   * gostR3410-2001-CryptoPro-C-ParamSet P.48
   */
  private void ecGOST3410_CParam() {
    SecureRandom random = new SecureRandom();

    BigInteger mod_p =
        new BigInteger(
            "70390085352083305199547718019018437841079516630045180471284346843705633502619"); // p

    ECCurve.Fp curve =
        new ECCurve.Fp(
            mod_p, // p
            new BigInteger(
                "70390085352083305199547718019018437841079516630045180471284346843705633502616"), // a
            new BigInteger("32858")); // b

    ECDomainParameters params =
        new ECDomainParameters(
            curve,
            new ECPoint.Fp(
                curve,
                new ECFieldElement.Fp(mod_p, new BigInteger("0")), // x
                new ECFieldElement.Fp(
                    mod_p,
                    new BigInteger(
                        "29818893917731240733471273240314769927240550812383695689146495261604565990247"))), // y
            new BigInteger(
                "70390085352083305199547718019018437840920882647164081035322601458352298396601")); // q

    ECKeyPairGenerator pGen = new ECKeyPairGenerator();
    ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(params, random);

    pGen.init(genParam);

    AsymmetricCipherKeyPair pair = pGen.generateKeyPair();

    ParametersWithRandom param = new ParametersWithRandom(pair.getPrivate(), random);

    ECGOST3410Signer ecgost3410 = new ECGOST3410Signer();

    ecgost3410.init(true, param);

    BigInteger[] sig = ecgost3410.generateSignature(hashmessage);

    ecgost3410.init(false, pair.getPublic());

    if (!ecgost3410.verifySignature(hashmessage, sig[0], sig[1])) {
      fail("signature fails");
    }
  }
示例#6
0
  /**
   * Test Sign & Verify with A parameters see:
   * http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
   * gostR3410-2001-CryptoPro-A-ParamSet P.47
   */
  public void ecGOST3410_AParam() {
    SecureRandom random = new SecureRandom();

    BigInteger mod_p =
        new BigInteger(
            "115792089237316195423570985008687907853269984665640564039457584007913129639319"); // p

    ECCurve.Fp curve =
        new ECCurve.Fp(
            mod_p, // p
            new BigInteger(
                "115792089237316195423570985008687907853269984665640564039457584007913129639316"), // a
            new BigInteger("166")); // b

    ECDomainParameters params =
        new ECDomainParameters(
            curve,
            new ECPoint.Fp(
                curve,
                new ECFieldElement.Fp(mod_p, new BigInteger("1")), // x
                new ECFieldElement.Fp(
                    mod_p,
                    new BigInteger(
                        "64033881142927202683649881450433473985931760268884941288852745803908878638612"))), // y
            new BigInteger(
                "115792089237316195423570985008687907853073762908499243225378155805079068850323")); // q

    ECKeyPairGenerator pGen = new ECKeyPairGenerator();
    ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(params, random);

    pGen.init(genParam);

    AsymmetricCipherKeyPair pair = pGen.generateKeyPair();

    ParametersWithRandom param = new ParametersWithRandom(pair.getPrivate(), random);

    ECGOST3410Signer ecgost3410 = new ECGOST3410Signer();

    ecgost3410.init(true, param);

    BigInteger[] sig = ecgost3410.generateSignature(hashmessage);

    ecgost3410.init(false, pair.getPublic());

    if (!ecgost3410.verifySignature(hashmessage, sig[0], sig[1])) {
      fail("signature fails");
    }
  }
  protected CipherParameters delegate(
      AsymmetricCipherKeyPair masterKey, CipherParameters secretKey, Element id) {
    UHIBELW11SecretKeyGenerator generator = new UHIBELW11SecretKeyGenerator();
    generator.init(
        new UHIBELW11DelegateGenerationParameters(
            (UHIBELW11PublicKeyParameters) masterKey.getPublic(),
            (UHIBELW11SecretKeyParameters) secretKey,
            id));

    return generator.generateKey();
  }
  @Test
  public void test() {
    // Setup
    AsymmetricCipherKeyPair keyPair = setup(32);

    // KeyGen
    Element[] ids = map(keyPair.getPublic(), "angelo", "de caro", "unisa");

    CipherParameters sk0 = keyGen(keyPair, ids[0]);
    CipherParameters sk01 = keyGen(keyPair, ids[0], ids[1]);
    CipherParameters sk012 = keyGen(keyPair, ids[0], ids[1], ids[2]);

    CipherParameters sk1 = keyGen(keyPair, ids[1]);
    CipherParameters sk10 = keyGen(keyPair, ids[1], ids[0]);
    CipherParameters sk021 = keyGen(keyPair, ids[0], ids[2], ids[1]);

    // Encrypt
    byte[] ciphertext0 = encrypt(keyPair.getPublic(), ids[0]);
    byte[] ciphertext01 = encrypt(keyPair.getPublic(), ids[0], ids[1]);
    byte[] ciphertext012 = encrypt(keyPair.getPublic(), ids[0], ids[1], ids[2]);

    // Test
    assertEquals(true, evaluate(sk0, ciphertext0));
    assertEquals(true, evaluate(sk01, ciphertext01));
    assertEquals(true, evaluate(sk012, ciphertext012));

    assertEquals(false, evaluate(sk1, ciphertext0));
    assertEquals(false, evaluate(sk10, ciphertext01));
    assertEquals(false, evaluate(sk021, ciphertext012));

    // Delegate and Test
    assertEquals(true, evaluate(delegate(keyPair, sk0, ids[1]), ciphertext01));
    assertEquals(true, evaluate(delegate(keyPair, sk01, ids[2]), ciphertext012));
    assertEquals(
        true, evaluate(delegate(keyPair, delegate(keyPair, sk0, ids[1]), ids[2]), ciphertext012));

    assertEquals(false, evaluate(delegate(keyPair, sk0, ids[2]), ciphertext01));
    assertEquals(false, evaluate(delegate(keyPair, sk01, ids[1]), ciphertext012));
    assertEquals(
        false, evaluate(delegate(keyPair, delegate(keyPair, sk0, ids[2]), ids[1]), ciphertext012));
  }
示例#9
0
  private void testDetachedRSA() throws Exception {
    Digest md = new SHA1Digest();
    List certList = new ArrayList();
    CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes());

    certList.add(_origCert);
    certList.add(_signCert);

    Store certs = new CollectionStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    byte[] digValue = new byte[md.getDigestSize()];
    byte[] data = "Hello world!".getBytes();

    md.update(data, 0, data.length);
    md.doFinal(digValue, 0);

    Attribute attr =
        new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digValue)));

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(attr);

    AsymmetricKeyParameter privKey = (AsymmetricKeyParameter) _origKP.getPrivate();

    AlgorithmIdentifier sigAlgId =
        new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    BcContentSignerBuilder contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);

    gen.addSignerInfoGenerator(
        new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
            .setSignedAttributeGenerator(
                new DefaultSignedAttributeTableGenerator(new AttributeTable(v)))
            .build(contentSignerBuilder.build(privKey), _origCert));

    gen.addCertificates(certs);

    CMSSignedData s = gen.generate(new CMSAbsentContent(), false);

    //
    // the signature is detached, so need to add msg before passing on
    //
    s = new CMSSignedData(msg, s.getEncoded());
    //
    // compute expected content digest
    //

    verifyRSASignatures(s, digValue);
  }
  @Override
  public byte[] prepareMessageAction() {
    // To use true DH ephemeral we need to precompute the prime number P(DH modulus)
    /**
     * int defaultPrimeProbability = 30;
     *
     * <p>DHParametersGenerator generator = new DHParametersGenerator(); //Genration of a higher bit
     * prime number takes too long (512 bits takes 2 seconds) generator.init(512,
     * defaultPrimeProbability, new SecureRandom()); DHParameters params =
     * generator.generateParameters();
     */
    DHPublicKeyParameters dhPublic;

    // fixed DH modulus P and DH generator G
    byte[] pArray =
        ArrayConverter.hexStringToByteArray(
            "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc"
                + "74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d"
                + "51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24"
                + "117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83"
                + "655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca1821"
                + "7c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695"
                + "5817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff");
    byte[] gArray = {0x02};
    BigInteger p = new BigInteger(1, pArray);
    BigInteger g = new BigInteger(1, gArray);
    DHParameters params = new DHParameters(p, g);

    KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), params);
    DHKeyPairGenerator keyGen = new DHKeyPairGenerator();
    keyGen.init(kgp);
    AsymmetricCipherKeyPair serverKeyPair = keyGen.generateKeyPair();

    dhPublic = (DHPublicKeyParameters) serverKeyPair.getPublic();
    DHPrivateKeyParameters dhPrivate = (DHPrivateKeyParameters) serverKeyPair.getPrivate();

    protocolMessage.setG(dhPublic.getParameters().getG());
    protocolMessage.setP(dhPublic.getParameters().getP());
    protocolMessage.setPublicKey(dhPublic.getY());
    protocolMessage.setPrivateKey(dhPrivate.getX());
    tlsContext.setServerDHPrivateKeyParameters(dhPrivate);

    byte[] serializedP = BigIntegers.asUnsignedByteArray(protocolMessage.getP().getValue());
    protocolMessage.setSerializedP(serializedP);
    protocolMessage.setSerializedPLength(serializedP.length);

    byte[] serializedG = BigIntegers.asUnsignedByteArray(protocolMessage.getG().getValue());
    protocolMessage.setSerializedG(serializedG);
    protocolMessage.setSerializedGLength(serializedG.length);

    byte[] serializedPublicKey =
        BigIntegers.asUnsignedByteArray(protocolMessage.getPublicKey().getValue());
    protocolMessage.setSerializedPublicKey(serializedPublicKey);
    protocolMessage.setSerializedPublicKeyLength(serializedPublicKey.length);

    byte[] dhParams =
        ArrayConverter.concatenate(
            ArrayConverter.intToBytes(
                protocolMessage.getSerializedPLength().getValue(),
                HandshakeByteLength.DH_PARAM_LENGTH),
            protocolMessage.getSerializedP().getValue(),
            ArrayConverter.intToBytes(
                protocolMessage.getSerializedGLength().getValue(),
                HandshakeByteLength.DH_PARAM_LENGTH),
            protocolMessage.getSerializedG().getValue(),
            ArrayConverter.intToBytes(
                protocolMessage.getSerializedPublicKeyLength().getValue(),
                HandshakeByteLength.DH_PARAM_LENGTH),
            protocolMessage.getSerializedPublicKey().getValue());
    InputStream is = new ByteArrayInputStream(dhParams);

    try {
      ServerDHParams publicKeyParameters = ServerDHParams.parse(is);

      tlsContext.setServerDHParameters(publicKeyParameters);

      KeyStore ks = tlsContext.getKeyStore();

      // could be extended to choose the algorithms depending on the certificate
      SignatureAndHashAlgorithm selectedSignatureHashAlgo =
          new SignatureAndHashAlgorithm(SignatureAlgorithm.RSA, HashAlgorithm.SHA1);
      protocolMessage.setSignatureAlgorithm(
          selectedSignatureHashAlgo.getSignatureAlgorithm().getValue());
      protocolMessage.setHashAlgorithm(selectedSignatureHashAlgo.getHashAlgorithm().getValue());

      Key key = ks.getKey(tlsContext.getAlias(), tlsContext.getPassword().toCharArray());

      RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;

      Signature instance = Signature.getInstance(selectedSignatureHashAlgo.getJavaName());
      instance.initSign(rsaKey);
      LOGGER.debug(
          "SignatureAndHashAlgorithm for ServerKeyExchange message: {}",
          selectedSignatureHashAlgo.getJavaName());

      byte[] toBeSignedBytes =
          ArrayConverter.concatenate(
              tlsContext.getClientRandom(), tlsContext.getServerRandom(), dhParams);

      instance.update(toBeSignedBytes);
      byte[] signature = instance.sign();
      protocolMessage.setSignature(signature);
      protocolMessage.setSignatureLength(signature.length);

      byte[] result =
          ArrayConverter.concatenate(
              dhParams,
              new byte[] {
                protocolMessage.getHashAlgorithm().getValue(),
                protocolMessage.getSignatureAlgorithm().getValue()
              },
              ArrayConverter.intToBytes(
                  protocolMessage.getSignatureLength().getValue(),
                  HandshakeByteLength.SIGNATURE_LENGTH),
              protocolMessage.getSignature().getValue());

      protocolMessage.setLength(result.length);

      long header =
          (HandshakeMessageType.SERVER_KEY_EXCHANGE.getValue() << 24)
              + protocolMessage.getLength().getValue();

      protocolMessage.setCompleteResultingMessage(
          ArrayConverter.concatenate(ArrayConverter.longToUint32Bytes(header), result));

    } catch (KeyStoreException
        | NoSuchAlgorithmException
        | UnrecoverableKeyException
        | InvalidKeyException
        | SignatureException
        | IOException ex) {
      throw new ConfigurationException(ex.getLocalizedMessage(), ex);
    }

    return protocolMessage.getCompleteResultingMessage().getValue();
  }