Example usage for java.security KeyFactory generatePublic

List of usage examples for java.security KeyFactory generatePublic

Introduction

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

Prototype

public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a public key object from the provided key specification (key material).

Usage

From source file:org.red5.server.net.rtmp.RTMPHandshake.java

/**
 * Determines the validation scheme for given input.
 * //  w w  w . j  a v a  2s. com
 * @param otherPublicKeyBytes
 * @param agreement
 * @return shared secret bytes if client used a supported validation scheme
 */
protected static byte[] getSharedSecret(byte[] otherPublicKeyBytes, KeyAgreement agreement) {
    BigInteger otherPublicKeyInt = new BigInteger(1, otherPublicKeyBytes);
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("DH");
        KeySpec otherPublicKeySpec = new DHPublicKeySpec(otherPublicKeyInt, RTMPHandshake.DH_MODULUS,
                RTMPHandshake.DH_BASE);
        PublicKey otherPublicKey = keyFactory.generatePublic(otherPublicKeySpec);
        agreement.doPhase(otherPublicKey, true);
    } catch (Exception e) {
        log.error("Exception getting the shared secret", e);
    }
    byte[] sharedSecret = agreement.generateSecret();
    //log.debug("Shared secret [{}]: {}", sharedSecret.length, Hex.encodeHexString(sharedSecret));
    return sharedSecret;
}

From source file:com.centurylink.mdw.services.util.AuthUtils.java

private static synchronized JWTVerifier createCustomTokenVerifier(String algorithmName, String issuer) {
    JWTVerifier tempVerifier = verifierCustom.get(issuer);
    if (tempVerifier == null) {
        Properties props = null;//from   ww  w . j av a2  s  .c  om
        if (customProviders == null) {
            props = PropertyManager.getInstance().getProperties(PropertyNames.MDW_JWT);
            customProviders = new HashMap<>();
            for (String pn : props.stringPropertyNames()) {
                String[] pnParsed = pn.split("\\.", 4);
                if (pnParsed.length == 4) {
                    String issuer_name = pnParsed[2];
                    String attrname = pnParsed[3];
                    Properties issuerSpec = customProviders.get(issuer_name);
                    if (issuerSpec == null) {
                        issuerSpec = new Properties();
                        customProviders.put(issuer_name, issuerSpec);
                    }
                    String v = props.getProperty(pn);
                    issuerSpec.put(attrname, v);
                }
            }
        }

        props = customProviders.get(getCustomProviderGroupName(issuer));

        if (props == null) {
            logger.severe("Exception creating Custom JWT Verifier for " + issuer + " - Missing 'key' Property");
            return null;
        }

        String propAlg = props.getProperty(PropertyNames.MDW_JWT_ALGORITHM);
        if (StringHelper.isEmpty(algorithmName)
                || (!StringHelper.isEmpty(propAlg) && !algorithmName.equals(propAlg))) {
            String message = "Exception creating Custom JWT Verifier - ";
            message = StringHelper.isEmpty(algorithmName) ? "Missing 'alg' claim in JWT"
                    : ("Mismatch algorithm with specified Property for " + issuer);
            logger.severe(message);
            return null;
        }
        String key = System.getenv("MDW_JWT_" + getCustomProviderGroupName(issuer).toUpperCase() + "_KEY");
        if (StringHelper.isEmpty(key)) {
            if (!algorithmName.startsWith("HS")) { // Only allow use of Key in MDW properties for asymmetric algorithms
                key = props.getProperty(PropertyNames.MDW_JWT_KEY);
                if (StringHelper.isEmpty(key)) {
                    logger.severe("Exception creating Custom JWT Verifier for " + issuer
                            + " - Missing 'key' Property");
                    return null;
                }
            } else {
                logger.severe("Could not find properties for JWT issuer " + issuer);
                return null;
            }
        }

        try {
            maxAge = PropertyManager.getIntegerProperty(PropertyNames.MDW_AUTH_TOKEN_MAX_AGE, 0) * 1000L;

            Algorithm algorithm = null;
            Method algMethod = null;
            if (algorithmName.startsWith("HS")) { // HMAC
                String methodName = "HMAC" + algorithmName.substring(2);
                algMethod = Algorithm.none().getClass().getMethod(methodName, String.class);
                algorithm = (Algorithm) algMethod.invoke(Algorithm.none(), key);
            } else if (algorithmName.startsWith("RS")) { // RSA
                String methodName = "RSA" + algorithmName.substring(2);
                byte[] publicBytes = Base64.decodeBase64(key.getBytes());
                X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                PublicKey pubKey = keyFactory.generatePublic(keySpec);
                algMethod = Algorithm.none().getClass().getMethod(methodName, RSAPublicKey.class,
                        RSAPrivateKey.class);
                algorithm = (Algorithm) algMethod.invoke(Algorithm.none(), pubKey, null);
            } else {
                logger.severe(
                        "Exception creating Custom JWT Verifier - Unsupported Algorithm: " + algorithmName);
                return null;
            }

            String subject = props.getProperty(PropertyNames.MDW_JWT_SUBJECT);

            Verification tmp = JWT.require(algorithm).withIssuer(issuer);
            tmp = StringHelper.isEmpty(subject) ? tmp : tmp.withSubject(subject);
            tempVerifier = tmp.build();
            verifierCustom.put(issuer, tempVerifier);
        } catch (IllegalArgumentException | NoSuchAlgorithmException | NoSuchMethodException | SecurityException
                | IllegalAccessException | InvocationTargetException | InvalidKeySpecException e) {
            logger.severeException("Exception creating Custom JWT Verifier for " + issuer, e);
        }
    }
    return tempVerifier;
}

From source file:com.github.ibole.infrastructure.security.ECDSA.java

public static void jdkECDSA() {
    try {/*from w ww .  j a  v a 2s  .  c om*/
        // 1.?
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
        keyPairGenerator.initialize(256);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
        ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();

        // 2.??
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());

        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Signature signature = Signature.getInstance("SHA256withECDSA");
        signature.initSign(privateKey);
        signature.update(src.getBytes());
        byte[] res = signature.sign();
        System.out.println("??" + Base64.encodeBase64String(res));

        // 3.???
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
        keyFactory = KeyFactory.getInstance("EC");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        signature = Signature.getInstance("SHA256withECDSA");
        signature.initVerify(publicKey);
        signature.update(src.getBytes());
        boolean bool = signature.verify(res);
        System.out.println("?" + bool);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Converts a given RSA PrivateKey instance to a KeyPair instance. The
 * PublicKey will be extracted from PrivateKey instance.
 * //from www  . j a  v a 2 s . com
 * @param pKey
 *            The RSA PrivateKey used to generate the KeyPair
 * @return KeyPair instance including the private and public key.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static KeyPair privateKeyToKeyPair(PrivateKey pKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.KEY_FACTORY, new BouncyCastleProvider());
    RSAPrivateCrtKey rsaPKey = (RSAPrivateCrtKey) pKey;
    RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPKey.getModulus(),
            rsaPKey.getPublicExponent());
    return new KeyPair(keyFactory.generatePublic(publicKeySpec), pKey);
}

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

/**
 * ?/*from   w  w w.jav  a2 s. 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:com.orange.oidc.secproxy_service.KryptoUtils.java

public static PublicKey pubKeyFromJwk(String jwkp) {
    PublicKey pubKey = null;/*from  ww  w . j a va 2  s  .c  o  m*/

    try {
        JSONObject jk = new JSONObject(jwkp).getJSONArray("keys").getJSONObject(0);

        BigInteger n = new BigInteger(1, decodeB64(jk.getString("n")));
        BigInteger e = new BigInteger(1, decodeB64(jk.getString("e")));

        // Log.d("pubKeyFromJwk","n "+n);
        // Log.d("pubKeyFromJwk","e "+e);

        RSAPublicKeySpec pubRsaSpec = new RSAPublicKeySpec(n, e);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "SC");
        pubKey = keyfact.generatePublic(pubRsaSpec);
        // Log.d("pubKeyFromJwk","pub key length "+pubRsaSpec.getModulus().toByteArray().length);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return pubKey;
}

From source file:biz.bokhorst.xprivacy.Util.java

private static PublicKey getPublicKey(Context context) throws Throwable {
    // Read public key
    String sPublicKey = "";
    InputStreamReader isr = new InputStreamReader(context.getAssets().open("XPrivacy_public_key.txt"), "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();//from www .  j  a  va  2s .co 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: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();//from   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.netscape.cms.servlet.test.DRMTest.java

/**
 * Verify the generated asymmetric key pair.
 *
 * @param keyAlgorithm - Algorithm used to generate keys.
 * @param privateKey - binary data of the private key.
 * @param publicKey - binary data of he public key.
 * @return//from  ww w  .  j a  v a  2  s  .c o m
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IOException
 */
public static boolean isKeyPairValid(String keyAlgorithm, byte[] privateKey, byte[] publicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException,
        IOException {
    String algorithm = keyAlgorithm.toUpperCase();
    String signingAlgorithm = "SHA1with" + algorithm;
    KeyFactory factory = KeyFactory.getInstance(algorithm);
    PrivateKey priKey = factory.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
    PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(publicKey));
    Signature sig = Signature.getInstance(signingAlgorithm);
    sig.initSign(priKey);
    String s = "Data to test asymmetric keys.";
    sig.update(s.getBytes());

    // Sign the data with the private key.
    byte[] realSig = sig.sign();

    Signature sig2 = Signature.getInstance(signingAlgorithm);
    sig2.initVerify(pubKey);

    sig2.update(s.getBytes());
    // Verify the signature with the public key.
    return sig2.verify(realSig);
}

From source file:JALPTest.java

/**
 * Creates a Producer using the given command line params.
 *
 * @param xml            the ApplicationMetadataXML
 * @param socketPath      a String which is the path to the socket
 * @param privateKeyPath   a String which is the path to the private key in DER format
 * @param publicKeyPath      a String which is the path to the public key in DER format
 * @param certPath         a String which is the path to the certificate
 * @param hasDigest         a Boolean, true to set a digest method in the producer
 * @return   the created Producer/*from w ww  . ja v  a 2  s .  c  om*/
 * @throws Exception
 */
private static Producer createProducer(ApplicationMetadataXML xml, String socketPath, String privateKeyPath,
        String publicKeyPath, String certPath, Boolean hasDigest) throws Exception {
    Producer producer = new Producer(xml);
    producer.setSocketFile(socketPath);

    if (privateKeyPath != null && !"".equals(privateKeyPath)) {

        File privateKeyFile = new File(privateKeyPath);
        DataInputStream privateDis = new DataInputStream(new FileInputStream(privateKeyFile));
        byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()];
        privateDis.readFully(privateKeyBytes);
        privateDis.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        KeySpec privateKs = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKs);

        File publicKeyFile = new File(publicKeyPath);
        DataInputStream publicDis = new DataInputStream(new FileInputStream(publicKeyFile));
        byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()];
        publicDis.readFully(publicKeyBytes);
        publicDis.close();

        KeySpec publicKs = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = keyFactory.generatePublic(publicKs);

        producer.setPrivateKey(privateKey);
        producer.setPublicKey(publicKey);
    }

    if (certPath != null && !"".equals(certPath)) {
        InputStream inputStream = new FileInputStream(certPath);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
        inputStream.close();
        producer.setCertificate(cert);
    }

    if (hasDigest) {
        producer.setDigestMethod(DMType.SHA256);
    }

    return producer;
}