Example usage for java.security.spec RSAPublicKeySpec RSAPublicKeySpec

List of usage examples for java.security.spec RSAPublicKeySpec RSAPublicKeySpec

Introduction

In this page you can find the example usage for java.security.spec RSAPublicKeySpec RSAPublicKeySpec.

Prototype

public RSAPublicKeySpec(BigInteger modulus, BigInteger publicExponent) 

Source Link

Document

Creates a new RSAPublicKeySpec.

Usage

From source file:org.umit.icm.mobile.utils.RSACrypto.java

/**
 * Reads an RSA {@link PublicKey} from disk.
 *    /*from w w  w.ja  v  a  2 s  . co m*/
                             
@param  fileName  An object of the type {@link String}
 *                                  
        
@return  {@link PublicKey}
 * 
        
@see         SDCardReadWrite
 */
public static PublicKey readPublicKey(String fileName) throws IOException {

    File sdCard = Environment.getExternalStorageDirectory();
    File keyDir = new File(sdCard.getAbsolutePath() + Constants.KEYS_DIR);
    File file = new File(keyDir, fileName);
    InputStream inputStream = new FileInputStream(file.toString());
    ObjectInputStream objInputStream = new ObjectInputStream(new BufferedInputStream(inputStream));
    try {
        BigInteger modulus = (BigInteger) objInputStream.readObject();
        BigInteger exponential = (BigInteger) objInputStream.readObject();
        RSAPublicKeySpec rsaKeySpec = new RSAPublicKeySpec(modulus, exponential);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(rsaKeySpec);
    } catch (Exception e) {
        throw new RuntimeException("readPublicKey exception", e);
    } finally {
        objInputStream.close();
    }

}

From source file:cn.quickj.AbstractApplication.java

private void decryptQuickjLicense(String hex) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    byte[] encrypted = Hex.decodeHex(hex.toCharArray());
    byte[] keydata = new byte[128];
    System.arraycopy(encrypted, 0, keydata, 0, 128);
    String key = new String(Hex.encodeHex(keydata));
    PublicKey pubKey = keyFactory
            .generatePublic(new RSAPublicKeySpec(new BigInteger(key, 16), new BigInteger("10001", 16)));
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, pubKey);
    byte[] decrypted = new byte[encrypted.length];
    int outputOffset = 0;
    for (int offset = 128; offset < encrypted.length;) {
        int inputLen = (encrypted.length - offset) > 128 ? 128 : (encrypted.length - offset);
        outputOffset += cipher.doFinal(encrypted, offset, inputLen, decrypted, outputOffset);
        offset += inputLen;/*from  w ww. ja v  a2  s  .  c  o  m*/
    }

    String licenseInfo = new String(decrypted, 0, outputOffset - 16, "utf8");
    String[] s = licenseInfo.split("\\|");
    hosts = s[1].split(",");
    endDate = new SimpleDateFormat("yyyy-MM-dd").parse(s[2]);
    byte[] md5 = new byte[16];
    System.arraycopy(decrypted, outputOffset - 16, md5, 0, 16);
    licensePath = new String(Hex.encodeHex(md5));
}

From source file:org.wso2.carbon.identity.sso.saml.builders.X509CredentialImpl.java

/**
 * The key is constructed form modulus and exponent.
 *
 * @param modulus// www. jav a2 s .c  om
 * @param publicExponent
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public X509CredentialImpl(BigInteger modulus, BigInteger publicExponent)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    publicKey = keyFactory.generatePublic(spec);
}

From source file:gov.niem.ws.util.SecurityUtil.java

public static PublicKey getPublicKeyFromKeyInfo(Node keyInfoNode)
        throws ParserConfigurationException, SAXException, IOException {
    PublicKey publicKey = null;//from  w  w  w . j ava  2 s  . com

    try {
        String modulusString = keyModulusPath.evaluate(keyInfoNode);
        String exponentString = keyExponentPath.evaluate(keyInfoNode);
        if (modulusString == null || exponentString == null) {
            return null;
        }
        byte[] modulusBytes = Base64.decodeBase64(modulusString);
        BigInteger modulus = new BigInteger(1, modulusBytes);
        byte[] exponentBytes = Base64.decodeBase64(exponentString);
        BigInteger exponent = new BigInteger(1, exponentBytes);
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent);
        publicKey = rsaKeyFactory.generatePublic(keySpec);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return publicKey;
}

From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java

private RSAPublicKey decodeRsaPublicKeyFromBitString(DERBitString der) throws SpkacException {
    try {//from   w w  w  . j  a v  a  2 s . c o m
        ASN1Sequence rsaPublicKey = ASN1Sequence.getInstance(der.getBytes());

        BigInteger modulus = ((ASN1Integer) rsaPublicKey.getObjectAt(0)).getValue();
        BigInteger publicExponent = ((ASN1Integer) rsaPublicKey.getObjectAt(1)).getValue();

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

        return (RSAPublicKey) keyFact.generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    } catch (GeneralSecurityException ex) {
        throw new SpkacException(res.getString("NoGenerateRsaPublicKeyFromSpkac.exception.message"), ex);
    } catch (Exception ex) {
        throw new SpkacException(res.getString("NoGenerateRsaPublicKeyFromSpkac.exception.message"), ex);
    }
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

public static PublicKey generatePublicKey(BigInteger modulus, BigInteger exponential)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPublicKeySpec rsaKeySpec = new RSAPublicKeySpec(modulus, exponential);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePublic(rsaKeySpec);
}

From source file:org.opensaml.xml.security.SecurityHelper.java

/**
 * Derives the public key from either a DSA or RSA private key.
 * /*from   w w w. ja  v  a  2s .c  o  m*/
 * @param key the private key to derive the public key from
 * 
 * @return the derived public key
 * 
 * @throws KeyException thrown if the given private key is not a DSA or RSA key or there is a problem generating the
 *             public key
 */
public static PublicKey derivePublicKey(PrivateKey key) throws KeyException {
    KeyFactory factory;
    if (key instanceof DSAPrivateKey) {
        DSAPrivateKey dsaKey = (DSAPrivateKey) key;
        DSAParams keyParams = dsaKey.getParams();
        BigInteger y = keyParams.getQ().modPow(dsaKey.getX(), keyParams.getP());
        DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, keyParams.getP(), keyParams.getQ(),
                keyParams.getG());

        try {
            factory = KeyFactory.getInstance("DSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from DSA private key", e);
        }
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());

        try {
            factory = KeyFactory.getInstance("RSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from RSA private key", e);
        }
    } else {
        throw new KeyException("Private key was not a DSA or RSA key");
    }
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureRS256(byte[] signingInput, byte[] sigBytes, RSAPublicKey rsaPublicKey)
        throws IllegalBlockSizeException, IOException, InvalidKeyException, NoSuchProviderException,
        InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException {
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
            rsaPublicKey.getPublicExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    byte[] decSig = cipher.doFinal(sigBytes);
    ASN1InputStream aIn = new ASN1InputStream(decSig);
    try {/*from  w w  w. ja  va 2 s  .com*/
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance("SHA-256", "BC");
        hash.update(signingInput);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}

From source file:strat.mining.stratum.proxy.Launcher.java

/**
 * Check that a valid SSl certificate already exists. If not, create a new
 * one./* ww w .  j  a  va 2 s  . c om*/
 * 
 * @throws Exception
 */
private static void checkCertificate() throws Exception {
    File storeFile = new File(ConfigurationManager.getInstance().getDatabaseDirectory(), KEYSTORE_FILE_NAME);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (!storeFile.exists()) {
        LOGGER.info("KeyStore does not exist. Create {}", storeFile.getAbsolutePath());
        storeFile.getParentFile().mkdirs();
        storeFile.createNewFile();
        keyStore.load(null, null);

        LOGGER.info("Generating new SSL certificate.");
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator();
        keyGenerator
                .init(new RSAKeyGenerationParameters(BigInteger.valueOf(101), new SecureRandom(), 2048, 14));
        AsymmetricCipherKeyPair keysPair = keyGenerator.generateKeyPair();

        RSAKeyParameters rsaPrivateKey = (RSAKeyParameters) keysPair.getPrivate();
        RSAPrivateKeySpec rsaPrivSpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
                rsaPrivateKey.getExponent());
        RSAKeyParameters rsaPublicKey = (RSAKeyParameters) keysPair.getPublic();
        RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
                rsaPublicKey.getExponent());
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey rsaPriv = kf.generatePrivate(rsaPrivSpec);
        PublicKey rsaPub = kf.generatePublic(rsaPublicSpec);

        X500Name issuerDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None");
        Integer randomNumber = new SecureRandom().nextInt();
        BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1);
        Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
        Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10));
        X500Name subjectDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None");
        byte[] publickeyb = rsaPub.getEncoded();
        ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb);
        SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence);
        X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore,
                notAfter, subjectDN, subPubKeyInfo);

        ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(keysPair.getPrivate());
        X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner);

        Certificate certificate = new CertificateFactory()
                .engineGenerateCertificate(new ByteBufferBackedInputStream(
                        ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded())));

        LOGGER.info("Certificate generated.");

        keyStore.setKeyEntry(KEYSTORE_KEY_ENTRY_ALIAS, rsaPriv, KEYSTORE_PASSWORD.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        keyStore.store(new FileOutputStream(storeFile), KEYSTORE_PASSWORD.toCharArray());
    }
}

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  a  v  a 2  s .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;
    }

}