Search in sources :

Example 26 with KeyPair

use of java.security.KeyPair in project kdeconnect-android by KDE.

the class NetworkPackageTest method testEncryption.

public void testEncryption() throws JSONException {
    NetworkPackage original = new NetworkPackage("com.test");
    original.set("hello", "hola");
    NetworkPackage copy = NetworkPackage.unserialize(original.serialize());
    NetworkPackage decrypted = new NetworkPackage("");
    KeyPair keyPair;
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        keyPair = keyGen.genKeyPair();
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/initializeRsaKeys", "Exception");
        return;
    }
    PrivateKey privateKey = keyPair.getPrivate();
    assertNotNull(privateKey);
    PublicKey publicKey = keyPair.getPublic();
    assertNotNull(publicKey);
    // Encrypt and decrypt np
    assertEquals(original.getType(), "com.test");
    try {
        NetworkPackage encrypted = RsaHelper.encrypt(original, publicKey);
        assertEquals(encrypted.getType(), NetworkPackage.PACKAGE_TYPE_ENCRYPTED);
        decrypted = RsaHelper.decrypt(encrypted, privateKey);
        assertEquals(decrypted.getType(), "com.test");
    } catch (Exception e) {
        e.printStackTrace();
    }
    // np should be equal to np2
    assertEquals(decrypted.getLong("id"), copy.getLong("id"));
    assertEquals(decrypted.getType(), copy.getType());
    assertEquals(decrypted.getJSONArray("body"), copy.getJSONArray("body"));
    String json = "{\"body\":{\"nowPlaying\":\"A really long song name - A really long artist name\",\"player\":\"A really long player name\",\"the_meaning_of_life_the_universe_and_everything\":\"42\"},\"id\":945945945,\"type\":\"kdeconnect.a_really_really_long_package_type\"}\n";
    NetworkPackage longJsonNp = NetworkPackage.unserialize(json);
    try {
        NetworkPackage encrypted = RsaHelper.encrypt(longJsonNp, publicKey);
        decrypted = RsaHelper.decrypt(encrypted, privateKey);
        String decryptedJson = decrypted.serialize();
        JSONAssert.assertEquals(json, decryptedJson, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) KeyPairGenerator(java.security.KeyPairGenerator) JSONException(org.json.JSONException)

Example 27 with KeyPair

use of java.security.KeyPair in project jdk8u_jdk by JetBrains.

the class RSAEncryptDecrypt method main.

public static void main(String[] args) throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SunMSCAPI");
    KeyPair keyPair = generator.generateKeyPair();
    Key publicKey = keyPair.getPublic();
    Key privateKey = keyPair.getPrivate();
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("RSA", "SunMSCAPI");
    } catch (GeneralSecurityException e) {
        System.out.println("Cipher not supported by provider, skipping...");
        return;
    }
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    displayBytes("Plaintext data:", PLAINTEXT);
    byte[] data = cipher.doFinal(PLAINTEXT);
    displayBytes("Encrypted data:", data);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    data = cipher.doFinal(data);
    displayBytes("Decrypted data:", data);
}
Also used : KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) KeyPairGenerator(java.security.KeyPairGenerator) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Example 28 with KeyPair

use of java.security.KeyPair in project jdk8u_jdk by JetBrains.

the class Offsets method init.

static Offsets init(String provider, String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    // fill the cleartext data with random bytes
    byte[] cleartext = new byte[100];
    RandomFactory.getRandom().nextBytes(cleartext);
    // NONEwith requires input to be of 20 bytes
    int size = algorithm.contains("NONEwith") ? 20 : 100;
    // create signature instance
    Signature signature = Signature.getInstance(algorithm, provider);
    String keyAlgo;
    if (algorithm.contains("RSA")) {
        keyAlgo = "RSA";
    } else if (algorithm.contains("ECDSA")) {
        keyAlgo = "EC";
    } else if (algorithm.contains("DSA")) {
        keyAlgo = "DSA";
    } else {
        throw new RuntimeException("Test doesn't support this signature " + "algorithm: " + algorithm);
    }
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubkey = kp.getPublic();
    PrivateKey privkey = kp.getPrivate();
    return new Offsets(signature, pubkey, privkey, size, cleartext);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) Signature(java.security.Signature) KeyPairGenerator(java.security.KeyPairGenerator)

Example 29 with KeyPair

use of java.security.KeyPair in project jdk8u_jdk by JetBrains.

the class VerifyRangeCheckOverflow method main.

public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
    keyPairGenerator.initialize(1024);
    KeyPair keys = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keys.getPublic();
    byte[] sigBytes = new byte[100];
    Signature signature = Signature.getInstance("SHA1withDSA");
    signature.initVerify(publicKey);
    try {
        signature.verify(sigBytes, Integer.MAX_VALUE, 1);
    } catch (IllegalArgumentException ex) {
    // Expected
    }
}
Also used : KeyPair(java.security.KeyPair) PublicKey(java.security.PublicKey) Signature(java.security.Signature) KeyPairGenerator(java.security.KeyPairGenerator)

Example 30 with KeyPair

use of java.security.KeyPair in project jdk8u_jdk by JetBrains.

the class Chain method runTest.

static boolean runTest(Test test) {
    System.out.format("Test: provider = %s, signature algorithm = %s, " + "key algorithm = %s\n", test.provider, test.sigAlg, test.keyAlg);
    try {
        // Generate all private/public key pairs
        PrivateKey[] privKeys = new PrivateKey[N];
        PublicKey[] pubKeys = new PublicKey[N];
        PublicKey[] anotherPubKeys = new PublicKey[N];
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(test.keyAlg.name);
        for (int j = 0; j < N; j++) {
            KeyPair kp = kpg.genKeyPair();
            KeyPair anotherKp = kpg.genKeyPair();
            privKeys[j] = kp.getPrivate();
            pubKeys[j] = kp.getPublic();
            anotherPubKeys[j] = anotherKp.getPublic();
            if (Arrays.equals(pubKeys[j].getEncoded(), anotherPubKeys[j].getEncoded())) {
                System.out.println("Failed: it should not get " + "the same pair of public key");
                return false;
            }
        }
        Signature signature;
        if (test.provider != Provider.Default) {
            signature = Signature.getInstance(test.sigAlg.name, test.provider.name);
        } else {
            signature = Signature.getInstance(test.sigAlg.name);
        }
        // Create a chain of signed objects
        SignedObject[] objects = new SignedObject[N];
        objects[0] = new SignedObject(str, privKeys[0], signature);
        for (int j = 1; j < N; j++) {
            objects[j] = new SignedObject(objects[j - 1], privKeys[j], signature);
        }
        // Verify the chain
        int n = objects.length - 1;
        SignedObject object = objects[n];
        do {
            if (!object.verify(pubKeys[n], signature)) {
                System.out.println("Failed: verification failed, n = " + n);
                return false;
            }
            if (object.verify(anotherPubKeys[n], signature)) {
                System.out.println("Failed: verification should not " + "succeed with wrong public key, n = " + n);
                return false;
            }
            object = (SignedObject) object.getObject();
            n--;
        } while (n > 0);
        System.out.println("signed data: " + object.getObject());
        if (!str.equals(object.getObject())) {
            System.out.println("Failed: signed data is not equal to " + "original one");
            return false;
        }
        System.out.println("Test passed");
        return true;
    } catch (NoSuchProviderException nspe) {
        if (test.provider == Provider.SunMSCAPI && !System.getProperty("os.name").startsWith("Windows")) {
            System.out.println("SunMSCAPI is available only on Windows: " + nspe);
            return true;
        }
        System.out.println("Unexpected exception: " + nspe);
        return false;
    } catch (Exception e) {
        System.out.println("Unexpected exception: " + e);
        e.printStackTrace(System.out);
        return false;
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) Signature(java.security.Signature) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchProviderException(java.security.NoSuchProviderException) SignedObject(java.security.SignedObject) NoSuchProviderException(java.security.NoSuchProviderException)

Aggregations

KeyPair (java.security.KeyPair)903 KeyPairGenerator (java.security.KeyPairGenerator)345 Test (org.junit.Test)235 PrivateKey (java.security.PrivateKey)189 X509Certificate (java.security.cert.X509Certificate)185 PublicKey (java.security.PublicKey)167 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)127 IOException (java.io.IOException)121 BigInteger (java.math.BigInteger)87 Date (java.util.Date)78 SecureRandom (java.security.SecureRandom)75 KeyStore (java.security.KeyStore)74 GeneralSecurityException (java.security.GeneralSecurityException)63 RSAPublicKey (java.security.interfaces.RSAPublicKey)55 X500Principal (javax.security.auth.x500.X500Principal)53 File (java.io.File)52 KeyFactory (java.security.KeyFactory)52 ECPrivateKey (java.security.interfaces.ECPrivateKey)52 ECPublicKey (java.security.interfaces.ECPublicKey)52 InvalidKeyException (java.security.InvalidKeyException)40