Search in sources :

Example 96 with KeyPair

use of java.security.KeyPair 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 97 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 98 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 99 with KeyPair

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

the class GenerationTests method test_create_detached_signature.

static boolean test_create_detached_signature(String canonicalizationMethod, String signatureMethod, String digestMethod, String transform, KeyInfoType keyInfo, Content contentType, int port) throws Exception {
    System.out.print("Sign ...");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    // Create SignedInfo
    DigestMethod dm = fac.newDigestMethod(digestMethod, null);
    List transformList = null;
    if (transform != null) {
        TransformParameterSpec params = null;
        switch(transform) {
            case Transform.XPATH:
                params = new XPathFilterParameterSpec("//.");
                break;
            case Transform.XPATH2:
                params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("//.", XPathType.Filter.INTERSECT)));
                break;
            case Transform.XSLT:
                Element element = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xslt.getBytes())).getDocumentElement();
                DOMStructure stylesheet = new DOMStructure(element);
                params = new XSLTTransformParameterSpec(stylesheet);
                break;
        }
        transformList = Collections.singletonList(fac.newTransform(transform, params));
    }
    String url = String.format("http://localhost:%d/%s", port, contentType);
    List refs = Collections.singletonList(fac.newReference(url, dm, transformList, null, null));
    CanonicalizationMethod cm = fac.newCanonicalizationMethod(canonicalizationMethod, (C14NMethodParameterSpec) null);
    SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
    Key signingKey;
    Key validationKey;
    switch(signatureMethod) {
        case SignatureMethod.DSA_SHA1:
        case SignatureMethod.RSA_SHA1:
            KeyPair kp = generateKeyPair(sm);
            validationKey = kp.getPublic();
            signingKey = kp.getPrivate();
            break;
        case SignatureMethod.HMAC_SHA1:
            KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
            signingKey = kg.generateKey();
            validationKey = signingKey;
            break;
        default:
            throw new RuntimeException("Unsupported signature algorithm");
    }
    SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
    // Create KeyInfo
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List list = null;
    if (keyInfo == KeyInfoType.KeyValue) {
        if (validationKey instanceof PublicKey) {
            KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
            list = Collections.singletonList(kv);
        }
    } else if (keyInfo == KeyInfoType.x509data) {
        list = Collections.singletonList(kif.newX509Data(Collections.singletonList("cn=Test")));
    } else if (keyInfo == KeyInfoType.KeyName) {
        list = Collections.singletonList(kif.newKeyName("Test"));
    } else {
        throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
    }
    KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
    // Create an empty doc for detached signature
    Document doc = dbf.newDocumentBuilder().newDocument();
    DOMSignContext xsc = new DOMSignContext(signingKey, doc);
    // Generate signature
    XMLSignature signature = fac.newXMLSignature(si, ki);
    signature.sign(xsc);
    // Save signature
    String signatureString;
    try (StringWriter writer = new StringWriter()) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        Node parent = xsc.getParent();
        trans.transform(new DOMSource(parent), new StreamResult(writer));
        signatureString = writer.toString();
    }
    System.out.print("Validate ... ");
    try (ByteArrayInputStream bis = new ByteArrayInputStream(signatureString.getBytes())) {
        doc = dbf.newDocumentBuilder().parse(bis);
    }
    NodeList nodeLst = doc.getElementsByTagName("Signature");
    Node node = nodeLst.item(0);
    if (node == null) {
        throw new RuntimeException("Couldn't find Signature element");
    }
    if (!(node instanceof Element)) {
        throw new RuntimeException("Unexpected node type");
    }
    Element sig = (Element) node;
    // Validate signature
    DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
    signature = fac.unmarshalXMLSignature(vc);
    boolean success = signature.validate(vc);
    if (!success) {
        System.out.println("Core signature validation failed");
        return false;
    }
    success = signature.getSignatureValue().validate(vc);
    if (!success) {
        System.out.println("Cryptographic validation of signature failed");
        return false;
    }
    return true;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) KeyGenerator(javax.crypto.KeyGenerator) KeyPair(java.security.KeyPair) StreamResult(javax.xml.transform.stream.StreamResult) PublicKey(java.security.PublicKey) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Example 100 with KeyPair

use of java.security.KeyPair in project android_frameworks_base by AOSPA.

the class AndroidKeyStoreKeyPairGeneratorSpi method generateKeyPair.

@Override
public KeyPair generateKeyPair() {
    if (mKeyStore == null || mSpec == null) {
        throw new IllegalStateException("Not initialized");
    }
    final int flags = (mEncryptionAtRestRequired) ? KeyStore.FLAG_ENCRYPTED : 0;
    if (((flags & KeyStore.FLAG_ENCRYPTED) != 0) && (mKeyStore.state() != KeyStore.State.UNLOCKED)) {
        throw new IllegalStateException("Encryption at rest using secure lock screen credential requested for key pair" + ", but the user has not yet entered the credential");
    }
    byte[] additionalEntropy = KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng(mRng, (mKeySizeBits + 7) / 8);
    Credentials.deleteAllTypesForAlias(mKeyStore, mEntryAlias, mEntryUid);
    final String privateKeyAlias = Credentials.USER_PRIVATE_KEY + mEntryAlias;
    boolean success = false;
    try {
        generateKeystoreKeyPair(privateKeyAlias, constructKeyGenerationArguments(), additionalEntropy, flags);
        KeyPair keyPair = loadKeystoreKeyPair(privateKeyAlias);
        storeCertificateChain(flags, createCertificateChain(privateKeyAlias, keyPair));
        success = true;
        return keyPair;
    } finally {
        if (!success) {
            Credentials.deleteAllTypesForAlias(mKeyStore, mEntryAlias, mEntryUid);
        }
    }
}
Also used : KeyPair(java.security.KeyPair) DERBitString(com.android.org.bouncycastle.asn1.DERBitString)

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