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:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

/**
 * Load an unencrypted PKCS #8 private key from the stream. The encoding of
 * the private key may be PEM or DER.//  w  w  w .  ja v  a  2 s . c o m
 *
 * @param is
 *            Stream to load the unencrypted private key from
 * @return The private key
 * @throws PrivateKeyEncryptedException
 *             If private key is encrypted
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);

    // Check pkcs #8 is unencrypted
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));

    if (encType == null) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }

    if (encType == ENCRYPTED) {
        throw new PrivateKeyEncryptedException(res.getString("Pkcs8IsEncrypted.exception.message"));
    }

    byte[] pvkBytes = null;
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));

    if (pemInfo != null) {
        // It is - get DER from PEM
        pvkBytes = pemInfo.getContent();
    }

    /*
     * If we haven't got the key bytes via PEM then just use stream
     * contents directly (assume it is DER encoded)
     */
    if (pvkBytes == null) {
        // Read in private key bytes
        pvkBytes = streamContents;
    }

    try {
        // Determine private key algorithm from key bytes
        String privateKeyAlgorithm = getPrivateKeyAlgorithm(pvkBytes);

        // Convert bytes to private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pvkBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(privateKeyAlgorithm);
        PrivateKey pvk = keyFactory.generatePrivate(privateKeySpec);

        return pvk;
    } catch (NoSuchAlgorithmException ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    } catch (InvalidKeySpecException ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    }
}

From source file:org.eclipse.leshan.server.demo.LeshanServerDemo.java

public static void createAndStartServer(int webPort, String localAddress, int localPort,
        String secureLocalAddress, int secureLocalPort, String redisUrl) throws Exception {
    // Prepare LWM2M server
    LeshanServerBuilder builder = new LeshanServerBuilder();
    builder.setLocalAddress(localAddress, localPort);
    builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
    builder.setEncoder(new DefaultLwM2mNodeEncoder());
    LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder();
    builder.setDecoder(decoder);/*from  w ww .  j av  a  2  s  .c  o  m*/

    // connect to redis if needed
    Pool<Jedis> jedis = null;
    if (redisUrl != null) {
        // TODO: support sentinel pool and make pool configurable
        jedis = new JedisPool(new URI(redisUrl));
    }

    // Get public and private server key
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    try {
        // Get point values
        byte[] publicX = Hex
                .decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray());
        byte[] publicY = Hex
                .decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray());
        byte[] privateS = Hex
                .decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray());

        // Get Elliptic Curve Parameter spec for secp256r1
        AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
        algoParameters.init(new ECGenParameterSpec("secp256r1"));
        ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

        // Create key specs
        KeySpec publicKeySpec = new ECPublicKeySpec(
                new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), parameterSpec);
        KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);

        // Get keys
        publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
        privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
        builder.setPublicKey(publicKey);
        builder.setPrivateKey(privateKey);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) {
        LOG.error("Unable to initialize RPK.", e);
        System.exit(-1);
    }

    // Define model provider
    LwM2mModelProvider modelProvider = new StandardModelProvider();
    builder.setObjectModelProvider(modelProvider);

    // Set securityStore & registrationStore
    EditableSecurityStore securityStore;
    if (jedis == null) {
        // use file persistence
        securityStore = new FileSecurityStore();
    } else {
        // use Redis Store
        securityStore = new RedisSecurityStore(jedis);
        builder.setRegistrationStore(new RedisRegistrationStore(jedis));
    }
    builder.setSecurityStore(securityStore);

    // Create and start LWM2M server
    LeshanServer lwServer = builder.build();

    // Now prepare Jetty
    Server server = new Server(webPort);
    WebAppContext root = new WebAppContext();
    root.setContextPath("/");
    root.setResourceBase(LeshanServerDemo.class.getClassLoader().getResource("webapp").toExternalForm());
    root.setParentLoaderPriority(true);
    server.setHandler(root);

    // Create Servlet
    EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecureAddress().getPort());
    ServletHolder eventServletHolder = new ServletHolder(eventServlet);
    root.addServlet(eventServletHolder, "/event/*");

    ServletHolder clientServletHolder = new ServletHolder(
            new ClientServlet(lwServer, lwServer.getSecureAddress().getPort()));
    root.addServlet(clientServletHolder, "/api/clients/*");

    ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(securityStore, publicKey));
    root.addServlet(securityServletHolder, "/api/security/*");

    ServletHolder objectSpecServletHolder = new ServletHolder(
            new ObjectSpecServlet(lwServer.getModelProvider()));
    root.addServlet(objectSpecServletHolder, "/api/objectspecs/*");

    // Start Jetty & Leshan
    lwServer.start();
    server.start();
    LOG.info("Web server started at {}.", server.getURI());
}

From source file:com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.util.PublicKeyReaderUtil.java

/**
 * <p>Decodes a DSA public key according to the SSH standard from the
 * data <code>_buffer</code> based on <b>NIST's FIPS-186</b>. The values of
 * the DSA public key specification are read in the order
 * <ul>/* w w  w .  ja va2 s  . com*/
 * <li>prime p</li>
 * <li>sub-prime q</li>
 * <li>base g</li>
 * <li>public key y</li>
 * </ul>
 * With the specification the related DSA public key is generated.</p>
 *
 * @param _buffer   SSH2 data buffer where the type of the key is already
 *                  read
 * @return DSA public key instance
 * @throws PublicKeyParseException if the SSH2 public key blob could not be
 *                                 decoded
 * @see DSAPublicKeySpec
 * @see <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm">Digital Signature Algorithm  on Wikipedia</a>
 * @see <a href="http://tools.ietf.org/html/rfc4253#section-6.6">RFC 4253 Section 6.6</a>
 */
private static PublicKey decodeDSAPublicKey(final SSH2DataBuffer _buffer) throws PublicKeyParseException {
    final BigInteger p = _buffer.readMPint();
    final BigInteger q = _buffer.readMPint();
    final BigInteger g = _buffer.readMPint();
    final BigInteger y = _buffer.readMPint();

    try {
        final KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA");
        final DSAPublicKeySpec dsaPubSpec = new DSAPublicKeySpec(y, p, q, g);

        return dsaKeyFact.generatePublic(dsaPubSpec);

    } catch (final Exception e) {
        throw new PublicKeyParseException(
                PublicKeyParseException.ErrorCode.SSH2DSA_ERROR_DECODING_PUBLIC_KEY_BLOB, e);
    }
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

static PublicKey loadPublicKey(String file, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(file);
    FileInputStream fis = new FileInputStream(file);
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);//from   w  w w.ja va  2  s. co m
    fis.close();

    // Generate Public Key.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    return publicKey;
}

From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java

public static PublicKey getPublicOscarKey(String publicOscarKeyString)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicOscarKeyString));
    KeyFactory pubKeyFactory = KeyFactory.getInstance("RSA");
    PublicKey publicOscarKey = pubKeyFactory.generatePublic(pubKeySpec);
    return publicOscarKey;
}

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>/*from  w w w  . j ava2s .  c  o  m*/
 * ?
 * </p>
 * 
 * @param data ??
 * @param privateKey ?(BASE64?)
 * @return byte
 * @throws Exception Exception
 */
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateK);
    int inputLen = data.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int index = 0;
    // ?
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
            cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(data, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        index++;
        offSet = index * MAX_ENCRYPT_BLOCK;
    }
    byte[] encryptedData = out.toByteArray();
    out.close();
    return encryptedData;
}

From source file:org.cprados.wificellmanager.billing.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key./* w  w w  .j av a  2 s.  co  m*/
 *
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey) {
    try {
        //byte[] decodedKey = Base64.decode(encodedPublicKey);
        byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
        return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        Log.e(TAG, "Invalid key specification.");
        throw new IllegalArgumentException(e);
    } // catch (Base64DecoderException e) {
      //    Log.e(TAG, "Base64 decoding failed.");
      //    throw new IllegalArgumentException(e);
      //}
}

From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java

/**
 * Gets the private key from bytes./*from w  ww  .  j  a  va  2  s  .  com*/
 *
 * @param keyBytes the key bytes
 * @return the private
 * @throws InvalidKeyException invalid key exception
 */
public static PrivateKey getPrivate(byte[] keyBytes) throws InvalidKeyException {
    try {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        return kf.generatePrivate(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        throw new InvalidKeyException(ex);
    }
}

From source file:com.guillaumesoft.escapehellprison.PurchaseActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mOuyaFacade = OuyaFacade.getInstance();
    Bundle developerInfo = new Bundle();
    developerInfo.putString(OuyaFacade.OUYA_DEVELOPER_ID, DEVELOPER_ID);
    developerInfo.putByteArray(OuyaFacade.OUYA_DEVELOPER_PUBLIC_KEY, loadApplicationKey());
    mOuyaFacade = OuyaFacade.getInstance();
    mOuyaFacade.init(this, developerInfo);

    // Uncomment this line to test against the server using "fake" credits.
    // This will also switch over to a separate "test" purchase history.
    //ouyaFacade.setTestMode();

    setContentView(R.layout.sample_app);

    receiptListView = (ListView) findViewById(R.id.receipts);
    receiptListView.setFocusable(false);

    /*//from ww  w . j  a va2  s .  co  m
     * In order to avoid "application not responding" popups, Android demands that long-running operations
     * happen on a background thread. Listener objects provide a way for you to specify what ought to happen
     * at the end of the long-running operation. Examples of this pattern in Android include
     * android.os.AsyncTask.
     */
    findViewById(R.id.gamer_uuid_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fetchGamerInfo();
        }
    });

    // Attempt to restore the product and receipt list from the savedInstanceState Bundle
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(PRODUCTS_INSTANCE_STATE_KEY)) {
            Parcelable[] products = savedInstanceState.getParcelableArray(PRODUCTS_INSTANCE_STATE_KEY);
            mProductList = new ArrayList<Product>(products.length);

            for (Parcelable product : products) {
                mProductList.add((Product) product);
            }
            addProducts();
        }

        if (savedInstanceState.containsKey(RECEIPTS_INSTANCE_STATE_KEY)) {
            Parcelable[] receipts = savedInstanceState.getParcelableArray(RECEIPTS_INSTANCE_STATE_KEY);
            mReceiptList = new ArrayList<Receipt>(receipts.length);

            for (Parcelable receipt : receipts) {
                mReceiptList.add((Receipt) receipt);
            }
            addReceipts();
        }
    }

    // Request the product list if it could not be restored from the savedInstanceState Bundle
    if (mProductList == null) {
        requestProducts();
    }

    // Make sure the receipt ListView starts empty if the receipt list could not be restored
    // from the savedInstanceState Bundle.
    if (mReceiptList == null) {
        receiptListView.setAdapter(new ReceiptAdapter(this, new Receipt[0]));
    }

    // Create a PublicKey object from the key data downloaded from the developer portal.
    try {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(loadApplicationKey());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        mPublicKey = keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to create encryption key", e);
    }
}