Example usage for org.bouncycastle.util.io.pem PemReader readPemObject

List of usage examples for org.bouncycastle.util.io.pem PemReader readPemObject

Introduction

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

Prototype

public PemObject readPemObject() throws IOException 

Source Link

Document

Read the next PEM object as a blob of raw data with header information.

Usage

From source file:AAModulePackage.ACHelper.java

/**
 * Loads an AC from a given file/*from ww w  .  j  av  a2s. c o m*/
 * @param acFile - File that should contain an attribute certificate
 * @return X509AttributeCertificateHolder - the X.509 attribute certificate loaded from the file.
 */
public static X509AttributeCertificateHolder loadAttributeCertFromFile(File acFile) {
    PemReader reader = null;
    try {
        reader = new PemReader(new FileReader(acFile));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    X509AttributeCertificateHolder ac = null;
    try {
        ac = new X509AttributeCertificateHolder(reader.readPemObject().getContent());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ac;
}

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 w w w .  j av  a  2s.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  w w  . j  a  va 2s .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:beta01.CreateCertByCsr.java

public CreateCertByCsr() throws Exception {
    //read p12//from w  ww  . j a  v a 2 s. c  o m
    KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC");
    pkcs12Store.load(new FileInputStream("D:\\rootPrivateKey.p12"), "pass".toCharArray());

    //read root key pair and certificate
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    X509Certificate rootCert = null;
    for (Enumeration en = pkcs12Store.aliases(); en.hasMoreElements();) {
        String alias = (String) en.nextElement();
        if (pkcs12Store.isCertificateEntry(alias)) {
            rootCert = (X509Certificate) pkcs12Store.getCertificate(alias);
            Certificate cert = pkcs12Store.getCertificate(alias);
            publicKey = cert.getPublicKey();
        } else if (pkcs12Store.isKeyEntry(alias)) {
            privateKey = (PrivateKey) pkcs12Store.getKey(alias, "pass".toCharArray());
        }
    }
    //read CSR
    String fileName = "CSR_DSA";
    FileReader fileReader = new FileReader("D:\\" + fileName + ".p10");
    PemReader pemReader = new PemReader(fileReader);
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(pemReader.readPemObject().getContent());

    //create certf
    JcaX509CertificateHolder holder = new JcaX509CertificateHolder(rootCert);
    X509v3CertificateBuilder certBuilder;
    certBuilder = new X509v3CertificateBuilder(holder.getSubject(),
            BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000), csr.getSubject(),
            csr.getSubjectPublicKeyInfo());
    certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));

    SignatureAlgorithmIdentifierFinder algFinder = new DefaultSignatureAlgorithmIdentifierFinder();
    AlgorithmIdentifier sigAlg = algFinder.find("SHA512withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    //RSAPrivateKey rsa = (RSAPrivateKey) privateKey;
    //AsymmetricCipherKeyPair ss =new AsymmetricCipherKeyPair
    // RSAKeyParameters rsaP = new RSAPrivateCrtKeyParameters(rsa.getModulus(), rsa.getPublicExponent(), 
    // rsa.getPrivateExponent(), rsa., BigInteger.ONE, BigInteger.ONE, BigInteger.ONE, BigInteger.ONE);
    //ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build((AsymmetricKeyParameter) privateKey);

    // AsymmetricCipherKeyPair sd = new AsymmetricCipherKeyPair(null, null)

    ContentSigner signer = new JcaContentSignerBuilder("SHA512withRSA").setProvider("BC").build(privateKey);
    X509CertificateHolder holder2 = certBuilder.build(signer);
    new SimpleGenCert().converToPem(holder2, fileName);
}

From source file:CAModulePackage.CertificateHelper.java

/**
 * Load a Certificate Signing Request from the specified File.
 * Note: CSR will be a .PEM File.//from   www. j  a  v a 2  s  .  c om
 * @param csrFile
 * @return 
 */
public static PKCS10CertificationRequest loadCSRFromFile(File csrFile) {
    PemReader reader = null;
    PKCS10CertificationRequest req = null;
    try {
        reader = new PemReader(new FileReader(csrFile));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        req = new PKCS10CertificationRequest(reader.readPemObject().getContent());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return req;
}

From source file:CAModulePackage.CertificateHelper.java

/**
 * Also pretty basic. Load an X.509 Certificate from the .PEM
 * file specified.//from   w w w.j  a  v  a 2s. c o m
 * @param filename - full path name to the certificate to be loaded.
 * @return The certificate loaded from the designated file.
 */
public static X509CertificateHolder loadCertFromFile(String filename) {

    PemReader reader = null;
    X509CertificateHolder certificate = null;
    try {
        reader = new PemReader(new FileReader(new File(filename)));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        certificate = new X509CertificateHolder(reader.readPemObject().getContent());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return certificate;
}

From source file:CAModulePackage.CertificateHelper.java

/**
 * /*from   w ww.  j  a v  a 2 s  .com*/
 * @param certFile - file to load the cert from (PEM file)
 * @return The certificate loaded from the designated file.
 */
public static X509CertificateHolder loadCertFromFile(File certFile) {

    PemReader reader = null;
    X509CertificateHolder certificate = null;
    try {
        reader = new PemReader(new FileReader(certFile));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        certificate = new X509CertificateHolder(reader.readPemObject().getContent());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return certificate;
}

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

License:Open Source License

/** Chargement de la cle AU FORMAT pem
 * Alors ajouter la dpendance dans le fichier pom.xml :
 * <dependency>//w w  w .ja v  a 2s.c  om
*     <groupId>org.bouncycastle</groupId>
*     <artifactId>bcprov-jdk15on</artifactId>
*     <version>1.47</version>
*   </dependency>
*
* Ainsi que l'import : import org.bouncycastle.util.io.pem.PemReader;
 *
 * @param pubKeyFile
 * @return
 * @throws Exception
 */
private PublicKey getPubKey(String pubKeyPath) throws Exception {

    PemReader reader = new PemReader(new FileReader(pubKeyPath));

    byte[] pubKey = reader.readPemObject().getContent();

    reader.close();

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

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKey);

    return keyFactory.generatePublic(pubKeySpec);

}

From source file:com.datamountaineer.streamreactor.connect.coap.Server.java

License:Apache License

public static PrivateKey loadPrivateKey(String path) throws Exception {
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(path)));
    PKCS8EncodedKeySpec content = new PKCS8EncodedKeySpec(pemReader.readPemObject().getContent());
    return factory.generatePrivate(content);
}

From source file:com.datamountaineer.streamreactor.connect.coap.Server.java

License:Apache License

public static PublicKey loadPublicKey(String path) throws Exception {
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(path)));
    X509EncodedKeySpec content = new X509EncodedKeySpec(pemReader.readPemObject().getContent());
    return factory.generatePublic(content);
}