Search in sources :

Example 71 with KeyPairGenerator

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

Example 72 with KeyPairGenerator

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

the class DeviceTest method testPairingDoneWithCertificate.

public void testPairingDoneWithCertificate() throws Exception {
    KeyPair keyPair = null;
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        keyPair = keyGen.genKeyPair();
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/initializeRsaKeys", "Exception");
    }
    X509Certificate certificate = null;
    try {
        BouncyCastleProvider BC = new BouncyCastleProvider();
        X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
        nameBuilder.addRDN(BCStyle.CN, "testDevice");
        nameBuilder.addRDN(BCStyle.OU, "KDE Connect");
        nameBuilder.addRDN(BCStyle.O, "KDE");
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + System.currentTimeMillis());
        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), BigInteger.ONE, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(keyPair.getPrivate());
        certificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateBuilder.build(contentSigner));
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/initialiseCert", "Exception");
    }
    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());
    fakeNetworkPackage.set("certificate", Base64.encodeToString(certificate.getEncoded(), 0));
    LanLinkProvider linkProvider = Mockito.mock(LanLinkProvider.class);
    Mockito.when(linkProvider.getName()).thenReturn("LanLinkProvider");
    LanLink link = Mockito.mock(LanLink.class);
    Mockito.when(link.getPairingHandler(Mockito.any(Device.class), Mockito.any(BasePairingHandler.PairingHandlerCallback.class))).thenReturn(Mockito.mock(LanPairingHandler.class));
    Mockito.when(link.getLinkProvider()).thenReturn(linkProvider);
    Device device = new Device(getContext(), fakeNetworkPackage, link);
    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);
    assertNotNull(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 : KeyPair(java.security.KeyPair) LanLink(org.kde.kdeconnect.Backends.LanBackend.LanLink) X500NameBuilder(org.spongycastle.asn1.x500.X500NameBuilder) SharedPreferences(android.content.SharedPreferences) JcaContentSignerBuilder(org.spongycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.spongycastle.operator.ContentSigner) KeyPairGenerator(java.security.KeyPairGenerator) Method(java.lang.reflect.Method) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) LanLinkProvider(org.kde.kdeconnect.Backends.LanBackend.LanLinkProvider) JcaX509v3CertificateBuilder(org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.spongycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.spongycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder) LanPairingHandler(org.kde.kdeconnect.Backends.LanBackend.LanPairingHandler) BouncyCastleProvider(org.spongycastle.jce.provider.BouncyCastleProvider)

Example 73 with KeyPairGenerator

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

use of java.security.KeyPairGenerator 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 75 with KeyPairGenerator

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

the class GenerationTests method generateKeyPair.

static KeyPair generateKeyPair(SignatureMethod sm) throws NoSuchAlgorithmException {
    KeyPairGenerator keygen;
    switch(sm.getAlgorithm()) {
        case SignatureMethod.DSA_SHA1:
            keygen = KeyPairGenerator.getInstance("DSA");
            break;
        case SignatureMethod.RSA_SHA1:
            keygen = KeyPairGenerator.getInstance("RSA");
            break;
        default:
            throw new RuntimeException("Unsupported signature algorithm");
    }
    SecureRandom random = new SecureRandom();
    keygen.initialize(1024, random);
    return keygen.generateKeyPair();
}
Also used : SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator)

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