Example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

List of usage examples for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec.

Prototype

public X509EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new X509EncodedKeySpec with the given encoded key.

Usage

From source file:com.axelor.apps.account.service.payment.PayboxService.java

/** Chargement de la cle AU FORMAT der
  * Utliser la commande suivante pour 'convertir' la cl 'pem' en 'der'
  * openssl rsa -inform PEM -in pubkey.pem -outform DER -pubin -out pubkey.der
  *//  ww  w .j  a  v a  2 s . c  o  m
  * @param pubKeyFile
  * @return
  * @throws Exception
  */
@Deprecated
private PublicKey getPubKeyDer(String pubKeyPath) throws Exception {

    FileInputStream fis = new FileInputStream(pubKeyPath);
    DataInputStream dis = new DataInputStream(fis);

    byte[] pubKeyBytes = new byte[fis.available()];

    dis.readFully(pubKeyBytes);
    fis.close();
    dis.close();

    KeyFactory keyFactory = KeyFactory.getInstance(this.ENCRYPTION_ALGORITHM);

    // extraction cle
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
    return keyFactory.generatePublic(pubSpec);

}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*w ww . ja v  a 2 s  .  c  o m*/
 */
@Override
public final ByteArray encryptRandomGeneratedKey(ByteArray key, ByteArray data) throws McbpCryptoException {
    ByteArray result;
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");

        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ByteArray.of(key).getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec));

        result = ByteArray.of(cipher.doFinal(data.getBytes()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException
            | BadPaddingException | IllegalBlockSizeException e) {
        throw new McbpCryptoException(e.getMessage());
    }
    return result;
}

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();//  w w w .ja v a  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:com.wso2telco.proxy.entity.ServerInitiatedServiceEndpoints.java

private RSAPublicKey loadPublicKey(String publicKeyContent) throws GeneralSecurityException {
    KeyFactory kf = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyContent));
    return (RSAPublicKey) kf.generatePublic(pubSpec);
}

From source file:ee.ria.xroad.common.util.CryptoUtils.java

/**
 * Reads a public key from X509 encoded bytes.
 * @param encoded the data//ww w .  j av a  2s  .  co  m
 * @return public key read from the bytes
 * @throws Exception if any errors occur
 */
public static PublicKey readX509PublicKey(byte[] encoded) throws Exception {
    X509EncodedKeySpec x509EncodedPublicKey = new X509EncodedKeySpec(encoded);
    return KEY_FACTORY.generatePublic(x509EncodedPublicKey);
}

From source file:com.arm.connector.bridge.core.Utils.java

static public PublicKey createPublicKeyFromPEM(ErrorLogger logger, String pem, String algorithm) {
    try {/*  w  ww. j a v  a 2 s  .  c  o  m*/
        String temp = Utils.escapeChars(pem);
        String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----", "");
        publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");

        // DEBUG
        //logger.info("createPublicKeyFromPEM: " + publicKeyPEM);

        Base64 b64 = new Base64();
        byte[] decoded = b64.decode(publicKeyPEM);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
        KeyFactory kf = KeyFactory.getInstance(algorithm);
        return kf.generatePublic(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        // exception caught
        logger.warning("createPublicKeyFromPEM: Exception during public key gen", ex);
    }
    return null;
}

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;//w ww  .  j a  v a  2 s .c  o m
        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:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * This assumes that authentication is the last piece of info in handshake
 *///  w  w w. j a  va2  s  . com
public void writeCredentials(DataOutputStream dos, DataInputStream dis, Properties p_credentials,
        boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos)
        throws IOException, GemFireSecurityException {

    if (p_credentials == null) {
        // No credentials indicator
        heapdos.writeByte(CREDENTIALS_NONE);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }

    if (dhSKAlgo == null || dhSKAlgo.length() == 0) {
        // Normal credentials without encryption indicator
        heapdos.writeByte(CREDENTIALS_NORMAL);
        DataSerializer.writeProperties(p_credentials, heapdos);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }

    try {
        InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter();
        securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo);
        boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0);
        if (requireAuthentication) {
            securityLogWriter.fine("HandShake: server authentication using digital " + "signature required");
        }
        // Credentials with encryption indicator
        heapdos.writeByte(CREDENTIALS_DHENCRYPT);
        heapdos.writeBoolean(requireAuthentication);
        // Send the symmetric encryption algorithm name
        DataSerializer.writeString(dhSKAlgo, heapdos);
        // Send the DH public key
        byte[] keyBytes = dhPublicKey.getEncoded();
        DataSerializer.writeByteArray(keyBytes, heapdos);
        byte[] clientChallenge = null;
        if (requireAuthentication) {
            // Authentication of server should be with the client supplied
            // challenge
            clientChallenge = new byte[64];
            random.nextBytes(clientChallenge);
            DataSerializer.writeByteArray(clientChallenge, heapdos);
        }
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();

        // Expect the alias and signature in the reply
        byte acceptanceCode = dis.readByte();
        if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) {
            // Ignore the useless data
            dis.readByte();
            dis.readInt();
            if (!isNotification) {
                DataSerializer.readByteArray(dis);
            }
            readMessage(dis, dos, acceptanceCode, member);
        } else if (acceptanceCode == REPLY_OK) {
            // Get the public key of the other side
            keyBytes = DataSerializer.readByteArray(dis);
            if (requireAuthentication) {
                String subject = DataSerializer.readString(dis);
                byte[] signatureBytes = DataSerializer.readByteArray(dis);
                if (!certificateMap.containsKey(subject)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0
                                    .toLocalizedString(subject));
                }

                // Check the signature with the public key
                X509Certificate cert = (X509Certificate) certificateMap.get(subject);
                Signature sig = Signature.getInstance(cert.getSigAlgName());
                sig.initVerify(cert);
                sig.update(clientChallenge);
                // Check the challenge string
                if (!sig.verify(signatureBytes)) {
                    throw new AuthenticationFailedException(
                            "Mismatch in client " + "challenge bytes. Malicious server?");
                }
                securityLogWriter
                        .fine("HandShake: Successfully verified the " + "digital signature from server");
            }

            byte[] challenge = DataSerializer.readByteArray(dis);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFact = KeyFactory.getInstance("DH");
            // PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
            this.clientPublicKey = keyFact.generatePublic(x509KeySpec);

            HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
            try {
                DataSerializer.writeProperties(p_credentials, hdos);
                // Also add the challenge string
                DataSerializer.writeByteArray(challenge, hdos);

                // byte[] encBytes = encrypt.doFinal(hdos.toByteArray());
                byte[] encBytes = encryptBytes(hdos.toByteArray(),
                        getEncryptCipher(dhSKAlgo, this.clientPublicKey));
                DataSerializer.writeByteArray(encBytes, dos);
            } finally {
                hdos.close();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex);
    }
    dos.flush();
}

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  w w  w  .  j  av  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:org.openbravo.erpCommon.obps.ActivationKey.java

private PublicKey getPublicKey(String strPublickey) {
    try {//from  ww w .  j  a va2 s .  c om
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] rawPublicKey = org.apache.commons.codec.binary.Base64.decodeBase64(strPublickey.getBytes());

        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(rawPublicKey);
        return keyFactory.generatePublic(publicKeySpec);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }
}