Example usage for org.bouncycastle.util.io.pem PemObject getContent

List of usage examples for org.bouncycastle.util.io.pem PemObject getContent

Introduction

In this page you can find the example usage for org.bouncycastle.util.io.pem PemObject getContent.

Prototype

public byte[] getContent() 

Source Link

Usage

From source file:ai.susi.server.api.aaa.PublicKeyRegistrationService.java

License:Open Source License

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) {
        throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'");
    }/*from  www .j  a v  a2 s  .co m*/

    JSONObject result = new JSONObject();

    // return algorithm parameters and users for whom we are allowed to register a key
    if (post.get("getParameters", false)) {
        result.put("self", permissions.getBoolean("self", false));
        result.put("users", permissions.getJSONObject("users"));
        result.put("userRoles", permissions.getJSONObject("userRoles"));

        JSONObject algorithms = new JSONObject();

        JSONObject rsa = new JSONObject();
        JSONArray keySizes = new JSONArray();
        for (int i : allowedKeySizesRSA) {
            keySizes.put(i);
        }
        rsa.put("sizes", keySizes);
        rsa.put("defaultSize", defaultKeySizeRSA);
        algorithms.put("RSA", rsa);
        result.put("algorithms", algorithms);

        JSONArray formats = new JSONArray();
        for (String format : allowedFormats) {
            formats.put(format);
        }
        result.put("formats", formats);

        return result;
    }

    // for which id?
    String id;
    if (post.get("id", null) != null)
        id = post.get("id", null);
    else
        id = authorization.getIdentity().getName();

    // check if we are allowed register a key
    if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user

        // create Authentication to check if the user id is a registered user
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() == null) { // check if identity is valid
            authentication.delete();
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
        }

        // check if the current user is allowed to create a key for the user in question
        boolean allowed = false;
        // check if the user in question is in 'users'
        if (permissions.getJSONObject("users", null).has(id)
                && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) {
            allowed = true;
        } else { // check if the user role of the user in question is in 'userRoles'
            Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization,
                    DAO.userRoles);
            for (String key : permissions.getJSONObject("userRoles").keySet()) {
                if (key.equals(auth.getUserRole().getName())
                        && permissions.getJSONObject("userRoles").getBoolean(key)) {
                    allowed = true;
                }
            }
        }
        if (!allowed)
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
    } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users)
        if (!permissions.getBoolean("self", false))
            throw new APIException(403, "You are not allowed to register a public key");
    }

    // set algorithm. later, we maybe want to support other algorithms as well
    String algorithm = "RSA";
    if (post.get("algorithm", null) != null) {
        algorithm = post.get("algorithm", null);
    }

    if (post.get("create", false)) { // create a new key pair on the server

        if (algorithm.equals("RSA")) {
            int keySize = 2048;
            if (post.get("key-size", null) != null) {
                int finalKeyLength = post.get("key-size", 0);
                if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) {
                    throw new APIException(400, "Invalid key size.");
                }
                keySize = finalKeyLength;
            }

            KeyPairGenerator keyGen;
            KeyPair keyPair;
            try {
                keyGen = KeyPairGenerator.getInstance(algorithm);
                keyGen.initialize(keySize);
                keyPair = keyGen.genKeyPair();
            } catch (NoSuchAlgorithmException e) {
                throw new APIException(500, "Server error");
            }

            registerKey(authorization.getIdentity(), keyPair.getPublic());

            String pubkey_pem = null, privkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                privkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            result.put("privatekey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("privatekey_PEM", privkey_pem);
            result.put("keyhash", IO.getKeyHash(keyPair.getPublic()));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("key-size", keySize);
            result.put("message",
                    "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    } else if (post.get("register", null) != null) {

        if (algorithm.equals("RSA")) {
            String type = post.get("type", null);
            if (type == null)
                type = "DER";

            RSAPublicKey pub;
            String encodedKey;
            try {
                encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8");
            } catch (Throwable e) {
                throw new APIException(500, "Server error");
            }
            Log.getLog().info("Key (" + type + "): " + encodedKey);

            if (type.equals("DER")) {
                try {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Throwable e) {
                    throw new APIException(400, "Public key not readable (DER)");
                }
            } else if (type.equals("PEM")) {
                try {
                    PemReader pemReader = new PemReader(new StringReader(encodedKey));
                    PemObject pem = pemReader.readPemObject();
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent());
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Exception e) {
                    throw new APIException(400, "Public key not readable (PEM)");
                }
            } else {
                throw new APIException(400, "Invalid value for 'type'.");
            }

            // check key size (not really perfect yet)
            int keySize;
            int bitLength = pub.getModulus().bitLength();
            if (bitLength <= 512) {
                keySize = 512;
            } else if (bitLength <= 1024) {
                keySize = 1024;
            } else if (bitLength <= 2048) {
                keySize = 2048;
            } else if (bitLength <= 4096) {
                keySize = 4096;
            } else {
                keySize = 8192;
            }
            if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) {
                throw new APIException(400, "Invalid key length.");
            }

            registerKey(authorization.getIdentity(), pub);

            String pubkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("keyhash", IO.getKeyHash(pub));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("message", "Successfully registered key.");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    }

    throw new APIException(400, "Invalid parameter");
}

From source file:be.fedict.trust.BelgianTrustValidatorFactory.java

License:Open Source License

private static X509Certificate loadPemCertificate(String pemResourceName) {
    CertificateFactory certificateFactory;
    try {//from   w ww .  j  a  v  a2  s . c  o m
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("X.509 factory error: " + e.getMessage(), e);
    }
    Thread currentThread = Thread.currentThread();
    ClassLoader classLoader = currentThread.getContextClassLoader();
    InputStream certificateInputStream = classLoader.getResourceAsStream(pemResourceName);
    if (null == certificateInputStream) {
        throw new IllegalArgumentException("resource not found: " + pemResourceName);
    }
    PemReader pemReader = new PemReader(new InputStreamReader(certificateInputStream));
    try {
        try {
            PemObject pemObject;
            pemObject = pemReader.readPemObject();
            X509Certificate certificate = (X509Certificate) certificateFactory
                    .generateCertificate(new ByteArrayInputStream(pemObject.getContent()));
            return certificate;
        } finally {
            pemReader.close();
        }
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    } catch (CertificateException e) {
        throw new RuntimeException("cert error: " + e.getMessage(), e);
    }
}

From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java

License:Apache License

private SSLSocketFactory getSocketFactoryFromPEM(String filePath) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    PEMParser pemParser = new PEMParser(new FileReader(getConfigFilename(filePath)));
    pemParser.readObject();//from  www . j a  va2 s  . com
    PemObject pemObject = pemParser.readPemObject();
    pemParser.close();

    X509CertificateHolder holder = new X509CertificateHolder(pemObject.getContent());
    X509Certificate bc = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", bc);

    TrustManager trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore);
    SSLContext sslContext = SSLContextUtils.createSSLContext("TLS", null, trustManager);

    return sslContext.getSocketFactory();
}

From source file:com.foilen.smalltools.crypt.bouncycastle.asymmetric.RSACrypt.java

License:Open Source License

@Override
public AsymmetricKeys loadKeysPemFromString(String... pems) {
    RSAKeyDetails keyDetails = new RSAKeyDetails();
    PemReader reader = null;//from   w w  w  . ja v  a  2s .c om
    try {
        for (String pem : pems) {
            if (pem == null) {
                continue;
            }
            reader = new PemReader(new StringReader(pem));
            PemObject pemObject;
            while ((pemObject = reader.readPemObject()) != null) {
                switch (pemObject.getType()) {
                case "RSA PRIVATE KEY":
                    RSAPrivateKey rsaPrivateKey = RSAPrivateKey.getInstance(pemObject.getContent());
                    keyDetails.setModulus(rsaPrivateKey.getModulus());
                    keyDetails.setPrivateExponent(rsaPrivateKey.getPrivateExponent());
                    keyDetails.setPublicExponent(rsaPrivateKey.getPublicExponent());

                    if (CollectionsTools.isAnyItemNotNull(rsaPrivateKey.getPrime1(), rsaPrivateKey.getPrime2(),
                            rsaPrivateKey.getExponent1(), rsaPrivateKey.getExponent2(),
                            rsaPrivateKey.getCoefficient())) {
                        keyDetails.setCrt(true);
                        keyDetails.setPrimeP(rsaPrivateKey.getPrime1());
                        keyDetails.setPrimeQ(rsaPrivateKey.getPrime2());
                        keyDetails.setPrimeExponentP(rsaPrivateKey.getExponent1());
                        keyDetails.setPrimeExponentQ(rsaPrivateKey.getExponent2());
                        keyDetails.setCrtCoefficient(rsaPrivateKey.getCoefficient());
                    }
                    break;
                case "PUBLIC KEY":
                    KeyFactory kf = KeyFactory.getInstance("RSA");
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pemObject.getContent());
                    RSAPublicKey rsaPublicKey = (RSAPublicKey) kf.generatePublic(keySpec);
                    keyDetails.setModulus(rsaPublicKey.getModulus());
                    keyDetails.setPublicExponent(rsaPublicKey.getPublicExponent());
                    break;
                }
            }
        }
        return createKeyPair(keyDetails);
    } catch (Exception e) {
        throw new SmallToolsException("Problem loading the keys", e);
    } finally {
        CloseableTools.close(reader);
    }
}

From source file:com.foilen.smalltools.crypt.bouncycastle.cert.RSACertificate.java

License:Open Source License

/**
 * Load the certificate and keys (if present in the strings).
 *
 * @param pems//w  ww  .j  a  va  2 s .  co  m
 *            the pems (some can be null)
 * @return the certificate
 */
public static RSACertificate loadPemFromString(String... pems) {
    RSACertificate certificate = new RSACertificate();
    PemReader pemReader = null;
    try {
        // Keys if present
        certificate.keysForSigning = rsaCrypt.loadKeysPemFromString(pems);

        // Certificate
        for (String pem : pems) {
            if (pem == null) {
                continue;
            }
            pemReader = new PemReader(new StringReader(pem));
            PemObject pemObject;
            while ((pemObject = pemReader.readPemObject()) != null) {
                if ("CERTIFICATE".equals(pemObject.getType())) {
                    certificate.certificateHolder = new X509CertificateHolder(pemObject.getContent());
                }
            }
        }

        return certificate;
    } catch (Exception e) {
        throw new SmallToolsException("Problem loading the certificate", e);
    } finally {
        CloseableTools.close(pemReader);
    }

}

From source file:com.foilen.smalltools.crypt.bouncycastle.cert.RSATrustedCertificates.java

License:Open Source License

private void addToList(Map<X500Name, List<RSACertificate>> certificatesBySubject, String filePath) {

    PemReader reader = null;/*ww w . java  2 s  .  c om*/
    try {
        // Certificate
        reader = new PemReader(new FileReader(filePath));
        PemObject pemObject;
        while ((pemObject = reader.readPemObject()) != null) {
            if ("CERTIFICATE".equals(pemObject.getType())) {
                RSACertificate rsaCertificate = new RSACertificate();
                rsaCertificate.setCertificateHolder(new X509CertificateHolder(pemObject.getContent()));

                addToList(certificatesBySubject, rsaCertificate);
            }
        }
    } catch (Exception e) {
        throw new SmallToolsException("Problem loading the certificates", e);
    } finally {
        CloseableTools.close(reader);
    }

}

From source file:com.github.autermann.sockets.ssl.SSLUtils.java

License:Apache License

private static PrivateKey createPrivateKey(PemObject privatePemObject)
        throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
    AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
    RSAPrivateKey instance = RSAPrivateKey.getInstance(privatePemObject.getContent());
    PrivateKeyInfo privateKeyInfo = new PrivateKeyInfo(algId, instance);
    return createKeyFromDER(privateKeyInfo.toASN1Primitive().getEncoded());
}

From source file:com.github.ibole.infrastructure.security.key.PemUtils.java

License:Apache License

private static byte[] parsePEMFile(File pemFile) throws IOException {
    if (!pemFile.isFile() || !pemFile.exists()) {
        throw new FileNotFoundException(
                String.format("The file '%s' doesn't exist.", pemFile.getAbsolutePath()));
    }//from  w  w w .ja  v  a  2s. c  o  m
    PemReader reader = null;
    PemObject pemObject;
    try {
        reader = new PemReader(new FileReader(pemFile));
        pemObject = reader.readPemObject();
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return pemObject.getContent();
}

From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java

License:Apache License

public String rsaEncryptPassword(String publicKeyInPEM, String password) {
    String encrypted = "";
    try {//from w  ww  . java  2s . co m
        RSAKeyParameters rsaPublicKey;
        Reader reader = new StringReader(publicKeyInPEM);
        PemObject pemObj = new PemReader(reader).readPemObject();

        rsaPublicKey = (RSAKeyParameters) PublicKeyFactory.createKey(pemObj.getContent());

        byte[] bytesToEncrypt = password.getBytes(Charset.forName("UTF-8"));

        PKCS1Encoding encryptEngine = new PKCS1Encoding(new RSAEngine());
        encryptEngine.init(true, rsaPublicKey);
        encrypted = new String(
                Base64.encode(encryptEngine.processBlock(bytesToEncrypt, 0, bytesToEncrypt.length)),
                Charset.forName("UTF-8"));

    } catch (Exception ex) {
        logger.severe(" Failure attempting to encrypt via RSA.  \r\n PublicKeyInPEM:" + publicKeyInPEM
                + "\r\n Exception : " + ex.toString());
        throw new RuntimeException(
                " Failure attempting to encrypt the RSA encrypted password. See Interface log for more details. Message : "
                        + ex.getMessage());
    }
    return encrypted;

}

From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java

License:Apache License

public String rsaDecryptPassword(String PrivateKeyInPEM, String Base64Encrypted) {
    String decrypted = "";
    try {//from   w  w w  .j  a  v a 2 s  .  c om
        RSAKeyParameters rsaprivateKey;

        Reader reader = new StringReader(PrivateKeyInPEM);
        PemObject pemObj = new PemReader(reader).readPemObject();

        rsaprivateKey = (RSAKeyParameters) PrivateKeyFactory.createKey(pemObj.getContent());

        byte[] bytesToDecrypt = Base64.decode(Base64Encrypted);
        //byte[] bytesToDecrypt = Convert.FromBase64String(Base64Encrypted);

        PKCS1Encoding decryptEngine = new PKCS1Encoding(new RSAEngine());
        decryptEngine.init(false, rsaprivateKey);
        decrypted = new String(decryptEngine.processBlock(bytesToDecrypt, 0, bytesToDecrypt.length),
                Charset.forName("UTF-8"));
        //decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));

    } catch (Exception ex) {
        //Without logging the private key lets get some info to make sure it looks like it could be a proper private key.
        String private_key_message = " Private key ";
        if (PrivateKeyInPEM.indexOf("----BEGIN PRIVATE KEY----") > 0) {
            private_key_message += " Has '----BEGIN PRIVATE KEY----' at pos "
                    + PrivateKeyInPEM.indexOf("----BEGIN PRIVATE KEY----");
        }
        if (PrivateKeyInPEM.indexOf("----END PRIVATE KEY----") > 0) {
            private_key_message += " Has '----END PRIVATE KEY----' at pos "
                    + PrivateKeyInPEM.indexOf("----END PRIVATE KEY----");
        }
        private_key_message += " Length : " + PrivateKeyInPEM.length();

        logger.log(Level.SEVERE,
                " Failure attempting to decrypt via RSA. \r\n Base64Encrypted string : " + Base64Encrypted
                        + " \r\n PrivateKeyInPEM " + private_key_message + " \r\n Exception : " + ex.toString(),
                ex);
        throw new RuntimeException(
                " Failure attempting to encrypt the RSA encrypted password. See Interface log for more details. Message : "
                        + ex.getMessage());
    }
    return decrypted.toString();
}