Search in sources :

Example 51 with KeyPairGenerator

use of java.security.KeyPairGenerator in project wycheproof by google.

the class EcdhTest method testBasic.

/** Checks that key agreement using ECDH works. */
public void testBasic() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
    keyGen.initialize(ecSpec);
    KeyPair keyPairA = keyGen.generateKeyPair();
    KeyPair keyPairB = keyGen.generateKeyPair();
    KeyAgreement kaA = KeyAgreement.getInstance("ECDH");
    KeyAgreement kaB = KeyAgreement.getInstance("ECDH");
    kaA.init(keyPairA.getPrivate());
    kaB.init(keyPairB.getPrivate());
    kaA.doPhase(keyPairB.getPublic(), true);
    kaB.doPhase(keyPairA.getPublic(), true);
    byte[] kAB = kaA.generateSecret();
    byte[] kBA = kaB.generateSecret();
    assertEquals(TestUtil.bytesToHex(kAB), TestUtil.bytesToHex(kBA));
}
Also used : KeyPair(java.security.KeyPair) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) KeyAgreement(javax.crypto.KeyAgreement)

Example 52 with KeyPairGenerator

use of java.security.KeyPairGenerator in project wycheproof by google.

the class EcdhTest method testWrongOrder.

/**
   * This test modifies the order of group in the public key. A severe bug would be an
   * implementation that leaks information whether the private key is larger than the order given in
   * the public key. Also a severe bug would be to reduce the private key modulo the order given in
   * the public key parameters.
   */
// TODO(bleichen): This can be merged with testModifiedPublic once this is fixed.
@SuppressWarnings("InsecureCryptoUsage")
public void testWrongOrder(String algorithm, ECParameterSpec spec) throws Exception {
    KeyAgreement ka;
    try {
        ka = KeyAgreement.getInstance(algorithm);
    } catch (NoSuchAlgorithmException ex) {
        System.out.println("testWrongOrder: " + algorithm + " not supported");
        return;
    }
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    ECPrivateKey priv;
    ECPublicKey pub;
    try {
        keyGen.initialize(spec);
        priv = (ECPrivateKey) keyGen.generateKeyPair().getPrivate();
        pub = (ECPublicKey) keyGen.generateKeyPair().getPublic();
    } catch (GeneralSecurityException ex) {
        // This is OK, since not all provider support Brainpool curves
        System.out.println("testWrongOrder: could not generate keys for curve");
        return;
    }
    // Get the shared secret for the unmodified keys.
    ka.init(priv);
    ka.doPhase(pub, true);
    byte[] shared = ka.generateSecret();
    // Generate a modified public key.
    ECParameterSpec modifiedParams = new ECParameterSpec(spec.getCurve(), spec.getGenerator(), spec.getOrder().shiftRight(16), 1);
    ECPublicKeySpec modifiedPubSpec = new ECPublicKeySpec(pub.getW(), modifiedParams);
    KeyFactory kf = KeyFactory.getInstance("EC");
    ECPublicKey modifiedPub;
    try {
        modifiedPub = (ECPublicKey) kf.generatePublic(modifiedPubSpec);
    } catch (GeneralSecurityException ex) {
        // The provider does not support non-standard curves or did a validity check.
        // Both would be correct.
        System.out.println("testWrongOrder: can't modify order.");
        return;
    }
    byte[] shared2;
    try {
        ka.init(priv);
        ka.doPhase(modifiedPub, true);
        shared2 = ka.generateSecret();
    } catch (GeneralSecurityException ex) {
        // This is the expected behavior
        System.out.println("testWrongOrder:" + ex.toString());
        return;
    }
    // TODO(bleichen): Getting here is already a bug and we might flag this later.
    // At the moment we are only interested in really bad behavior of a library, that potentially
    // leaks the secret key. This is the case when the shared secrets are different, since this
    // suggests that the implementation reduces the multiplier modulo the given order of the curve
    // or some other behaviour that is dependent on the private key.
    // An attacker who can check whether a DH computation was done correctly or incorrectly because
    // of modular reduction, can determine the private key, either by a binary search or by trying
    // to guess the private key modulo some small "order".
    // BouncyCastle v.1.53 fails this test, and leaks the private key.
    System.out.println("Generated shared secret with a modified order:" + algorithm + "\n" + "expected:" + TestUtil.bytesToHex(shared) + " computed:" + TestUtil.bytesToHex(shared2));
    assertEquals("Algorithm:" + algorithm, TestUtil.bytesToHex(shared), TestUtil.bytesToHex(shared2));
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) ECPublicKey(java.security.interfaces.ECPublicKey) ECParameterSpec(java.security.spec.ECParameterSpec) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyPairGenerator(java.security.KeyPairGenerator) KeyAgreement(javax.crypto.KeyAgreement) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) KeyFactory(java.security.KeyFactory)

Example 53 with KeyPairGenerator

use of java.security.KeyPairGenerator in project wycheproof by google.

the class EcdsaTest method testBias.

/** Checks whether the one time key k in ECDSA is biased. */
public void testBias(String algorithm, String curve, ECParameterSpec ecParams) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    try {
        keyGen.initialize(ecParams);
    } catch (InvalidAlgorithmParameterException ex) {
        System.out.println("This provider does not support curve:" + curve);
        return;
    }
    KeyPair keyPair = keyGen.generateKeyPair();
    ECPrivateKey priv = (ECPrivateKey) keyPair.getPrivate();
    // If we throw a fair coin tests times then the probability that
    // either heads or tails appears less than mincount is less than 2^{-32}.
    // Therefore the test below is not expected to fail unless the generation
    // of the one time keys is indeed biased.
    final int tests = 1024;
    final int mincount = 410;
    String hashAlgorithm = getHashAlgorithm(algorithm);
    String message = "Hello";
    byte[] messageBytes = message.getBytes("UTF-8");
    byte[] digest = MessageDigest.getInstance(hashAlgorithm).digest(messageBytes);
    // TODO(bleichen): Truncate the digest if the digest size is larger than the
    //   curve size.
    BigInteger h = new BigInteger(1, digest);
    BigInteger q = priv.getParams().getOrder();
    BigInteger qHalf = q.shiftRight(1);
    Signature signer = Signature.getInstance(algorithm);
    signer.initSign(priv);
    // count the number of k's with msb set
    int countLsb = 0;
    // count the number of k's with lsb set
    int countMsb = 0;
    for (int i = 0; i < tests; i++) {
        signer.update(messageBytes);
        byte[] signature = signer.sign();
        BigInteger k = extractK(signature, h, priv);
        if (k.testBit(0)) {
            countLsb++;
        }
        if (k.compareTo(qHalf) == 1) {
            countMsb++;
        }
    }
    System.out.println(signer.getProvider().getName() + " curve:" + curve + " countLsb:" + countLsb + " countMsb:" + countMsb);
    if (countLsb < mincount || countLsb > tests - mincount) {
        fail("Bias detected in the least significant bit of k:" + countLsb);
    }
    if (countMsb < mincount || countMsb > tests - mincount) {
        fail("Bias detected in the most significant bit of k:" + countMsb);
    }
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) KeyPair(java.security.KeyPair) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) Signature(java.security.Signature) BigInteger(java.math.BigInteger) KeyPairGenerator(java.security.KeyPairGenerator) ECPoint(java.security.spec.ECPoint)

Example 54 with KeyPairGenerator

use of java.security.KeyPairGenerator in project wycheproof by google.

the class EciesTest method testExceptions.

/**
   * Tries to decrypt ciphertexts where the symmetric part has been randomized.
   * If this randomization leads to distinguishable exceptions then this may indicate that the
   * implementation is vulnerable to a padding attack.
   *
   * Problems detected:
   * <ul>
   * <li> CVE-2016-1000345 BouncyCastle before v.1.56 is vulnerable to a padding oracle attack.
   * </ul>
   */
@SuppressWarnings("InsecureCryptoUsage")
public void testExceptions(String algorithm) throws Exception {
    Cipher ecies;
    try {
        ecies = Cipher.getInstance(algorithm);
    } catch (NoSuchAlgorithmException ex) {
        // Allowing to skip the algorithm
        System.out.println("No implementation for:" + algorithm);
        return;
    }
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
    final int kemSize = 65;
    KeyPairGenerator kf = KeyPairGenerator.getInstance("EC");
    kf.initialize(ecSpec);
    KeyPair keyPair = kf.generateKeyPair();
    PrivateKey priv = keyPair.getPrivate();
    PublicKey pub = keyPair.getPublic();
    byte[] message = new byte[40];
    ecies.init(Cipher.ENCRYPT_MODE, pub);
    byte[] ciphertext = ecies.doFinal(message);
    System.out.println(TestUtil.bytesToHex(ciphertext));
    ecies.init(Cipher.DECRYPT_MODE, priv, ecies.getParameters());
    HashSet<String> exceptions = new HashSet<String>();
    for (int byteNr = kemSize; byteNr < ciphertext.length; byteNr++) {
        for (int bit = 0; bit < 8; bit++) {
            byte[] corrupt = Arrays.copyOf(ciphertext, ciphertext.length);
            corrupt[byteNr] ^= (byte) (1 << bit);
            ecies.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
            try {
                ecies.doFinal(corrupt);
                fail("Decrypted:" + TestUtil.bytesToHex(corrupt));
            } catch (Exception ex) {
                String exception = ex.toString();
                if (exceptions.add(exception)) {
                    System.out.println(algorithm + ":" + exception);
                }
            }
        }
    }
    assertEquals(1, exceptions.size());
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) PublicKey(java.security.PublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyPairGenerator(java.security.KeyPairGenerator) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Cipher(javax.crypto.Cipher) HashSet(java.util.HashSet)

Example 55 with KeyPairGenerator

use of java.security.KeyPairGenerator in project wycheproof by google.

the class RsaEncryptionTest method testExceptions.

/**
   * Tries decrypting random messages with a given algorithm. Counts the number of distinct error
   * messages and expects this number to be 1.
   *
   * <p><b>References:</b>
   *
   * <ul>
   *   <li>Bleichenbacher, "Chosen ciphertext attacks against protocols based on the RSA encryption
   *       standard PKCS# 1" Crypto 98
   *   <li>Manger, "A chosen ciphertext attack on RSA optimal asymmetric encryption padding (OAEP)
   *       as standardized in PKCS# 1 v2.0", Crypto 2001 This paper shows that OAEP is susceptible
   *       to a chosen ciphertext attack if error messages distinguish between different failure
   *       condidtions.
   *   <li>Bardou, Focardi, Kawamoto, Simionato, Steel, Tsay "Efficient Padding Oracle Attacks on
   *       Cryptographic Hardware", Crypto 2012 The paper shows that small differences on what
   *       information an attacker recieves can make a big difference on the number of chosen
   *       message necessary for an attack.
   *   <li>Smart, "Errors matter: Breaking RSA-based PIN encryption with thirty ciphertext validity
   *       queries" RSA conference, 2010 This paper shows that padding oracle attacks can be
   *       successful with even a small number of queries.
   * </ul>
   *
   * <p><b>Some recent bugs:</b> CVE-2012-5081: Java JSSE provider leaked information through
   * exceptions and timing. Both the PKCS #1 padding and the OAEP padding were broken:
   * http://www-brs.ub.ruhr-uni-bochum.de/netahtml/HSS/Diss/MeyerChristopher/diss.pdf
   *
   * <p><b>What this test does not (yet) cover:</b>
   *
   * <ul>
   *   <li> A previous version of one of the provider leaked the block type. (when was this fixed?)
   *   <li> Some attacks require a large number of ciphertexts to be detected if random ciphertexts
   *       are used. Such problems require specifically crafted ciphertexts to run in a unit test.
   *       E.g. "Attacking RSA-based Sessions in SSL/TLS" by V. Klima, O. Pokorny, and T. Rosa:
   *       https://eprint.iacr.org/2003/052/
   *   <li> Timing leakages because of differences in parsing the padding (e.g. CVE-2015-7827) Such
   *       differences are too small to be reliably detectable in unit tests.
   * </ul>
   */
@SuppressWarnings("InsecureCryptoUsage")
public void testExceptions(String algorithm) throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(1024);
    KeyPair keypair = keygen.genKeyPair();
    SecureRandom rand = new SecureRandom();
    Cipher c = Cipher.getInstance(algorithm);
    byte[] ciphertext = new byte[1024 / 8];
    HashSet<String> exceptions = new HashSet<String>();
    final int samples = 1000;
    for (int i = 0; i < samples; i++) {
        rand.nextBytes(ciphertext);
        ciphertext[0] &= (byte) 0x7f;
        try {
            c.init(Cipher.DECRYPT_MODE, keypair.getPrivate());
            c.doFinal(ciphertext);
        } catch (Exception ex) {
            exceptions.add(ex.toString());
        }
    }
    Cipher enc = Cipher.getInstance("RSA/ECB/NOPADDING");
    enc.init(Cipher.ENCRYPT_MODE, keypair.getPublic());
    c.init(Cipher.DECRYPT_MODE, keypair.getPrivate());
    byte[][] paddedKeys = generatePkcs1Vectors(1024 / 8);
    for (int i = 0; i < paddedKeys.length; i++) {
        ciphertext = enc.doFinal(paddedKeys[i]);
        try {
            c.doFinal(ciphertext);
        } catch (Exception ex) {
            exceptions.add(ex.toString());
        }
    }
    if (exceptions.size() > 1) {
        System.out.println("Exceptions for " + algorithm);
        for (String s : exceptions) {
            System.out.println(s);
        }
        fail("Exceptions leak information about the padding for " + algorithm);
    }
}
Also used : KeyPair(java.security.KeyPair) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) Cipher(javax.crypto.Cipher) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HashSet(java.util.HashSet)

Aggregations

KeyPairGenerator (java.security.KeyPairGenerator)197 KeyPair (java.security.KeyPair)145 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)43 SecureRandom (java.security.SecureRandom)39 PublicKey (java.security.PublicKey)27 PrivateKey (java.security.PrivateKey)26 X509Certificate (java.security.cert.X509Certificate)23 KeyFactory (java.security.KeyFactory)21 IOException (java.io.IOException)19 BigInteger (java.math.BigInteger)17 GeneralSecurityException (java.security.GeneralSecurityException)15 Signature (java.security.Signature)15 Date (java.util.Date)15 Cipher (javax.crypto.Cipher)15 KeyAgreement (javax.crypto.KeyAgreement)15 RSAPublicKey (java.security.interfaces.RSAPublicKey)14 X500Principal (javax.security.auth.x500.X500Principal)13 ECPrivateKey (java.security.interfaces.ECPrivateKey)12 ECPublicKey (java.security.interfaces.ECPublicKey)12 HashMap (java.util.HashMap)11