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.ddubyat.develop.jhawtcode.util.PropertyUtil.java

private boolean validLicense(String email, String licenseCode) throws Exception {

    Resource res = applicationContext.getResource("classpath:jhc-public.der");
    InputStream is = res.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[4096];
    byte[] pkey;/*from  w  w  w  .j ava2  s.c om*/
    int stream;
    while ((stream = is.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, stream);
    }

    pkey = baos.toByteArray();

    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pkey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey mypk = keyFactory.generatePublic(keySpec);

    Signature instance = Signature.getInstance("SHA1withRSA");
    instance.initVerify(mypk);
    instance.update(email.getBytes());

    //BASE64Decoder decoder = new BASE64Decoder();
    //byte[] decodedBytes = decoder.decodeBuffer(licenseCode);

    return instance.verify(DatatypeConverter.parseBase64Binary(licenseCode));
}

From source file:enc_mods.aes.java

/**
 * Encrypts the AES key to a file using an RSA public key
 *///from   w  w w. j av a  2s  .c o m
public void saveKey(File out, File publicKeyFile) {
    try {
        // read public key to be used to encrypt the AES key
        byte[] encodedKey = new byte[(int) publicKeyFile.length()];
        new FileInputStream(publicKeyFile).read(encodedKey);

        // create public key
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pk = kf.generatePublic(publicKeySpec);

        // write AES key
        cipher.init(Cipher.ENCRYPT_MODE, pk);
        CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), cipher);
        os.write(key);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.opensaml.xml.security.SecurityHelper.java

/**
 * Derives the public key from either a DSA or RSA private key.
 * // w w w . ja va  2  s .co m
 * @param key the private key to derive the public key from
 * 
 * @return the derived public key
 * 
 * @throws KeyException thrown if the given private key is not a DSA or RSA key or there is a problem generating the
 *             public key
 */
public static PublicKey derivePublicKey(PrivateKey key) throws KeyException {
    KeyFactory factory;
    if (key instanceof DSAPrivateKey) {
        DSAPrivateKey dsaKey = (DSAPrivateKey) key;
        DSAParams keyParams = dsaKey.getParams();
        BigInteger y = keyParams.getQ().modPow(dsaKey.getX(), keyParams.getP());
        DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, keyParams.getP(), keyParams.getQ(),
                keyParams.getG());

        try {
            factory = KeyFactory.getInstance("DSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from DSA private key", e);
        }
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());

        try {
            factory = KeyFactory.getInstance("RSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from RSA private key", e);
        }
    } else {
        throw new KeyException("Private key was not a DSA or RSA key");
    }
}

From source file:com.xinferin.licensing.LicenceActivator.java

private void initialiseKeys() throws Exception {
    try {//from   w w w.  j av a  2s  .c  o  m

        byte[] publicKeyBytes = Base64.decodeBase64(spublicKey);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        publicKey = keyFactory.generatePublic(publicKeySpec);

    } catch (InvalidKeySpecException e) {
        throw new Exception("Invalid Key Specs not valid Key files." + e.getCause());
    } catch (NoSuchAlgorithmException e) {
        throw new Exception("There is no such algorithm. Please check the JDK ver." + e.getCause());
    }
}

From source file:org.apache.abdera2.common.security.DHBase.java

private Key decode(byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException {
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
    KeyFactory keyFact = KeyFactory.getInstance("DH");
    return keyFact.generatePublic(x509KeySpec);
}

From source file:org.orbeon.oxf.processor.SignatureVerifierProcessor.java

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(SignatureVerifierProcessor.this, name) {
        public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) {
            try {
                final Document pubDoc = readCacheInputAsDOM4J(context, INPUT_PUBLIC_KEY);
                final String pubString = XPathUtils.selectStringValueNormalize(pubDoc, "/public-key");
                final byte[] pubBytes = Base64.decode(pubString);
                final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

                final Signature dsa = Signature.getInstance("SHA1withDSA");
                dsa.initVerify(pubKey);/*from ww w  .j a  va2 s  .c om*/

                final Document data = readInputAsDOM4J(context, INPUT_DATA);
                final Node sigDataNode = data.selectSingleNode("/signed-data/data/*");
                final String sig = StringUtils
                        .trimToEmpty(XPathUtils.selectStringValue(data, "/signed-data/signature"));

                sigDataNode.detach();
                final Document sigData = new NonLazyUserDataDocument();
                sigData.add(sigDataNode);

                dsa.update(Dom4jUtils.domToString(sigData).getBytes("utf-8"));

                // Verify signature and throw in case of failure
                try {
                    if (!dsa.verify(Base64.decode(sig)))
                        throw new OXFException("Signature verification failed");
                } catch (SignatureException e) {
                    throw e;
                } catch (Exception e) {
                    // A number of things can fail above, including Base64 decoding
                    // NOTE: We don't pas the cause so that we can match on SignatureException as root Exception
                    throw new SignatureException("Signature verification failed");
                }

                // Signature verification passed
                final LocationSAXWriter saw = new LocationSAXWriter();
                saw.setContentHandler(xmlReceiver);
                saw.write(sigData);
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:jp.alessandro.android.iab.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key./*  w  w w .  j a  va  2 s .com*/
 *
 * @param encodedPublicKey rsa public key generated by Google Play Developer Console
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
protected PublicKey generatePublicKey(String encodedPublicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException {

    byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
}

From source file:com.ss.license.LicenseManager.java

/**
 * license/* w  w w  .  j av a2s.  c  o  m*/
 * Mac
 * 
 * 
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.getMacAddress();
    if (macAddress != null && macAddress.length() > 0) {
        String curMacAddress = "";
        if (!macAddress.equals(curMacAddress))
            return false;
    }
    String publicKey = FileHelper.readFile(new File(LicenseFactory.PUBLIC_KEY_FILE)).trim();

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance("DSA");
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.getLicenseSignature()));
}

From source file:org.limewire.activation.impl.ActivationCommunicatorImpl.java

private String getEncryptedToken(String licenseId, String randomNumber) throws IOException {
    // get public key from string
    byte[] cipherData;
    byte[] keyBytes = Base64.decodeBase64(activationSettings.getServerKey().getBytes());
    try {//from   w  ww  . jav  a2  s.  co  m
        KeyFactory fac = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
        PublicKey publicKey = fac.generatePublic(new X509EncodedKeySpec(keyBytes));

        byte[] messageToEcrypt = StringUtils.toUTF8Bytes(licenseId + "," + randomNumber);
        cipherData = cipherProvider.encrypt(messageToEcrypt, publicKey, CIPHER_TYPE);
    } catch (GeneralSecurityException e) {
        throw IOUtils.getIOException("Security exception while initializing key", e);
    }
    String noEncoding = new String(Base64.encodeBase64(cipherData));
    return EncodingUtils.encode(noEncoding);
}