Search in sources :

Example 71 with KeyPair

use of java.security.KeyPair 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 72 with KeyPair

use of java.security.KeyPair 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 73 with KeyPair

use of java.security.KeyPair 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 74 with KeyPair

use of java.security.KeyPair 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)

Example 75 with KeyPair

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

the class RsaKeyTest method testKeyGenerationSize.

public void testKeyGenerationSize(int keySizeInBits) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(keySizeInBits);
    KeyPair keypair = keyGen.genKeyPair();
    checkKeyPair(keypair, keySizeInBits);
}
Also used : KeyPair(java.security.KeyPair) KeyPairGenerator(java.security.KeyPairGenerator)

Aggregations

KeyPair (java.security.KeyPair)313 KeyPairGenerator (java.security.KeyPairGenerator)146 X509Certificate (java.security.cert.X509Certificate)61 PrivateKey (java.security.PrivateKey)60 PublicKey (java.security.PublicKey)59 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)36 IOException (java.io.IOException)34 SecureRandom (java.security.SecureRandom)31 Test (org.junit.Test)26 KeyFactory (java.security.KeyFactory)23 KeyStore (java.security.KeyStore)23 Date (java.util.Date)22 BigInteger (java.math.BigInteger)21 Signature (java.security.Signature)19 File (java.io.File)17 Cipher (javax.crypto.Cipher)17 KeyPairGeneratorSpec (android.security.KeyPairGeneratorSpec)16 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)16 RSAPublicKey (java.security.interfaces.RSAPublicKey)16 HashMap (java.util.HashMap)16