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.microsoft.azure.oidc.token.impl.SimpleTokenValidator.java

@Override
public Boolean validateSignature(final Token token) {
    if (token == null) {
        throw new PreconditionException("Required parameter is null");
    }//from   w  w  w  .j a  va 2s.com
    if (algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName())
            .equals("HMAC")) {
        return Boolean.FALSE;
    }
    final Configuration configuration = configurationCache.load();
    if (configuration == null) {
        throw new GeneralException("Error loading configuration");
    }
    try {
        final TimeStamp now = timeStampFactory.createTimeStamp(System.currentTimeMillis() / 1000);
        if (configuration.getKey(token.getKeyName()).getNotBefore().compareTo(now) > 0) {
            return Boolean.FALSE;
        }
        final Base64 decoder = new Base64();
        final BigInteger exponent = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getExponent().getValue()));
        final BigInteger modulus = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getSecret().getValue()));
        final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance(
                algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()));
        final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        final Signature sig = Signature.getInstance(
                algorithmConfigurationService.get().getAlgorithmMap().get(token.getAlgorithm().getName()));
        sig.initVerify(pubKey);
        sig.update(token.getPayload().getValue().getBytes());
        return sig.verify(decoder.decode(token.getSignature().getValue()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | InvalidKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return Boolean.FALSE;
    }
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair)
        throws Exception {
    SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance(ALG_RSA);
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() - DateConstant.ONE_DAY),
            new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
            .build(pKeyPair.getPrivate());
    X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
            .getCertificate(certBuilder.build(signer));
    signedCert.verify(pKeyPair.getPublic());

    return signedCert;
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * read Public Key From File/*from   w  ww  . ja v a 2 s  . com*/
 * @param filePath
 * @return PublicKey
 * @throws IOException
 */
public PublicKey readPublicKeyFromFile(String filePath) throws Exception {
    // Read file to a byte array.
    Path path = Paths.get(filePath);
    byte[] pubKeyByteArray = Files.readAllBytes(path);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(pubKeyByteArray);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
}

From source file:com.ibm.dbwkl.helper.CryptionModule.java

/**
 * @return PublicKey Instance/*from  ww w .j  av  a2s.c o m*/
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws InvalidKeySpecException
 */
private RSAPublicKey getPublicKey() throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    KeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(PUBLIC_KEY));
    RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);

    return publicKey;
}

From source file:info.globalbus.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*from   ww  w. j  a  v  a  2  s .c o  m*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test
            // validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * RSA??/*w w w  . j av  a  2s. co  m*/
 * <dl>
 * <dt>?
 * <dd>RSA??
 * </dl>
 * @param name RSA???
 * @return RSA?
 */
public KeyPair loadKeyPair(final String name) {
    try {
        final Properties property = new PropertyService(PROPERTY_NAME).getProperty();
        final KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGO_NAME);
        final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(
                Hex.decodeHex(property.getProperty(String.format(KEY_PUBLIC_ENCODED, name)).toCharArray())));
        final RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(
                Hex.decodeHex(property.getProperty(String.format(KEY_PRIVATE_ENCODED, name)).toCharArray())));
        return new KeyPair(publicKey, privateKey);
    } catch (final IOException | DecoderException | InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:Networking.Client.java

public boolean SignatureVerification() {
    Signature sig = null;/*from  w ww.  j  av a  2s. com*/
    Boolean result = false;
    try {
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PubToVerify);
        KeyFactory keyFact = KeyFactory.getInstance("DSA", "SUN");
        PublicKey pubkeyToVerify = keyFact.generatePublic(pubKeySpec);
        confirmIdentity = checkAgainstRT(pubkeyToVerify.hashCode());
        sig = Signature.getInstance("SHA1withDSA", "SUN");
        sig.initVerify(pubkeyToVerify);

        byte[] g_pow_y_sign = this.node.getG_pow_y().toByteArray();
        byte[] g_pow_x_sign = this.node.getG_pow_x().toByteArray();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(g_pow_x_sign);
        outputStream.write(g_pow_y_sign);
        byte[] c = outputStream.toByteArray();

        sig.update(c);
        result = (sig.verify(sigToVerify));
    } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException
            | InvalidKeySpecException | IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:com.wso2telco.gsma.authenticators.OpCoCompositeAuthenticator.java

/**
 * Read public key from file.//w  w w  .j a  v a  2  s  . co  m
 *
 * @param fileName the file name
 * @return the public key
 * @throws AuthenticationFailedException the authentication failed exception
 */
private PublicKey readPublicKeyFromFile(String fileName) throws AuthenticationFailedException {
    try {
        String publicK = readStringKey(fileName);
        byte[] keyBytes = Base64.decodeBase64(publicK.getBytes());
        ;
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(spec);
    } catch (Exception e) {
        throw new AuthenticationFailedException(
                "Authentication Failed since reading public key from file failed.");
    }
}

From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java

public KeyPair keyPairFromJson(String keyPairJson) throws U2FException {
    BigInteger x = null;/* w  ww  .ja v a 2  s . c o m*/
    BigInteger y = null;
    BigInteger d = null;

    try {
        JSONObject jsonKeyPair = (JSONObject) new JSONTokener(keyPairJson).nextValue();

        JSONObject jsonPrivateKey = jsonKeyPair.getJSONObject("privateKey");
        d = new BigInteger(Utils.decodeHexString(jsonPrivateKey.getString("d")));

        JSONObject jsonPublicKey = jsonKeyPair.getJSONObject("publicKey");
        x = new BigInteger(Utils.decodeHexString(jsonPublicKey.getString("x")));
        y = new BigInteger(Utils.decodeHexString(jsonPublicKey.getString("y")));
    } catch (JSONException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    } catch (DecoderException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    }

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");

    ECCurve curve = ecSpec.getCurve();
    ECPoint validatePoint = curve.validatePoint(x, y);

    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(validatePoint, ecSpec);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(d, ecSpec);

    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance("ECDSA", BOUNCY_CASTLE_PROVIDER);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        return new KeyPair(publicKey, privateKey);
    } catch (NoSuchAlgorithmException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    } catch (InvalidKeySpecException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    }
}

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

/**
 * //  ww  w . ja  v a  2  s  .c  o  m
 * 
 * 
 * @param info ?
 * @return ?
 * @throws GeneralSecurityException GeneralSecurityException
 */
public String encode(String info) throws GeneralSecurityException {
    // ?token?
    byte[] pubKeyText = this.getPubKeyText();
    X509EncodedKeySpec bobPKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKeyText));
    KeyFactory keyFactory = null;
    if (provider == null) {
        keyFactory = KeyFactory.getInstance(ALGORITHM);
    } else {
        keyFactory = KeyFactory.getInstance(ALGORITHM, provider);
    }
    // ?
    PublicKey pubkey = keyFactory.generatePublic(bobPKeySpec);
    // CipherECB?PKCS5Padding
    Cipher cipher = null;
    if (provider == null) {
        cipher = Cipher.getInstance(ALGORITHM);
    } else {
        cipher = Cipher.getInstance(ALGORITHM, provider);
    }
    // ?
    cipher.init(Cipher.ENCRYPT_MODE, pubkey);
    byte[] cipherText = cipher.doFinal(info.getBytes());
    return new String(Base64.encodeBase64(cipherText));
}