Search in sources :

Example 91 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 92 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)

Example 93 with KeyPair

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

the class Copy method main.

public static void main(String[] args) throws Exception {
    KeyPairGenerator kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    KeyPair kp = kg.genKeyPair();
    Signature signature = Signature.getInstance(DSA);
    Test original = new Test();
    SignedObject so = new SignedObject(original, kp.getPrivate(), signature);
    System.out.println("Signature algorithm: " + so.getAlgorithm());
    signature = Signature.getInstance(DSA, "SUN");
    if (!so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Verification failed");
    }
    kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    kp = kg.genKeyPair();
    if (so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Unexpected success");
    }
    Object copy = so.getObject();
    if (!original.equals(copy)) {
        throw new RuntimeException("Signed object is not equal " + "to original one: " + copy);
    }
    /*
         * The signed object is a copy of an original one.
         * Once the copy is made, further manipulation
         * of the original object shouldn't has any effect on the copy.
         */
    original.set(MAGIC - 1);
    copy = so.getObject();
    if (original.equals(copy)) {
        throw new RuntimeException("Signed object is not a copy " + "of original one: " + copy);
    }
    System.out.println("Test passed");
}
Also used : KeyPair(java.security.KeyPair) Signature(java.security.Signature) SignedObject(java.security.SignedObject) KeyPairGenerator(java.security.KeyPairGenerator) SignedObject(java.security.SignedObject)

Example 94 with KeyPair

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

the class SignatureTest method main.

public static void main(String[] args) throws Exception {
    String testAlg = args[0];
    int testSize = Integer.parseInt(args[1]);
    byte[] data = new byte[100];
    RandomFactory.getRandom().nextBytes(data);
    // create a key pair
    KeyPair kpair = generateKeys(KEYALG, testSize);
    Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
    Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
    // For signature algorithm, create and verify a signature
    Arrays.stream(privs).forEach(priv -> Arrays.stream(pubs).forEach(pub -> {
        try {
            checkSignature(data, (PublicKey) pub, (PrivateKey) priv, testAlg);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException ex) {
            throw new RuntimeException(ex);
        }
    }));
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SignatureException(java.security.SignatureException) Signature(java.security.Signature) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory) Key(java.security.Key) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) PUBLIC_KEY(javax.crypto.Cipher.PUBLIC_KEY) RSAPublicKey(java.security.interfaces.RSAPublicKey) RandomFactory(jdk.testlibrary.RandomFactory) PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) InvalidKeyException(java.security.InvalidKeyException) PRIVATE_KEY(javax.crypto.Cipher.PRIVATE_KEY) NoSuchProviderException(java.security.NoSuchProviderException) KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) RSAPublicKey(java.security.interfaces.RSAPublicKey) PrivateKey(java.security.PrivateKey)

Example 95 with KeyPair

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

the class DeviceTest method testPairingDone.

// Testing pairing done using reflection since it is private
// Created an unpaired device inside this test
public void testPairingDone() {
    NetworkPackage fakeNetworkPackage = new NetworkPackage(NetworkPackage.PACKAGE_TYPE_IDENTITY);
    fakeNetworkPackage.set("deviceId", "unpairedTestDevice");
    fakeNetworkPackage.set("deviceName", "Unpaired Test Device");
    fakeNetworkPackage.set("protocolVersion", NetworkPackage.ProtocolVersion);
    fakeNetworkPackage.set("deviceType", Device.DeviceType.Phone.toString());
    LanLinkProvider linkProvider = Mockito.mock(LanLinkProvider.class);
    Mockito.when(linkProvider.getName()).thenReturn("LanLinkProvider");
    LanLink link = Mockito.mock(LanLink.class);
    Mockito.when(link.getLinkProvider()).thenReturn(linkProvider);
    Mockito.when(link.getPairingHandler(Mockito.any(Device.class), Mockito.any(BasePairingHandler.PairingHandlerCallback.class))).thenReturn(Mockito.mock(LanPairingHandler.class));
    Device device = new Device(getContext(), fakeNetworkPackage, link);
    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;
    }
    device.publicKey = keyPair.getPublic();
    assertNotNull(device);
    assertEquals(device.getDeviceId(), "unpairedTestDevice");
    assertEquals(device.getName(), "Unpaired Test Device");
    assertEquals(device.getDeviceType(), Device.DeviceType.Phone);
    assertNotNull(device.publicKey);
    assertNull(device.certificate);
    Method method;
    try {
        method = Device.class.getDeclaredMethod("pairingDone");
        method.setAccessible(true);
        method.invoke(device);
    } catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(device.isPaired(), true);
    SharedPreferences preferences = getContext().getSharedPreferences("trusted_devices", Context.MODE_PRIVATE);
    assertEquals(preferences.getBoolean(device.getDeviceId(), false), true);
    SharedPreferences settings = getContext().getSharedPreferences(device.getDeviceId(), Context.MODE_PRIVATE);
    assertEquals(settings.getString("deviceName", "Unknown device"), "Unpaired Test Device");
    assertEquals(settings.getString("deviceType", "tablet"), "phone");
    // Cleanup for unpaired test device
    preferences.edit().remove(device.getDeviceId()).apply();
    settings.edit().clear().apply();
}
Also used : LanLink(org.kde.kdeconnect.Backends.LanBackend.LanLink) KeyPair(java.security.KeyPair) SharedPreferences(android.content.SharedPreferences) KeyPairGenerator(java.security.KeyPairGenerator) Method(java.lang.reflect.Method) LanPairingHandler(org.kde.kdeconnect.Backends.LanBackend.LanPairingHandler) LanLinkProvider(org.kde.kdeconnect.Backends.LanBackend.LanLinkProvider)

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