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.floreantpos.license.FiveStarPOSLicenseManager.java

private final PublicKey readPublicKey(String uri) throws LicenseException {
    try {//from   w  w  w. j a v  a  2 s  .co m

        InputStream inputStream = getClass().getResourceAsStream(uri);
        byte[] bytes = IOUtils.toByteArray(inputStream);

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");

        return keyFactory.generatePublic(keySpec);

    } catch (Exception e) {
        throw new LicenseException("Invalid license key! Please contact our support.", e);
    }
}

From source file:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPrivateKey.java

/**
 *
 *
 * @return//w w  w .j  a  va  2s  . co  m
 */
public SshPublicKey getPublicKey() {
    try {
        DSAPublicKeySpec spec = new DSAPublicKeySpec(getY(), prvkey.getParams().getP(),
                prvkey.getParams().getQ(), prvkey.getParams().getG());

        KeyFactory kf = KeyFactory.getInstance("DSA");

        return new SshDssPublicKey((DSAPublicKey) kf.generatePublic(spec));
    } catch (Exception e) {
        return null;
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * An ECDSA key can be stripped of the curve parameters so it only contains the public point, and this is not enough to use the key for
 * verification. However, if we know the curve name we can fill in the curve parameters and get a usable EC public key
 * /*from w w w.j  a  v  a  2 s .com*/
 * @param pk
 *            PublicKey, org.ejbca.cvc.PublicKeyEC, that might miss parameters, if parameters are there we do not touch the public key just return it unchanged
 * @param keySpec
 *            name of curve for example brainpoolp224r1
 * @return PublicKey with parameters from the named curve
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getECPublicKeyWithParams(final PublicKey pk, final String keySpec)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    PublicKey ret = pk;
    if ((pk instanceof PublicKeyEC) && (keySpec != null)) {
        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) {
            // we did not have the parameter specs, lets create them because we know which curve we are using
            final org.bouncycastle.jce.spec.ECParameterSpec bcspec = ECNamedCurveTable
                    .getParameterSpec(keySpec);
            final java.security.spec.ECPoint p = pkec.getW();
            final org.bouncycastle.math.ec.ECPoint ecp = EC5Util.convertPoint(bcspec.getCurve(), p, false);
            final ECPublicKeySpec pubKey = new ECPublicKeySpec(ecp, bcspec);
            final KeyFactory keyfact = KeyFactory.getInstance("ECDSA", "BC");
            ret = keyfact.generatePublic(pubKey);
        }
    }
    return ret;
}

From source file:org.diorite.impl.auth.yggdrasil.YggdrasilSessionService.java

public YggdrasilSessionService(final Proxy proxy, final String clientToken) {
    this.proxy = proxy;
    this.clientToken = clientToken;
    try {/*  www. j a  va 2 s.c om*/
        //noinspection HardcodedFileSeparator
        final KeySpec spec = new X509EncodedKeySpec(IOUtils.toByteArray(
                YggdrasilSessionService.class.getResourceAsStream("/yggdrasil_session_pubkey.der")));
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        this.publicKey = keyFactory.generatePublic(spec);
    } catch (final Exception e) {
        //noinspection HardcodedFileSeparator
        throw new Error("Missing/invalid yggdrasil public key!");
    }
}

From source file:jenkins.security.RSAConfidentialKey.java

/**
 * Obtains the private key (lazily.)//from  www  .j av  a2  s.  c  o  m
 * <p>
 * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}.
 * Instead of exposing private key, define methods that use them in specific way, such as
 * {@link RSADigitalSignatureConfidentialKey}.
 *
 * @throws Error
 *      If key cannot be loaded for some reasons, we fail.
 */
protected synchronized RSAPrivateKey getPrivateKey() {
    try {
        if (priv == null) {
            byte[] payload = load();
            if (payload == null) {
                KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
                gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension
                KeyPair keys = gen.generateKeyPair();
                priv = (RSAPrivateKey) keys.getPrivate();
                pub = (RSAPublicKey) keys.getPublic();
                store(priv.getEncoded());
            } else {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload));

                RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv;
                pub = (RSAPublicKey) keyFactory
                        .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent()));
            }
        }
        return priv;
    } catch (IOException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    } catch (GeneralSecurityException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/** 
 * Get the ASN.1 encoded PublicKey as a Java PublicKey Object.
 * @param the ASN.1 encoded PublicKey//from   w w w . java 2 s . com
 * @return the ASN.1 encoded PublicKey as a Java Object
 */
public static PublicKey getPublicKeyFromBytes(byte[] asn1EncodedPublicKey) {
    PublicKey pubKey = null;
    final ASN1InputStream in = new ASN1InputStream(asn1EncodedPublicKey);
    try {
        final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(in.readObject());
        final AlgorithmIdentifier keyAlg = keyInfo.getAlgorithm();
        final X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(new DERBitString(keyInfo).getBytes());
        final KeyFactory keyFact = KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), "BC");
        pubKey = keyFact.generatePublic(xKeySpec);
    } catch (IOException e) {
        log.debug("Unable to decode PublicKey.", e);
    } catch (NoSuchAlgorithmException e) {
        log.debug("Unable to decode PublicKey.", e);
    } catch (NoSuchProviderException e) {
        log.debug("Unable to decode PublicKey.", e);
    } catch (InvalidKeySpecException e) {
        log.debug("Unable to decode PublicKey.", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            log.debug("Unable to close input stream.");
        }
    }
    return pubKey;
}

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

/**
 * The key is constructed form modulus and exponent.
 *
 * @param modulus//from   w  w  w. ja va 2 s  .c o  m
 * @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:com.tasktop.c2c.server.internal.profile.crypto.Rfc4716PublicKeyReader.java

/**
 * read a public key from the given text
 * /*from   w w  w  .java  2s .  c o  m*/
 * @param keySpec
 *            the key specification.
 * @return the key or null if no key was found
 */
public SshPublicKey readPublicKey(String keySpec) {
    BufferedReader reader = new BufferedReader(new StringReader(keySpec));
    String line;
    SshPublicKey key = null;
    boolean endFound = false;
    boolean dataStarted = false;
    boolean continueHeader = false;
    String base64Data = "";
    try {
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            // skip blank lines. They shouldn't really be in there, but if they are we can ignore them.
            if (line.length() != 0) {
                if (key == null) {
                    if (line.equals(START_MARKER)) {
                        key = new SshPublicKey();
                    }
                } else {
                    if (line.equals(END_MARKER)) {
                        endFound = true;
                        break;
                    } else if (!dataStarted && (continueHeader || HEADER_PATTERN.matcher(line).matches())) {
                        // skip headers
                        continueHeader = line.endsWith("\"");
                    } else {
                        dataStarted = true;

                        base64Data += line;
                    }
                }
            }
        }
        if (!endFound) {
            key = null;
        } else {
            if (base64Data.length() > 0) {
                byte[] keyData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data));

                Rfc4253Reader keyReader = new Rfc4253Reader(keyData, 0);
                String algorithm = keyReader.readString();
                if ("ssh-rsa".equals(algorithm)) {
                    key.setAlgorithm("RSA");

                    BigInteger exponent = keyReader.readMpint();
                    BigInteger modulus = keyReader.readMpint();

                    try {
                        KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                        RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
                        PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

                        byte[] encoded = publicKey.getEncoded();

                        key.setKeyData(encoded);

                    } catch (InvalidKeySpecException t) {
                        getLogger().warn("Invalid key spec: " + t.getMessage(), t);
                    } catch (NoSuchAlgorithmException t) {
                        getLogger().warn("Invalid algorithm: " + t.getMessage(), t);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    if (key == null || key.getAlgorithm() == null || key.getKeyData() == null) {
        key = null;
    }
    return key;
}

From source file:tech.beshu.ror.acl.blocks.rules.impl.JwtAuthSyncRule.java

@Override
public CompletableFuture<RuleExitResult> match(__old_RequestContext rc) {
    Optional<String> token = Optional.of(rc.getHeaders()).map(m -> m.get(settings.getHeaderName()))
            .flatMap(JwtAuthSyncRule::extractToken);

    /*//  w  ww  .  j  ava 2  s.  co m
      JWT ALGO    FAMILY
      =======================
      NONE        None
            
      HS256       HMAC
      HS384       HMAC
      HS512       HMAC
            
      RS256       RSA
      RS384       RSA
      RS512       RSA
      PS256       RSA
      PS384       RSA
      PS512       RSA
            
      ES256       EC
      ES384       EC
      ES512       EC
    */

    if (!token.isPresent()) {
        logger.debug("Authorization header is missing or does not contain a bearer token");
        return CompletableFuture.completedFuture(NO_MATCH);
    }

    try {

        JwtParser parser = Jwts.parser();

        // Defaulting to HMAC for backward compatibility
        String algoFamily = settings.getAlgo().map(String::toUpperCase).orElse("HMAC");
        if (settings.getKey() == null) {
            algoFamily = "NONE";
        }

        if (!"NONE".equals(algoFamily)) {

            if ("RSA".equals(algoFamily)) {
                try {
                    byte[] keyBytes = Base64.decodeBase64(settings.getKey());
                    KeyFactory kf = KeyFactory.getInstance("RSA");
                    PublicKey pubKey = kf.generatePublic(new X509EncodedKeySpec(keyBytes));
                    parser.setSigningKey(pubKey);
                } catch (GeneralSecurityException gso) {
                    throw new RuntimeException(gso);
                }
            }

            else if ("EC".equals(algoFamily)) {
                try {
                    byte[] keyBytes = Base64.decodeBase64(settings.getKey());
                    KeyFactory kf = KeyFactory.getInstance("EC");
                    PublicKey pubKey = kf.generatePublic(new X509EncodedKeySpec(keyBytes));
                    parser.setSigningKey(pubKey);
                } catch (GeneralSecurityException gso) {
                    throw new RuntimeException(gso);
                }
            }

            else if ("HMAC".equals(algoFamily)) {
                parser.setSigningKey(settings.getKey());
            } else {
                throw new RuntimeException("unrecognised algorithm family " + algoFamily
                        + ". Should be either of: HMAC, EC, RSA, NONE");
            }
        }

        Claims jws;
        if (settings.getKey() != null) {
            jws = parser.parseClaimsJws(token.get()).getBody();
        } else {
            String[] ar = token.get().split("\\.");
            if (ar.length < 2) {
                // token is not a valid JWT
                return CompletableFuture.completedFuture(NO_MATCH);
            }
            String tokenNoSig = ar[0] + "." + ar[1] + ".";
            jws = parser.parseClaimsJwt(tokenNoSig).getBody();
        }

        Claims finalJws = jws;
        Optional<String> user = settings.getUserClaim().map(claim -> finalJws.get(claim, String.class));
        if (settings.getUserClaim().isPresent())
            if (!user.isPresent()) {
                return CompletableFuture.completedFuture(NO_MATCH);
            } else {
                rc.setLoggedInUser(new LoggedUser(user.get()));
            }

        Optional<Set<String>> roles = this.extractRoles(jws);
        if (settings.getRolesClaim().isPresent() && !roles.isPresent()) {
            return CompletableFuture.completedFuture(NO_MATCH);
        }
        if (!settings.getRoles().isEmpty()) {
            if (!roles.isPresent()) {
                return CompletableFuture.completedFuture(NO_MATCH);
            } else {
                Set<String> r = roles.get();
                if (r.isEmpty() || Sets.intersection(r, settings.getRoles()).isEmpty())
                    return CompletableFuture.completedFuture(NO_MATCH);
            }
        }

        if (settings.getExternalValidator().isPresent()) {
            return httpClient.authenticate("x", token.get()).thenApply(resp -> resp ? MATCH : NO_MATCH);
        }
        return CompletableFuture.completedFuture(MATCH);

    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException e) {
        return CompletableFuture.completedFuture(NO_MATCH);
    }
}

From source file:org.apache.james.jdkim.tagvalue.PublicKeyRecordImpl.java

/**
 * @see org.apache.james.jdkim.api.PublicKeyRecord#getPublicKey()
 *//*from   w w  w .  ja  v a 2s .c  om*/
public PublicKey getPublicKey() {
    try {
        String p = getValue("p").toString();
        byte[] key = Base64.decodeBase64(p.getBytes());
        KeyFactory keyFactory;
        keyFactory = KeyFactory.getInstance(getValue("k").toString());
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(key);
        RSAPublicKey rsaKey;
        rsaKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
        return rsaKey;
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Unknown algorithm: " + e.getMessage());
    } catch (InvalidKeySpecException e) {
        throw new IllegalStateException("Invalid key spec: " + e.getMessage());
    }
}