Example usage for java.security KeyFactory getInstance

List of usage examples for java.security KeyFactory getInstance

Introduction

In this page you can find the example usage for java.security KeyFactory getInstance.

Prototype

public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyFactory object that converts public/private keys of the specified algorithm.

Usage

From source file:com.amarinfingroup.net.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this uri.
 *
 * @param mUri either an instance URI (if previously saved) or a form URI
 * @param instanceMetadata//from  ww w .jav  a 2  s. c o  m
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri,
        InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
        if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
            // chain back to the Form record...
            String[] selectionArgs = null;
            String selection = null;
            Cursor instanceCursor = null;
            try {
                instanceCursor = cr.query(mUri, null, null, null, null);
                if (instanceCursor.getCount() != 1) {
                    Log.e(t, "Not exactly one record for this instance!");
                    return null; // save unencrypted.
                }
                instanceCursor.moveToFirst();
                String jrFormId = instanceCursor
                        .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
                if (!instanceCursor.isNull(idxJrVersion)) {
                    selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
                } else {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
                }
            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form matches this jr_form_id");
                return null; // save unencrypted
            }
            formCursor.moveToFirst();
        } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
            formCursor = cr.query(mUri, null, null, null, null);
            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form!");
                return null; // save unencrypted.
            }
            formCursor.moveToFirst();
        }

        formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
        if (formId == null || formId.length() == 0) {
            Log.e(t, "No FormId specified???");
            return null;
        }
        int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
        int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
        formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
        String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null
                : formCursor.getString(idxBase64RsaPublicKey);

        if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
            return null; // this is legitimately not an encrypted form
        }

        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 8) {
            Log.e(t, "Phone does not support encryption.");
            return null; // save unencrypted
        }

        // this constructor will throw an exception if we are not
        // running on version 8 or above (if Base64 is not found).
        try {
            wrapper = new Base64Wrapper();
        } catch (ClassNotFoundException e) {
            Log.e(t, "Phone does not have Base64 class but API level is " + version);
            e.printStackTrace();
            return null; // save unencrypted
        }

        // OK -- Base64 decode (requires API Version 8 or higher)
        byte[] publicKey = wrapper.decode(base64RsaPublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            Log.e(t, "Phone does not support RSA encryption.");
            e.printStackTrace();
            return null;
        }
        try {
            pk = kf.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.e(t, "Invalid RSA public key.");
            return null;
        }
    } finally {
        if (formCursor != null) {
            formCursor.close();
        }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
        Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
        Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
        return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
}

From source file:com.charabia.SmsViewActivity.java

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
    case SMS_KEY_CONTACT:
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();//from   w  ww . j ava 2s  .  co  m

            ContentResolver cr = getContentResolver();

            Cursor cursor = cr.query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null);

            String lookup = null;

            if (cursor.moveToFirst()) {
                lookup = cursor.getString(0);
            }

            cursor.close();

            if (lookup == null) {
                Toast.makeText(this, R.string.unexpected_error, Toast.LENGTH_LONG).show();
                return;
            }

            cursor = cr.query(Data.CONTENT_URI, new String[] { Phone.NUMBER },
                    Data.MIMETYPE + "=? AND " + Data.LOOKUP_KEY + "=?",
                    new String[] { Phone.CONTENT_ITEM_TYPE, lookup }, null);

            ArrayList<String> options = new ArrayList<String>();

            while (cursor.moveToNext()) {
                options.add(cursor.getString(0));
            }

            cursor.close();

            final String[] phoneList = options.toArray(new String[0]);

            Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.send_invit_on_phone);
            builder.setItems(phoneList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {

                    keypair = tools.loadKeyPair();
                    RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic();

                    byte[] encoded = pubKey.getModulus().toByteArray();

                    byte[] data = new byte[3 + encoded.length];

                    data[0] = Tools.MAGIC[0];
                    data[1] = Tools.MAGIC[1];
                    data[2] = Tools.PUBLIC_KEY_TYPE;

                    System.arraycopy(encoded, 0, data, 3, encoded.length);

                    tools.sendData(phoneList[i], Tools.INVITATION, "", data);

                }
            });

            builder.create().show();
        } else {
            Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
        }
        break;
    case IntentIntegrator.REQUEST_CODE:
        if (resultCode == RESULT_OK) {
            try {
                String contents = data.getStringExtra("SCAN_RESULT");
                @SuppressWarnings("unused")
                String format = data.getStringExtra("SCAN_RESULT_FORMAT");
                // Handle successful scan

                // TODO: add more tests control

                String[] infos = contents.split("\n");

                Cipher rsaCipher = Cipher.getInstance(Tools.RSA_CIPHER_ALGO);

                if (mode == MODE_ESCLAVE) {
                    // Save key and show crypted key on QRCode
                    key = tools.generateKeyAES().getEncoded();

                    KeyFactory keyFact = KeyFactory.getInstance("RSA");

                    PublicKey pubkey = keyFact.generatePublic(
                            new RSAPublicKeySpec(new BigInteger(infos[1]), new BigInteger(infos[2])));

                    rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey);

                    int blockSize = rsaCipher.getBlockSize();

                    int nbBlock = key.length / blockSize;
                    int reste = key.length % blockSize;

                    byte[] cryptedKey = new byte[(nbBlock + 1) * rsaCipher.getOutputSize(blockSize)];

                    int offset = 0;

                    for (int i = 0; i < nbBlock; i++) {
                        offset += rsaCipher.doFinal(key, i * blockSize, blockSize, cryptedKey, offset);
                    }

                    rsaCipher.doFinal(key, nbBlock * blockSize, reste, cryptedKey, offset);

                    IntentIntegrator.shareText(SmsViewActivity.this,
                            prefPhoneNumber + "\n" + Base64.encodeToString(cryptedKey, Base64.NO_WRAP));

                } else {

                    // We have read crypted key, so decode it
                    rsaCipher.init(Cipher.DECRYPT_MODE, keypair.getPrivate());

                    byte[] cryptedData = Base64.decode(infos[1], Base64.NO_WRAP);

                    int blockSize = rsaCipher.getBlockSize();
                    int nbBlock = cryptedData.length / blockSize;

                    int offset = 0;

                    byte[] tempKey = new byte[(nbBlock + 1) * blockSize];

                    for (int i = 0; i < nbBlock; i++) {
                        offset += rsaCipher.doFinal(cryptedData, i * blockSize, blockSize, tempKey, offset);
                    }

                    key = new byte[offset];
                    System.arraycopy(tempKey, 0, key, 0, offset);
                }

                phoneNumber = infos[0];

                // store the key
                // TODO dialog to confirm add contact in mode SLAVE
                try {
                    new Tools(this).updateOrCreateContactKey(phoneNumber, key);
                } catch (NoContactException e) {
                    e.printStackTrace();
                    // propose to add contact
                    Intent newIntent = new Intent(Intents.SHOW_OR_CREATE_CONTACT);
                    newIntent.setData(Uri.fromParts("tel", phoneNumber, null));
                    startActivityForResult(newIntent, ADD_CONTACT);
                    return;
                }

                Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG)
                        .show();

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
            }

        } else {
            // TODO: string
            Toast.makeText(this, R.string.fail_reading_tag, Toast.LENGTH_LONG).show();
        }
        break;
    case ADD_CONTACT:
        try {
            tools.updateOrCreateContactKey(phoneNumber, key);
            Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG)
                    .show();
        } catch (NoContactException e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
        }
        break;
    }

}

From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this uri.
 *
 * @param mUri either an instance URI (if previously saved) or a form URI
 * @param instanceMetadata//from w w  w .  j a  va 2  s.co  m
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri,
        FormController.InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
        if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
            // chain back to the Form record...
            String[] selectionArgs = null;
            String selection = null;
            Cursor instanceCursor = null;
            try {
                instanceCursor = cr.query(mUri, null, null, null, null);
                if (instanceCursor.getCount() != 1) {
                    Log.e(t, "Not exactly one record for this instance!");
                    return null; // save unencrypted.
                }
                instanceCursor.moveToFirst();
                String jrFormId = instanceCursor
                        .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
                if (!instanceCursor.isNull(idxJrVersion)) {
                    selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
                } else {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
                }
            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form matches this jr_form_id");
                return null; // save unencrypted
            }
            formCursor.moveToFirst();
        } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
            formCursor = cr.query(mUri, null, null, null, null);
            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form!");
                return null; // save unencrypted.
            }
            formCursor.moveToFirst();
        }

        formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
        if (formId == null || formId.length() == 0) {
            Log.e(t, "No FormId specified???");
            return null;
        }
        int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
        int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
        formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
        String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null
                : formCursor.getString(idxBase64RsaPublicKey);

        if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
            return null; // this is legitimately not an encrypted form
        }

        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 8) {
            Log.e(t, "Phone does not support encryption.");
            return null; // save unencrypted
        }

        // this constructor will throw an exception if we are not
        // running on version 8 or above (if Base64 is not found).
        try {
            wrapper = new Base64Wrapper();
        } catch (ClassNotFoundException e) {
            Log.e(t, "Phone does not have Base64 class but API level is " + version);
            e.printStackTrace();
            return null; // save unencrypted
        }

        // OK -- Base64 decode (requires API Version 8 or higher)
        byte[] publicKey = wrapper.decode(base64RsaPublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            Log.e(t, "Phone does not support RSA encryption.");
            e.printStackTrace();
            return null;
        }
        try {
            pk = kf.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.e(t, "Invalid RSA public key.");
            return null;
        }
    } finally {
        if (formCursor != null) {
            formCursor.close();
        }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
        Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
        Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
        return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
}

From source file:org.thoughtland.xlocation.Util.java

private static PublicKey getPublicKey(Context context) throws Throwable {
    // Read public key
    String sPublicKey = "";
    InputStreamReader isr = new InputStreamReader(context.getAssets().open("XLocation_public_key.txt"),
            "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();/* w w w.j a va  2s. c  o m*/
    while (line != null) {
        if (!line.startsWith("-----"))
            sPublicKey += line;
        line = br.readLine();
    }
    br.close();
    isr.close();

    // Create public key
    byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey);
    return keyFactory.generatePublic(encodedPubKeySpec);
}

From source file:com.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java

private String decryptRSAToString(String encryptedBase64, String privateKey) {
    String decryptedString = "";
    try {/*  w  w  w .j av a  2 s  .c  o m*/
        String rStart = privateKey.replace("-----BEGIN PUBLIC KEY-----", "");
        String rEnd = rStart.replace("-----END PUBLIC KEY-----", "");
        rEnd = rEnd.replaceAll("\r", "");
        rEnd = rEnd.replaceAll("\n", "");
        rEnd = rEnd.replaceAll("\t", "");
        rEnd = rEnd.replaceAll(" ", "");
        KeyFactory keyFac = KeyFactory.getInstance("RSA");

        PublicKey publicKey = keyFac
                .generatePublic(new X509EncodedKeySpec(Base64.decode(rEnd.toString(), Base64.DEFAULT)));

        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        // encrypt the plain text using the public key
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        byte[] encryptedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        decryptedString = new String(decryptedBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return decryptedString;
}

From source file:org.kde.kdeconnect.Device.java

public void addLink(NetworkPackage identityPackage, BaseLink link) {
    //FilesHelper.LogOpenFileCount();

    this.protocolVersion = identityPackage.getInt("protocolVersion");

    if (identityPackage.has("deviceName")) {
        this.name = identityPackage.getString("deviceName", this.name);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("deviceName", this.name);
        editor.apply();/*from  ww  w  .j  a v a 2s.co  m*/
    }

    if (identityPackage.has("deviceType")) {
        this.deviceType = DeviceType.FromString(identityPackage.getString("deviceType", "desktop"));
    }

    if (identityPackage.has("certificate")) {
        String certificateString = identityPackage.getString("certificate");

        try {
            byte[] certificateBytes = Base64.decode(certificateString, 0);
            certificate = SslHelper.parseCertificate(certificateBytes);
            Log.i("KDE/Device", "Got certificate ");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("KDE/Device", "Error getting certificate");

        }
    }

    links.add(link);

    try {
        SharedPreferences globalSettings = PreferenceManager.getDefaultSharedPreferences(context);
        byte[] privateKeyBytes = Base64.decode(globalSettings.getString("privateKey", ""), 0);
        PrivateKey privateKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        link.setPrivateKey(privateKey);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/Device", "Exception reading our own private key"); //Should not happen
    }

    Log.i("KDE/Device", "addLink " + link.getLinkProvider().getName() + " -> " + getName() + " active links: "
            + links.size());

    if (!pairingHandlers.containsKey(link.getName())) {
        BasePairingHandler.PairingHandlerCallback callback = new BasePairingHandler.PairingHandlerCallback() {
            @Override
            public void incomingRequest() {
                for (PairingCallback cb : pairingCallback) {
                    cb.incomingRequest();
                }
            }

            @Override
            public void pairingDone() {
                Device.this.pairingDone();
            }

            @Override
            public void pairingFailed(String error) {
                for (PairingCallback cb : pairingCallback) {
                    cb.pairingFailed(error);
                }
            }

            @Override
            public void unpaired() {
                unpairInternal();
            }
        };
        pairingHandlers.put(link.getName(), link.getPairingHandler(this, callback));
    }

    Set<String> outgoingCapabilities = identityPackage.getStringSet("outgoingCapabilities", null);
    Set<String> incomingCapabilities = identityPackage.getStringSet("incomingCapabilities", null);
    if (incomingCapabilities != null && outgoingCapabilities != null) {
        m_supportedPlugins = new Vector<>(
                PluginFactory.pluginsForCapabilities(context, incomingCapabilities, outgoingCapabilities));
    } else {
        m_supportedPlugins = new Vector<>(PluginFactory.getAvailablePlugins());
    }

    link.addPackageReceiver(this);

    reloadPluginsFromSettings();

}

From source file:com.axelor.apps.account.service.payment.PayboxService.java

/** Chargement de la cle AU FORMAT pem
 * Alors ajouter la dpendance dans le fichier pom.xml :
 * <dependency>//  w ww . ja  v a 2 s .  co m
*     <groupId>org.bouncycastle</groupId>
*     <artifactId>bcprov-jdk15on</artifactId>
*     <version>1.47</version>
*   </dependency>
*
* Ainsi que l'import : import org.bouncycastle.util.io.pem.PemReader;
 *
 * @param pubKeyFile
 * @return
 * @throws Exception
 */
private PublicKey getPubKey(String pubKeyPath) throws Exception {

    PemReader reader = new PemReader(new FileReader(pubKeyPath));

    byte[] pubKey = reader.readPemObject().getContent();

    reader.close();

    KeyFactory keyFactory = KeyFactory.getInstance(this.ENCRYPTION_ALGORITHM);

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKey);

    return keyFactory.generatePublic(pubKeySpec);

}

From source file:jp.app_mart.billing.AppmartHelper.java

/**
 * ?/*from ww w  .ja v a2s  .co  m*/
 * @param serviceId
 * @param developId
 * @param strLicenseKey
 * @param strPublicKey
 * @return
 */
public static String createEncryptedData(String serviceId, String developId, String strLicenseKey,
        String strPublicKey) {
    final String SEP_SYMBOL = "&";
    StringBuilder infoDataSB = new StringBuilder();
    infoDataSB.append(serviceId).append(SEP_SYMBOL);
    // ?ID 
    infoDataSB.append(developId).append(SEP_SYMBOL);
    // 
    infoDataSB.append(strLicenseKey);
    String strEncryInfoData = "";
    try {
        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(strPublicKey.getBytes(), Base64.DEFAULT));
        Key publicKey = keyFac.generatePublic(keySpec);
        if (publicKey != null) {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] EncryInfoData = cipher.doFinal(infoDataSB.toString().getBytes());
            strEncryInfoData = new String(Base64.encode(EncryInfoData, Base64.DEFAULT));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        strEncryInfoData = "";
        Log.e("AppmartHelper", "?");
    }
    return strEncryInfoData.replaceAll("(\\r|\\n)", "");
}

From source file:net.padlocksoftware.padlock.validator.Validator.java

private PublicKey convertPublicKey(String publicKey, boolean isRSA) {
    PublicKey pub = null;/* w w  w.jav  a  2 s . c o m*/
    try {
        byte[] pubKey = Hex.decodeHex(publicKey.toCharArray());
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKey);
        KeyFactory keyFactory = KeyFactory.getInstance(isRSA ? "RSA" : "DSA");
        if (isRSA) {
            pub = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
        } else {
            pub = (DSAPublicKey) keyFactory.generatePublic(pubSpec);
        }
    } catch (InvalidKeySpecException ex) {
        logger.log(Level.FINE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        logger.log(Level.FINE, null, ex);
    } catch (DecoderException ex) {
        logger.log(Level.FINE, null, ex);
    } catch (ClassCastException ex) {
        logger.log(Level.FINE, null, ex);
    }

    return pub;
}

From source file:org.jets3t.service.security.EncryptionUtil.java

/**
 * Generate an RSA SHA1 signature of the given data using the given private
 * key DER certificate./*from   www  . ja v  a 2 s. c  o  m*/
 *
 * Based on example code from:
 * http://www.java2s.com/Tutorial/Java/0490__Security/RSASignatureGeneration.htm
 * http://forums.sun.com/thread.jspa?threadID=5175986
 *
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws InvalidKeySpecException
 * @throws NoSuchProviderException
 */
public static byte[] signWithRsaSha1(byte[] derPrivateKeyBytes, byte[] dataToSign)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException,
        NoSuchProviderException {
    // Build an RSA private key from private key data
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(derPrivateKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);

    // Sign data
    Signature signature = Signature.getInstance("SHA1withRSA", "BC");
    signature.initSign(privateKey, new SecureRandom());
    signature.update(dataToSign);

    byte[] signatureBytes = signature.sign();
    return signatureBytes;
}