Example usage for java.security.cert CertificateEncodingException printStackTrace

List of usage examples for java.security.cert CertificateEncodingException printStackTrace

Introduction

In this page you can find the example usage for java.security.cert CertificateEncodingException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:at.asitplus.regkassen.demo.RKSVCashboxSimulator.java

public static void main(String[] args) {
    try {//from  w ww  .j a v  a 2s . c  o  m
        //IMPORTANT HINT REGARDING STRING ENCODING
        //in Java all Strings have UTF-8 as default encoding
        //therefore: there are only a few references to UTF-8 encoding in this demo code
        //however, if values are retrieved from a database or another program language is used, then one needs to
        //make sure that the UTF-8 encoding is correctly implemented

        //this demo cashbox does not implement error handling
        //it should only demonstrate the core elements of the RKSV and any boilerplate code is avoided as much as possible
        //if an error occurs, only the stacktraces are logged
        //obviously this needs to be adapted in a productive cashbox

        //----------------------------------------------------------------------------------------------------
        //basic inits
        //add bouncycastle provider
        Security.addProvider(new BouncyCastleProvider());

        //----------------------------------------------------------------------------------------------------
        //check if unlimited strength policy files are installed, they are required for strong crypto algorithms ==> AES 256
        if (!CryptoUtil.isUnlimitedStrengthPolicyAvailable()) {
            System.out.println(
                    "Your JVM does not provide the unlimited strength policy. However, this policy is required to enable strong cryptography (e.g. AES with 256 bits). Please install the required policy files.");
            System.exit(0);
        }

        //----------------------------------------------------------------------------------------------------
        //parse cmd line options
        Options options = new Options();

        // add CMD line options
        options.addOption("o", "output-dir", true,
                "specify base output directory, if none is specified, a new directory will be created in the current working directory");
        //options.addOption("i", "simulation-file-or-directory", true, "cashbox simulation (file) or multiple cashbox simulation files (directory), if none is specified the internal test suites will be executed (can also be considered as demo mode)");
        options.addOption("v", "verbose", false, "dump demo receipts to cmd line");
        options.addOption("c", "closed system", false, "simulate closed system");

        ///parse CMD line options
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        //setup inputs from cmd line
        //verbose
        VERBOSE = cmd.hasOption("v");
        CLOSED_SYSTEM = cmd.hasOption("c");

        //output directory
        String outputParentDirectoryString = cmd.getOptionValue("o");
        if (outputParentDirectoryString == null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
            outputParentDirectoryString = "./CashBoxDemoOutput" + df.format(new Date());
        }
        File OUTPUT_PARENT_DIRECTORY = new File(outputParentDirectoryString);
        OUTPUT_PARENT_DIRECTORY.mkdirs();

        //----------------------------------------------------------------------------------------------------
        //external simulation runs... not implemented yet, currently only the internal test suites can be executed
        //String simulationFileOrDirectoryPath = cmd.getOptionValue("i");
        //handling of arbitrary input simulation files will be possible in 0.7
        //if (simulationFileOrDirectoryPath == null) {
        //} else {
        //                File simulationFileOrDirectory = new File(simulationFileOrDirectoryPath);
        //                cashBoxSimulationList = readCashBoxSimulationFromFile(simulationFileOrDirectory);
        //}

        List<CashBoxSimulation> cashBoxSimulationList = TestSuiteGenerator.getSimulationRuns();

        //setup simulation and execute
        int index = 1;
        for (CashBoxSimulation cashboxSimulation : cashBoxSimulationList) {
            System.out.println("Executing simulation run " + index + "/" + cashBoxSimulationList.size());
            System.out.println("Simulation run: " + cashboxSimulation.getSimulationRunLabel());
            index++;

            File testSetDirectory = new File(OUTPUT_PARENT_DIRECTORY,
                    cashboxSimulation.getSimulationRunLabel());
            testSetDirectory.mkdirs();

            CashBoxParameters cashBoxParameters = new CashBoxParameters();
            cashBoxParameters.setCashBoxId(cashboxSimulation.getCashBoxId());
            cashBoxParameters.setTurnOverCounterAESKey(
                    CryptoUtil.convertBase64KeyToSecretKey(cashboxSimulation.getBase64AesKey()));
            cashBoxParameters.setDepModul(new SimpleMemoryDEPModule());
            cashBoxParameters.setPrinterModule(new SimplePDFPrinterModule());
            cashBoxParameters.setCompanyID(cashboxSimulation.getCompanyID());

            //create pre-defined number of signature devices
            for (int i = 0; i < cashboxSimulation.getNumberOfSignatureDevices(); i++) {
                JWSModule jwsModule = new ManualJWSModule();
                SignatureModule signatureModule;
                if (!CLOSED_SYSTEM) {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule(
                            RKSuite.R1_AT100, null);
                } else {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareKeySignatureModule(
                            cashboxSimulation.getCompanyID() + "-" + "K" + i);
                }
                jwsModule.setOpenSystemSignatureModule(signatureModule);
                cashBoxParameters.getJwsSignatureModules().add(jwsModule);
            }

            //init cashbox
            DemoCashBox demoCashBox = new DemoCashBox(cashBoxParameters);

            //exceute simulation run
            demoCashBox.executeSimulation(cashboxSimulation.getCashBoxInstructionList());

            //----------------------------------------------------------------------------------------------------
            //export DEP
            DEPExportFormat depExportFormat = demoCashBox.exportDEP();
            //get JSON rep and dump export format to file/std output
            File depExportFile = new File(testSetDirectory, "dep-export.json");
            dumpJSONRepOfObject(depExportFormat, depExportFile, true,
                    "------------DEP-EXPORT-FORMAT------------");

            //----------------------------------------------------------------------------------------------------
            //store signature certificates and AES key (so that they can be used for verification purposes)
            CryptographicMaterialContainer cryptographicMaterialContainer = new CryptographicMaterialContainer();
            HashMap<String, CertificateOrPublicKeyContainer> certificateContainerMap = new HashMap<>();
            cryptographicMaterialContainer.setCertificateOrPublicKeyMap(certificateContainerMap);

            //store AES key as BASE64 String
            //ATTENTION, this is only for demonstration purposes, the AES key must be stored in a secure location
            cryptographicMaterialContainer.setBase64AESKey(cashboxSimulation.getBase64AesKey());
            List<JWSModule> jwsSignatureModules = demoCashBox.getCashBoxParameters().getJwsSignatureModules();
            for (JWSModule jwsSignatureModule : jwsSignatureModules) {
                CertificateOrPublicKeyContainer certificateOrPublicKeyContainer = new CertificateOrPublicKeyContainer();
                certificateOrPublicKeyContainer.setId(jwsSignatureModule.getSerialNumberOfKeyID());
                certificateContainerMap.put(jwsSignatureModule.getSerialNumberOfKeyID(),
                        certificateOrPublicKeyContainer);
                X509Certificate certificate = (X509Certificate) jwsSignatureModule.getSignatureModule()
                        .getSigningCertificate();
                if (certificate == null) {
                    //must be public key based... (closed system)
                    PublicKey publicKey = jwsSignatureModule.getSignatureModule().getSigningPublicKey();
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(publicKey.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.PUBLIC_KEY);
                } else {
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(certificate.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.CERTIFICATE);
                }
            }

            File cryptographicMaterialContainerFile = new File(testSetDirectory,
                    "cryptographicMaterialContainer.json");
            dumpJSONRepOfObject(cryptographicMaterialContainer, cryptographicMaterialContainerFile, true,
                    "------------CRYPTOGRAPHIC MATERIAL------------");

            //----------------------------------------------------------------------------------------------------
            //export QR codes to file
            //dump machine readable code of receipts (this "code" is used for the QR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            //dump to File
            File qrCoreRepExportFile = new File(testSetDirectory, "qr-code-rep.json");
            List<ReceiptPackage> receiptPackages = demoCashBox.getStoredReceipts();
            List<String> qrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                qrCodeRepList.add(CashBoxUtils.getQRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(qrCodeRepList, qrCoreRepExportFile, true,
                    "------------QR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //export OCR codes to file
            //dump machine readable code of receipts (this "code" is used for the OCR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            //dump to File
            File ocrCoreRepExportFile = new File(testSetDirectory, "ocr-code-rep.json");
            List<String> ocrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                ocrCodeRepList.add(CashBoxUtils.getOCRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(ocrCodeRepList, ocrCoreRepExportFile, true,
                    "------------OCR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //create PDF receipts and print to directory
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            File qrCodeDumpDirectory = new File(testSetDirectory, "qr-code-dir-pdf");
            qrCodeDumpDirectory.mkdirs();
            List<byte[]> printedQRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.QR_CODE);
            CashBoxUtils.writeReceiptsToFiles(printedQRCodeReceipts, "QR-", qrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //export receipts as PDF (OCR)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            File ocrCodeDumpDirectory = new File(testSetDirectory, "ocr-code-dir-pdf");
            ocrCodeDumpDirectory.mkdirs();
            List<byte[]> printedOCRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.OCR);
            CashBoxUtils.writeReceiptsToFiles(printedOCRCodeReceipts, "OCR-", ocrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //dump executed testsuite
            File testSuiteDumpFile = new File(testSetDirectory,
                    cashboxSimulation.getSimulationRunLabel() + ".json");
            dumpJSONRepOfObject(cashboxSimulation, testSuiteDumpFile, true,
                    "------------CASHBOX Simulation------------");
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java

static private String getCertificateFingerprint(X509Certificate certificate, String algorithm) {
    byte[] digest = null;
    try {/*from  w w w . j  a va  2s . co  m*/
        byte[] certificateBytes = certificate.getEncoded();
        MessageDigest md = MessageDigest.getInstance(algorithm);
        md.update(certificateBytes);
        digest = md.digest();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return new String(algorithm + ": " + byteArrayToHex(digest));
}

From source file:com.connectsdk.service.config.WebOSTVServiceConfig.java

private String exportCertificateToPEM(X509Certificate cert) {
    try {//from w  w w . j  a v  a  2  s.  c om
        if (cert == null)
            return null;
        return Base64.encodeToString(cert.getEncoded(), Base64.DEFAULT);
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.persistent.cloudninja.controller.CloudNinjaAuthFilter.java

/**
 * This method filters every incoming request.
 * If request contains cookie, it checks whether the cookie is valid.
 *    A. If request cookie is present and is valid, forwards the request 
 *          to next page.//from  www . ja  v  a 2s .  c  o m
 *    B. If cookie is not valid and request is not coming from ACS, this
 *          method redirects the request to ACS login page.
 * If request does not contain a cookie, but contains an ACS token,
 * this method, creates or updates cookie and 
 * forwards the request to landing page.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    // capture ACS response
    String acsToken = httpServletRequest.getParameter("wresult");
    if (null != acsToken && acsToken.trim().length() == 0) {
        acsToken = null;
    }
    String isEncodedWresult = httpServletRequest.getParameter("isEncodedWresult");
    String decodedTokenString = null;
    if (null != acsToken && null != isEncodedWresult && isEncodedWresult.trim().equalsIgnoreCase("true")) {
        decodedTokenString = new String(URLDecoder.decode(acsToken, "UTF-8"));
        acsToken = decodedTokenString;
    }

    // by pass the url access validation validateInvitationCode
    if (httpServletRequest.getRequestURI().contains("/validateInvitationCode")) {
        request.getRequestDispatcher("/validateInvitationCode.htm").forward(httpServletRequest,
                httpServletResponse);
    } else {

        CloudNinjaUser cloudNinjaUser = null;

        boolean isValidCookiePresent = false;
        String cookieName = CloudNinjaConstants.AUTH_COOKIE_NAME;

        Cookie preExistentCookie = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, cookieName);

        if (preExistentCookie != null && StringUtils.isNotBlank(preExistentCookie.getValue())) {
            isValidCookiePresent = AuthFilterUtils.checkValidityOfCookie(preExistentCookie);
        }

        if (isValidCookiePresent) {
            Cookie cookieToUse = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, cookieName);
            cookieToUse.setPath("/");
            httpServletResponse.addCookie(cookieToUse);

            // Add cookie userNames, etc to request attributes
            httpServletRequest.setAttribute("cookieNameAttr", cookieToUse.getValue());

            forwardToNextPage(httpServletRequest, httpServletResponse, chain);
        } else if (!isValidCookiePresent && (acsToken == null)) {
            redirectToACSPage(httpServletRequest, httpServletResponse);
            return;
        } else if (acsToken != null) {

            acsToken = new String(acsToken.getBytes(), CloudNinjaConstants.UTF_8_FORMAT);
            boolean isValidCertificate = AuthFilterUtils.checkCertificateValidity(acsToken);
            if (!isValidCertificate) {
                redirectToACSPage(httpServletRequest, httpServletResponse);
                return;
            }

            try {
                cloudNinjaUser = parseSAMLResponseAndCreateCNUser(acsToken);
            } catch (CertificateEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            String liveGuid = null;

            //  GUID is present and user is null it means that user is from windowsLiveId
            // and is login-in in for the first time so we need to ask for verification code
            if (cloudNinjaUser != null && cloudNinjaUser.getUser() == null) {
                liveGuid = cloudNinjaUser.getLiveGUID();
                cloudNinjaUser = null;
                forwardToVerificationPage(httpServletRequest, httpServletResponse, liveGuid, acsToken);
                return;
            }
            // if user is null and no GUID is present
            // redirect to ACS page

            if (null == cloudNinjaUser) {
                redirectToACSPage(httpServletRequest, httpServletResponse);
                return;
            }

            Cookie cookieToUse;
            if (preExistentCookie == null) {
                cookieToUse = AuthFilterUtils.createNewCookieForACSAuthenticatedUser(cloudNinjaUser,
                        cookieName);
            } else {
                cookieToUse = AuthFilterUtils.updateExistingCookie(preExistentCookie, cloudNinjaUser);
            }
            cookieToUse.setMaxAge(getCookieMaxAge());
            cookieToUse.setPath("/");
            httpServletResponse.addCookie(cookieToUse);
            httpServletRequest.setAttribute("cookieNameAttr", cookieToUse.getValue());

            forwardToLandingPage(httpServletRequest, httpServletResponse, chain, cloudNinjaUser);
        }
    }
}

From source file:org.strongswan.android.logic.CharonVpnService.java

/**
 * Function called via JNI to generate a list of DER encoded CA certificates
 * as byte array.//ww w  .j a  va  2  s . c o  m
 *
 * @return a list of DER encoded CA certificates
 */
private byte[][] getTrustedCertificates() {
    ArrayList<byte[]> certs = new ArrayList<byte[]>();
    TrustedCertificateManager certman = TrustedCertificateManager.getInstance().load();
    try {
        String alias = this.mCurrentCertificateAlias;
        if (alias != null) {
            X509Certificate cert = certman.getCACertificateFromAlias(alias);
            if (cert == null) {
                return null;
            }
            certs.add(cert.getEncoded());
        } else {
            for (X509Certificate cert : certman.getAllCACertificates().values()) {
                certs.add(cert.getEncoded());
            }
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        return null;
    }
    return certs.toArray(new byte[certs.size()][]);
}

From source file:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * Saves and accepts a x509 certificate.
 * @param cert/*from w w w.j  a  va  2s. c  om*/
 */
private void saveAndAcceptCert(X509Certificate cert) {
    String certificate = null;
    try {
        certificate = Base64.encodeToString(cert.getEncoded(), Base64.DEFAULT);
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
    connection.setSshHostKey(certificate);
    connection.save(database.getWritableDatabase());
    database.close();
    // Indicate the certificate was accepted.
    certificateAccepted = true;
    synchronized (RemoteCanvas.this) {
        RemoteCanvas.this.notifyAll();
    }
}

From source file:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * If there is a saved cert, checks the one given against it. If a signature was passed in
 * and no saved cert, then check that signature. Otherwise, presents the
 * given cert's signature to the user for approval.
 * /*from   w  w w  .  j  a  v  a  2s  . c o m*/
 * The saved data must always win over any passed-in URI data
 * 
 * @param cert the given cert.
 */
private void validateX509Cert(final X509Certificate cert) {

    boolean certMismatch = false;

    int hashAlg = connection.getIdHashAlgorithm();
    byte[] certData = null;
    boolean isSigEqual = false;
    try {
        certData = cert.getEncoded();
        isSigEqual = SecureTunnel.isSignatureEqual(hashAlg, connection.getIdHash(), certData);
    } catch (Exception ex) {
        ex.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
        return;
    }

    // If there is no saved cert, then if a signature was provided,
    // check the signature and save the cert if the signature matches.
    if (connection.getSshHostKey().equals("")) {
        if (!connection.getIdHash().equals("")) {
            if (isSigEqual) {
                Log.i(TAG, "Certificate validated from URI data.");
                saveAndAcceptCert(cert);
                return;
            } else {
                certMismatch = true;
            }
        }
        // If there is a saved cert, check against it.
    } else if (connection.getSshHostKey().equals(Base64.encodeToString(certData, Base64.DEFAULT))) {
        Log.i(TAG, "Certificate validated from saved key.");
        saveAndAcceptCert(cert);
        return;
    } else {
        certMismatch = true;
    }

    // Show a dialog with the key signature for approval.
    DialogInterface.OnClickListener signatureNo = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // We were told not to continue, so stop the activity
            Log.i(TAG, "Certificate rejected by user.");
            closeConnection();
            ((Activity) getContext()).finish();
        }
    };
    DialogInterface.OnClickListener signatureYes = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.i(TAG, "Certificate accepted by user.");
            saveAndAcceptCert(cert);
        }
    };

    // Display dialog to user with cert info and hash.
    try {
        // First build the message. If there was a mismatch, prepend a warning about it.
        String message = "";
        if (certMismatch) {
            message = getContext().getString(R.string.warning_cert_does_not_match) + "\n\n";
        }
        byte[] certBytes = cert.getEncoded();
        String certIdHash = SecureTunnel.computeSignatureByAlgorithm(hashAlg, certBytes);
        String certInfo = String.format(Locale.US, getContext().getString(R.string.info_cert_tunnel),
                certIdHash, cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName(),
                cert.getNotBefore(), cert.getNotAfter());
        certInfo = message + certInfo.replace(",", "\n");

        // Actually display the message
        Utils.showYesNoPrompt(getContext(),
                getContext().getString(R.string.info_continue_connecting) + connection.getAddress() + "?",
                certInfo, signatureYes, signatureNo);
    } catch (NoSuchAlgorithmException e2) {
        e2.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
}

From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java

/**
 * Create an Amazon IAM account with a password, a secret key and member of
 * "Admins". The password, access key and secret key are sent by email.
 * //w w  w  .  j  a  v a 2s .  c om
 * @param userName
 *            valid email used as userName of the created account.
 */
public void createUsers(String userName) {

    CreateUserRequest createUserRequest = new CreateUserRequest(userName);
    CreateUserResult createUserResult = iam.createUser(createUserRequest);
    User user = createUserResult.getUser();

    String password = RandomStringUtils.randomAlphanumeric(8);

    iam.createLoginProfile(new CreateLoginProfileRequest(user.getUserName(), password));
    iam.addUserToGroup(new AddUserToGroupRequest("Admins", user.getUserName()));
    CreateAccessKeyResult createAccessKeyResult = iam
            .createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName()));
    AccessKey accessKey = createAccessKeyResult.getAccessKey();

    // SSH
    KeyPair sshKeyPair = createOrOverWriteSshKeyPair(userName);

    // X509
    java.security.KeyPair x509KeyPair = createRsaKeyPair();
    X509Certificate x509Certificate = createX509Certificate(userName, x509KeyPair);

    SigningCertificate signingCertificate;
    try {
        UploadSigningCertificateResult uploadSigningCertificateResult = iam
                .uploadSigningCertificate(new UploadSigningCertificateRequest(Pems.pem(x509Certificate))
                        .withUserName(user.getUserName()));
        signingCertificate = uploadSigningCertificateResult.getCertificate();
    } catch (CertificateEncodingException e) {
        throw Throwables.propagate(e);
    }

    System.out.println("CREATED userName=" + user.getUserName() + "\tpassword=" + password + "\taccessKeyId="
            + accessKey.getAccessKeyId() + "\tsecretAccessKey=" + accessKey.getSecretAccessKey()
            + "\tsshKeyPair=" + sshKeyPair.getKeyName() + "\tx509Certificate="
            + signingCertificate.getCertificateId());

    String subject = "Xebia France Amazon EC2 Credentials";

    String body = "Hello,\n";
    body += "\n";
    body += "Here are the credentials to connect to Xebia Amazon AWS/EC2 training infrastructure:\n";
    body += "\n";
    body += "User Name: " + user.getUserName() + "\n";
    body += "Password: " + password + "\n";
    body += "\n";
    body += "Access Key Id: " + accessKey.getAccessKeyId() + "\n";
    body += "Secret Access Key: " + accessKey.getSecretAccessKey() + "\n";
    body += "\n";
    body += "SSH private key pair '" + sshKeyPair.getKeyName() + "' attached, rename it as '"
            + sshKeyPair.getKeyName() + ".pem" + "'n";
    body += "\n";
    body += "The authentication page is https://xebia-france.signin.aws.amazon.com/console";
    body += "\n";
    body += "Don't hesitate to connect to Amazon AWS, to play with it but please DO NOT FORGET TO STOP INSTANCES OR IF POSSIBLE TERMINATE THEM AFTER USING THEM.\n";
    body += "Letting instances started would cost unnecessary money to Xebia.\n";
    body += "\n";
    body += "\n";
    body += "Thanks,\n";
    body += "\n";
    body += "Cyrille";
    try {
        sendEmail(subject, body, accessKey, sshKeyPair, x509KeyPair, x509Certificate, signingCertificate,
                "cyrille@cyrilleleclerc.com", user.getUserName());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java

/**
 * adds a user certificate to user/*from  w  ww.  jav a 2  s . c o  m*/
 */
public void addUserCert(IUser identity) throws EUsrGrpException {
    User user = (User) identity;

    if (user == null) {
        return;
    }

    X509Certificate cert[] = null;
    LDAPModificationSet addCert = new LDAPModificationSet();

    if ((cert = user.getX509Certificates()) != null) {
        LDAPAttribute attrCertStr = new LDAPAttribute(LDAP_ATTR_USER_CERT_STRING);
        LDAPAttribute attrCertBin = new LDAPAttribute(LDAP_ATTR_USER_CERT);

        try {
            attrCertBin.addValue(cert[0].getEncoded());
            attrCertStr.addValue(getCertificateString(cert[0]));
        } catch (CertificateEncodingException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_USER_CERT", e.toString()));
            throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_USR_CERT_ERROR"));
        }

        addCert.add(LDAPModification.ADD, attrCertStr);
        addCert.add(LDAPModification.ADD, attrCertBin);

        LDAPConnection ldapconn = null;

        try {
            ldapconn = getConn();
            ldapconn.modify("uid=" + LDAPUtil.escapeRDNValue(user.getUserID()) + "," + getUserBaseDN(),
                    addCert);
            // for audit log
            SessionContext sessionContext = SessionContext.getContext();
            String adminId = (String) sessionContext.get(SessionContext.USER_ID);

            mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP, AuditFormat.LEVEL, AuditFormat.ADDUSERCERTFORMAT,
                    new Object[] { adminId, user.getUserID(), cert[0].getSubjectDN().toString(),
                            cert[0].getSerialNumber().toString(16) });

        } catch (LDAPException e) {
            if (Debug.ON) {
                e.printStackTrace();
            }
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_USER", e.toString()));
            throw LDAPExceptionConverter.toPKIException(e);

        } catch (ELdapException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_USER", e.toString()));
            throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_USR_CERT_ERROR"));

        } finally {
            if (ldapconn != null)
                returnConn(ldapconn);
        }
    }

    return;
}