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: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:org.jasig.cas.util.PublicKeyFactoryBean.java

@Override
protected final PublicKey createInstance() throws Exception {
    logger.debug("Creating public key instance from [{}] using [{}]", this.resource.getFilename(),
            this.algorithm);

    try (final InputStream pubKey = this.resource.getInputStream()) {
        final byte[] bytes = new byte[pubKey.available()];
        pubKey.read(bytes);/*  ww w. ja va  2 s .  c  o m*/
        final X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes);
        final KeyFactory factory = KeyFactory.getInstance(this.algorithm);
        return factory.generatePublic(pubSpec);
    }
}

From source file:pl.kotcrab.crypto.RSAEncrypter.java

/** Constructs RSAEcnrypted from the key spec itself
 * @param publicKeySpec key spec */
public RSAEncrypter(X509EncodedKeySpec publicKeySpec) {
    try {//from  w w w  . j  av  a  2s.  co  m
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");

        publicKey = keyFactory.generatePublic(publicKeySpec);

        setupCiphers();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
}

From source file:org.bibsonomy.webapp.validation.opensocial.BibSonomyOAuthValidator.java

private PublicKey getPublicKeyFromPem(String pem) throws GeneralSecurityException, IOException {
    InputStream stream = new ByteArrayInputStream(pem.getBytes("UTF-8"));

    PEMReader reader = new PEMReader(stream);
    byte[] bytes = reader.getDerBytes();
    PublicKey pubKey;//from   w  w w  .ja v a2  s .  com

    if (PEMReader.PUBLIC_X509_MARKER.equals(reader.getBeginMarker())) {
        KeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory fac = KeyFactory.getInstance("RSA");
        pubKey = fac.generatePublic(keySpec);
    } else if (PEMReader.CERTIFICATE_X509_MARKER.equals(reader.getBeginMarker())) {
        pubKey = getPublicKeyFromDerCert(bytes);
    } else {
        throw new IOException(
                "Invalid PEM fileL: Unknown marker for " + " public key or cert " + reader.getBeginMarker());
    }

    return pubKey;
}

From source file:org.echocat.marquardt.example.keyprovisioning.KeyFileReadingKeyPairProvider.java

private PublicKey loadPublicKey(final String publicKeyFileName) {
    LOGGER.debug("Reading public key file {}.", publicKeyFileName);
    final byte[] keyFilePayload = readKeyFile(publicKeyFileName);
    final X509EncodedKeySpec spec = new X509EncodedKeySpec(keyFilePayload);
    try {//from   w  w  w.j a  v a 2  s  . c o m
        final KeyFactory keyFactory = KeyFactory.getInstance(rsa.getJavaInternalName());
        return keyFactory.generatePublic(spec);
    } catch (final GeneralSecurityException e) {
        throw new IllegalArgumentException(
                "Failed to create public key from keyfile " + publicKeyFileName + ".", e);
    }
}

From source file:org.apache.cordova.crypt.Crypt.java

public String encrypt(String data, String publickey) throws Exception {
    publickey = publickey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");

    try {/*from www . j a va2  s  .co m*/
        byte[] publickeyRaw = Base64.decode(publickey, Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publickeyRaw);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pub = fact.generatePublic(keySpec);

        byte[] text = data.getBytes(Charset.forName("UTF-8"));

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pub);
        byte[] cipherString = cipher.doFinal(text);

        return new String(Base64.encode(cipherString, Base64.DEFAULT));

    } catch (Exception e) {
        Log.w("Crypt", e);
        return null;
    }
}

From source file:com.spotify.helios.authentication.crtauth.LdapKeyProvider.java

@Override
public RSAPublicKey getKey(final String username) throws KeyNotFoundException {
    final List<String> result = ldapTemplate.search(query().base(baseSearchPath).where("uid").is(username),
            new AttributesMapper<String>() {
                @Override/* w w  w .ja v a 2  s.  c o  m*/
                public String mapFromAttributes(final Attributes attributes) throws NamingException {
                    log.debug("got ldap stuff for uid {}", username);
                    return attributes.get("sshPublicKey").toString();
                }
            });

    if (result.isEmpty()) {
        throw new KeyNotFoundException();
    } else if (result.size() == 1) {
        final String r = result.get(0);
        RSAPublicKeySpec publicKeySpec;
        try {
            final String sshPublicKey = r.replace("sshPublicKey: ", "");
            publicKeySpec = TraditionalKeyParser.parsePemPublicKey(sshPublicKey);
            final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
        } catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

    throw new IllegalStateException("Found more than one LDAP user for name: " + username);
}

From source file:com.yazino.web.payment.googlecheckout.AndroidInAppOrderSecurity.java

private PublicKey generatePublicKey(String gameType, final Partner partnerId) {
    PublicKey publicKey = null;// ww  w  .ja va2 s .c o  m
    String normalisedPartnerId = getNormalisedPartnerId(partnerId);
    final String licenseKey = yazinoConfiguration
            .getString(format(CONFIG_PREFIX, normalisedPartnerId, gameType));
    if (licenseKey == null) {
        LOG.error("No license key found for gameType {}", gameType);
    } else {
        try {
            byte[] decodedKey = Base64.decode(licenseKey.getBytes());
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
            publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
        } catch (Exception e) {
            LOG.error("Failed to decode licenseKey [{}] for gameType {}", licenseKey, gameType, e);
        }
    }
    return publicKey;
}

From source file:org.ejbca.util.keystore.KeyTools.java

public static PublicKey getECPublicKeyWithParams(final PublicKey pk, final PublicKey pkwithparams)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    PublicKey ret = pk;/*from w  w  w .j  a v a 2s .co  m*/
    if ((pk instanceof PublicKeyEC) && (pkwithparams instanceof PublicKeyEC)) {
        final PublicKeyEC pkec = (PublicKeyEC) pk;
        // The public key of IS and DV certificate do not have any parameters so we have to do some magic to get a complete EC public key
        final ECParameterSpec spec = pkec.getParams();
        if (spec == null) {
            final PublicKeyEC pkecp = (PublicKeyEC) pkwithparams;
            final ECParameterSpec pkspec = pkecp.getParams();
            if (pkspec != null) {
                final org.bouncycastle.jce.spec.ECParameterSpec bcspec = EC5Util.convertSpec(pkspec, false);
                final java.security.spec.ECPoint p = pkec.getW();
                final org.bouncycastle.math.ec.ECPoint ecp = EC5Util.convertPoint(pkspec, p, false);
                final ECPublicKeySpec pubKey = new ECPublicKeySpec(ecp, bcspec);
                final KeyFactory keyfact = KeyFactory.getInstance("ECDSA", "BC");
                ret = keyfact.generatePublic(pubKey);
            } else {
                log.info("pkwithparams does not have any params.");
            }
        }
    } else {
        log.info("Either pk or pkwithparams is not a PublicKeyEC: " + pk.toString() + ", "
                + pkwithparams.toString());
    }
    return ret;
}

From source file:org.cloudfoundry.identity.uaa.oauth.SignerProvider.java

static KeyPair parseKeyPair(String pemData) {
    Matcher m = PEM_DATA.matcher(pemData.trim());

    if (!m.matches()) {
        throw new IllegalArgumentException("String is not PEM encoded data");
    }//from  ww  w  .  j  av  a  2  s  .c  om

    String type = m.group(1);
    final byte[] content = b64Decode(utf8Encode(m.group(2)));

    PublicKey publicKey;
    PrivateKey privateKey = null;

    try {
        KeyFactory fact = KeyFactory.getInstance("RSA");
        if (type.equals("RSA PRIVATE KEY")) {
            ASN1Sequence seq = ASN1Sequence.getInstance(content);
            if (seq.size() != 9) {
                throw new IllegalArgumentException("Invalid RSA Private Key ASN1 sequence.");
            }
            org.bouncycastle.asn1.pkcs.RSAPrivateKey key = org.bouncycastle.asn1.pkcs.RSAPrivateKey
                    .getInstance(seq);
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(key.getModulus(), key.getPublicExponent(),
                    key.getPrivateExponent(), key.getPrime1(), key.getPrime2(), key.getExponent1(),
                    key.getExponent2(), key.getCoefficient());
            publicKey = fact.generatePublic(pubSpec);
            privateKey = fact.generatePrivate(privSpec);
        } else if (type.equals("PUBLIC KEY")) {
            KeySpec keySpec = new X509EncodedKeySpec(content);
            publicKey = fact.generatePublic(keySpec);
        } else if (type.equals("RSA PUBLIC KEY")) {
            ASN1Sequence seq = ASN1Sequence.getInstance(content);
            org.bouncycastle.asn1.pkcs.RSAPublicKey key = org.bouncycastle.asn1.pkcs.RSAPublicKey
                    .getInstance(seq);
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            publicKey = fact.generatePublic(pubSpec);
        } else {
            throw new IllegalArgumentException(type + " is not a supported format");
        }

        return new KeyPair(publicKey, privateKey);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}