/** * Returns the encoded form of this certification path, using the specified encoding. * * @param encoding the name of the encoding to use * @return the encoded bytes * @exception java.security.cert.CertificateEncodingException if an encoding error occurs or the * encoding requested is not supported */ public byte[] getEncoded(String encoding) throws CertificateEncodingException { if (encoding.equalsIgnoreCase("PkiPath")) { ASN1EncodableVector v = new ASN1EncodableVector(); ListIterator iter = certificates.listIterator(certificates.size()); while (iter.hasPrevious()) { v.add(toASN1Object((X509Certificate) iter.previous())); } return toDEREncoded(new DERSequence(v)); } else if (encoding.equalsIgnoreCase("PKCS7")) { ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null); ASN1EncodableVector v = new ASN1EncodableVector(); for (int i = 0; i != certificates.size(); i++) { v.add(toASN1Object((X509Certificate) certificates.get(i))); } SignedData sd = new SignedData( new ASN1Integer(1), new DERSet(), encInfo, new DERSet(v), null, new DERSet()); return toDEREncoded(new ContentInfo(PKCSObjectIdentifiers.signedData, sd)); } else if (encoding.equalsIgnoreCase("PEM")) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut)); try { for (int i = 0; i != certificates.size(); i++) { pWrt.writeObject( new PemObject("CERTIFICATE", ((X509Certificate) certificates.get(i)).getEncoded())); } pWrt.close(); } catch (Exception e) { throw new CertificateEncodingException("can't encode certificate for PEM encoded path"); } return bOut.toByteArray(); } else { throw new CertificateEncodingException("unsupported encoding: " + encoding); } }
@Security.Authenticated(SignedIn.class) public Result generateKey(String applicationId) throws IOException { Logger.info(String.format("Generating new key pair for %s", applicationId)); KeyPair keyPair = keyPairGenerator.genKeyPair(); Application app = Application.find.byId(applicationId); app.key = keyPair.getPublic().getEncoded(); app.save(); String filename = "privatekey-" + applicationId + ".pem"; String filepath = "generated_keys/" + filename; File pemfile = new File(filepath); pemfile.getParentFile().mkdirs(); PemObject pemObject = new PemObject(PEM_FILE_HEADER, keyPair.getPrivate().getEncoded()); PemWriter writer = new PemWriter(new FileWriter(pemfile)); writer.writeObject(pemObject); writer.flush(); writer.close(); response().setContentType("application/x-download"); response().setHeader("Content-disposition", "attachment; filename=" + filename); return ok(pemfile); }