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:acceptable_risk.nik.uniobuda.hu.andrawid.util.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key./*from   w w w  .j a  va2 s  .  c  o  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);
        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:net.nicholaswilliams.java.licensing.encryption.KeyFileUtilities.java

public static PrivateKey readEncryptedPrivateKey(byte[] fileContents, char[] passphrase) {
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
            Encryptor.decryptRaw(fileContents, passphrase));

    try {//from   w w w  .  ja  va  2s  .c om
        return KeyFactory.getInstance(KeyFileUtilities.keyAlgorithm).generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new AlgorithmNotSupportedException(KeyFileUtilities.keyAlgorithm, e);
    } catch (InvalidKeySpecException e) {
        throw new InappropriateKeySpecificationException(e);
    }
}

From source file:net.sf.zekr.common.util.CryptoUtils.java

public static byte[] sign(byte[] text, byte[] prvKeyBytes) throws GeneralSecurityException {
    PKCS8EncodedKeySpec prvSpec = new PKCS8EncodedKeySpec(prvKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PrivateKey prvKey = keyFactory.generatePrivate(prvSpec);
    Signature sig = Signature.getInstance("SHA1withDSA");
    sig.initSign(prvKey);//w  w  w  .j  av  a  2s  .com
    sig.update(text);
    return sig.sign();
}

From source file:com.nexmo.client.auth.JWTAuthMethodTest.java

@Test
public void testConstructToken() throws Exception {
    String constructedToken = auth.constructToken(1234, "1111111");

    byte[] keyBytes = testUtils.loadKey("test/keys/application_public_key.der");
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);

    final JWTVerifier verifier = new JWTVerifier(key);
    final Map<String, Object> claims = verifier.verify(constructedToken);

    assertEquals(1234, claims.get("iat"));
    assertEquals("1111111", claims.get("jti"));
    assertEquals("application-id", claims.get("application_id"));
}

From source file:net.networksaremadeofstring.cyllell.Authentication.java

private String SignHeaders(String dataToSign)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(this.PrivateKey.getBytes(), 0));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, pk);

    byte[] EncryptedStream = new byte[cipher.getOutputSize(dataToSign.length())];
    try {/*w  w w  .j  a  v  a 2 s . c  o  m*/
        cipher.doFinal(dataToSign.getBytes(), 0, dataToSign.length(), EncryptedStream, 0);
    } catch (ShortBufferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Base64.encodeToString(EncryptedStream, Base64.NO_WRAP);
}

From source file:architecture.common.license.LicenseSigner.java

protected void init(Reader keyReader) throws IOException, NoSuchAlgorithmException, DecoderException,
        InvalidKeySpecException, InvalidKeyException {
    BufferedReader in = new BufferedReader(keyReader);
    String privateKey = in.readLine();
    in.close();/*  w  w  w  .  j a  v  a2  s  .c o  m*/
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    sig = Signature.getInstance("SHA1withDSA");
    PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Hex.decodeHex(privateKey.toCharArray()));
    java.security.PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
    sig.initSign(privKey);
}

From source file:com.vimukti.accounter.developer.api.PublicKeyGenerator.java

private static void generate() throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeySpecException, KeyStoreException, CertificateException, IOException, URISyntaxException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed("VimTech".getBytes("UTF-8"));
    keyGen.initialize(1024, random);//w  ww . j a  v a  2 s . c  om

    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();
    System.out.println(priv);
    System.out.println(pub);

    byte[] encoded = pub.getEncoded();
    byte[] encodeBase64 = Base64.encodeBase64(encoded);
    System.out.println("Public Key:" + new String(encodeBase64));

    byte[] encodedPrv = priv.getEncoded();
    byte[] encodeBase64Prv = Base64.encodeBase64(encodedPrv);
    System.out.println("Private Key:" + new String(encodeBase64Prv));

    byte[] decodeBase64 = Base64.decodeBase64(encodeBase64);
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(decodeBase64);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");

    System.out.println(keyFactory.generatePublic(pubKeySpec).equals(pub));
}

From source file:org.kde.kdeconnect.Helpers.SecurityHelpers.RsaHelper.java

public static PublicKey getPublicKey(Context context, String deviceId) throws Exception {
    try {// w  ww.  j  ava  2s.  c o  m
        SharedPreferences settings = context.getSharedPreferences(deviceId, Context.MODE_PRIVATE);
        byte[] publicKeyBytes = Base64.decode(settings.getString("publicKey", ""), 0);
        PublicKey publicKey = KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        return publicKey;
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.github.woki.payments.adyen.action.CSEUtil.java

public static Cipher rsaCipher(final String cseKeyText) throws NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidKeyException, InvalidKeySpecException, IllegalArgumentException {
    String[] cseKeyParts = cseKeyText.split("\\|");
    if (cseKeyParts.length != 2) {
        throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText);
    }//  w  ww.  j  av  a 2s  .  com
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    BigInteger keyComponent1, keyComponent2;
    try {
        keyComponent1 = new BigInteger(cseKeyParts[1].toLowerCase(Locale.getDefault()), 16);
        keyComponent2 = new BigInteger(cseKeyParts[0].toLowerCase(Locale.getDefault()), 16);
    } catch (NumberFormatException e) {
        throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText);
    }
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(keyComponent1, keyComponent2);
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Cipher result = Cipher.getInstance("RSA/None/PKCS1Padding");
    result.init(Cipher.ENCRYPT_MODE, pubKey);
    return result;
}

From source file:be.fedict.eid.idp.model.CryptoUtil.java

public static PrivateKey getPrivate(byte[] keyBytes) throws KeyLoadException {

    // try DSA//  w w w  . j a v a 2s. c  o  m
    try {
        KeyFactory dsaKeyFactory = KeyFactory.getInstance("DSA");
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        try {
            return dsaKeyFactory.generatePrivate(privateKeySpec);
        } catch (InvalidKeySpecException e) {
            // try RSA
            KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");
            try {
                return rsaKeyFactory.generatePrivate(privateKeySpec);
            } catch (InvalidKeySpecException e1) {
                throw new KeyLoadException(e);
            }

        }
    } catch (NoSuchAlgorithmException e) {
        throw new KeyLoadException(e);
    }
}