Example usage for java.security NoSuchAlgorithmException getMessage

List of usage examples for java.security NoSuchAlgorithmException getMessage

Introduction

In this page you can find the example usage for java.security NoSuchAlgorithmException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#signFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *///from w w w .ja  va 2s .com
public synchronized FileSecurityResponse signFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#signFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initSign(keyPair.getPrivate());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            byte[] sig = signature.sign();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
            }

            IOUtils.write(sig, new FileOutputStream(request.getSignedFile()));

            if ((request.getSignedFile().exists()) && (request.getSignedFile().length() != 0)) {
                response.setSignedFile(request.getSignedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.SIGNFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#encryptFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *///  ww  w  .  ja v a 2  s .  co m
public synchronized FileSecurityResponse encryptFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#encryptFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Cipher cipher = Cipher.getInstance(fileSecurityConfig.getEncryptionAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());

            if (DEBUG) {
                DEBUGGER.debug("Cipher: {}", cipher);
            }

            CipherOutputStream cipherOut = new CipherOutputStream(
                    new FileOutputStream(request.getEncryptedFile()), cipher);

            if (DEBUG) {
                DEBUGGER.debug("CipherOutputStream: {}", cipherOut);
            }

            byte[] data = IOUtils.toByteArray(new FileInputStream(request.getDecryptedFile()));
            IOUtils.write(data, cipherOut);

            cipherOut.flush();
            cipherOut.close();

            if ((request.getEncryptedFile().exists()) && (request.getEncryptedFile().length() != 0)) {
                response.setSignedFile(request.getEncryptedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (NoSuchPaddingException nspx) {
        ERROR_RECORDER.error(nspx.getMessage(), nspx);

        throw new FileSecurityException(nspx.getMessage(), nspx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.ENCRYPTFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * @param body//from w w  w.  ja  v a 2  s .  co m
 * @return a hash of body base64 encoded.
 */
private String hash(String toHash) {
    try {
        MessageDigest m = MessageDigest.getInstance("SHA-256");
        return new String(Base64.encodeBase64(m.digest(toHash.getBytes("UTF-8"))), "UTF-8");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.cloud.bridge.io.S3CAStorBucketAdapter.java

@Override
public String saveObject(InputStream is, String mountedRoot, String bucket, String fileName) {
    // TODO: Currently this writes the object to a temporary file,
    // so that the MD5 can be computed and so that we have the
    // stream length needed by this version of CAStor SDK. Will
    // change to calculate MD5 while streaming to CAStor and to
    // either pass Content-length to this method or use newer SDK
    // that doesn't require it.

    FileOutputStream fos = null;/*from   ww  w . j  ava  2s. c o  m*/
    MessageDigest md5 = null;

    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unexpected exception " + e.getMessage(), e);
        throw new InternalErrorException("Unable to get MD5 MessageDigest", e);
    }

    File spoolFile = null;
    try {
        spoolFile = File.createTempFile("castor", null);
    } catch (IOException e) {
        s_logger.error("Unexpected exception creating temporary CAStor spool file: " + e.getMessage(), e);
        throw new InternalErrorException("Unable to create temporary CAStor spool file", e);
    }
    try {
        String retVal;
        int streamLen = 0;
        try {
            fos = new FileOutputStream(spoolFile);
            byte[] buffer = new byte[4096];
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
                streamLen = streamLen + len;
                md5.update(buffer, 0, len);

            }
            //Convert MD5 digest to (lowercase) hex String
            retVal = StringHelper.toHexString(md5.digest());

        } catch (IOException e) {
            s_logger.error("Unexpected exception " + e.getMessage(), e);
            throw new OutOfStorageException(e);
        } finally {
            try {
                if (null != fos)
                    fos.close();
            } catch (Exception e) {
                s_logger.error(
                        "Can't close CAStor spool file " + spoolFile.getAbsolutePath() + ": " + e.getMessage(),
                        e);
                throw new OutOfStorageException("Unable to close CAStor spool file: " + e.getMessage(), e);
            }
        }

        try {
            ScspResponse bwResponse = myClient(mountedRoot).write(bucket + "/" + fileName,
                    new ResettableFileInputStream(spoolFile), streamLen, domainQueryArg(), new ScspHeaders());
            if (bwResponse.getHttpStatusCode() >= HTTP_UNSUCCESSFUL) {
                s_logger.error("CAStor write responded with error " + bwResponse.getHttpStatusCode());
                throw new OutOfStorageException("Unable to write object to CAStor " + bucket + "/" + fileName
                        + ": " + bwResponse.getHttpStatusCode());
            }
        } catch (ScspExecutionException e) {
            s_logger.error("Unable to write object to CAStor " + bucket + "/" + fileName, e);
            throw new OutOfStorageException(
                    "Unable to write object to CAStor " + bucket + "/" + fileName + ": " + e.getMessage());
        } catch (IOException ie) {
            s_logger.error("Unable to write object to CAStor " + bucket + "/" + fileName, ie);
            throw new OutOfStorageException(
                    "Unable to write object to CAStor " + bucket + "/" + fileName + ": " + ie.getMessage());
        }
        return retVal;
    } finally {
        try {
            if (!spoolFile.delete()) {
                s_logger.error("Failed to delete CAStor spool file " + spoolFile.getAbsolutePath());
            }
        } catch (SecurityException e) {
            s_logger.error("Unable to delete CAStor spool file " + spoolFile.getAbsolutePath(), e);
        }
    }
}

From source file:eu.peppol.security.OxalisCipherConverter.java

/**
 * Encrypts the secret key (symmetric key) held inside the OxalisCipher instance using the supplied PublicKey, after
 * which the resulting wrapped secret key is transformed into a hex string suitable for transmission, persistence etc.
 *
 * @param publicKey the public asymmetric key to use for encrypting the secret symmetric key
 * @param oxalisCipher the instance of OxalisCipher in which the secret symmetric key is held.
 * @return//  w w  w . j  a  va2s  .  co m
 */
public String getWrappedSymmetricKeyAsString(PublicKey publicKey, OxalisCipher oxalisCipher) {

    try {
        Cipher cipher = Cipher.getInstance(StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM);
        cipher.init(Cipher.WRAP_MODE, publicKey);
        SecretKey secretKey = oxalisCipher.getSecretKey();
        byte[] encodedBytes = cipher.wrap(secretKey);

        return new String(Hex.encodeHex(encodedBytes));

    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(
                "Unable to create cipher with algorithm: " + StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM, e);
    } catch (NoSuchPaddingException e) {
        throw new IllegalStateException("Unable to create cipher with default padding for algorithm "
                + StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM, e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException("The public key is invalid " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        throw new IllegalStateException("Error during encryption of symmetric key: " + e.getMessage(), e);
    }
}

From source file:password.pwm.util.operations.OtpService.java

public String doRecoveryHash(final String input, final OTPUserRecord.RecoveryInfo recoveryInfo)
        throws IllegalStateException {
    final String algorithm = settings.getRecoveryHashMethod();
    final MessageDigest md;
    try {// w w w . jav  a2  s  . c o m
        md = MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(
                "unable to load " + algorithm + " message digest algorithm: " + e.getMessage());
    }

    final String raw = recoveryInfo.getSalt() == null ? input.trim()
            : recoveryInfo.getSalt().trim() + input.trim();

    final int hashCount = recoveryInfo.getHashCount();
    byte[] hashedBytes = raw.getBytes();
    for (int i = 0; i < hashCount; i++) {
        hashedBytes = md.digest(hashedBytes);
    }
    return StringUtil.base64Encode(hashedBytes);
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskXMsgClient.CFAsteriskXMsgClientHttpSchema.java

public boolean connect(String loginId, String password, String clusterName, String tenantName) {
    final String S_ProcName = "connect-full";
    CFTipClientHandler clientHandler = getCFTipClientHandler();
    String deviceName = clientHandler.getDeviceName();
    if (clientContext != null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "clientContext already exists");
    }/*from  www . j  av  a2  s. c om*/
    CookieStore cookieStore = new BasicCookieStore();
    clientContext = HttpClientContext.create();
    clientContext.setCookieStore(cookieStore);

    String rqst = null;

    try {
        clientHandler.requestServerInfo();

        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(password.getBytes("UTF-8"));
        byte[] hash = msgDigest.digest();
        byte[] encodedHash = Base64.encodeBase64(hash);
        byte[] devEncPWHash = clientHandler.encryptWithDevicePrivateKey(encodedHash);

        clientHandler.initSessionKey();

        rqst = CFAsteriskXMsgSchemaMessageFormatter.formatRqstXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRqstLogIn("\n\t\t\t", loginId, deviceName,
                        devEncPWHash, clusterName, tenantName)
                + "\n" + CFAsteriskXMsgSchemaMessageFormatter.formatRqstXmlPostamble();
    } catch (NoSuchAlgorithmException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException - " + e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught UnsupportedEncodingException - " + e.getMessage(), e);
    } catch (InvalidKeyException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught InvalidKeyException - " + e.getMessage(), e);
    } catch (NoSuchPaddingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchPaddingException - " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught IllegalBlockSizeException - " + e.getMessage(), e);
    } catch (BadPaddingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught BadPaddingException - " + e.getMessage(), e);
    } catch (InvalidKeySpecException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught InvalidKeySpecException - " + e.getMessage(), e);
    } catch (RuntimeException e) {
        clientContext = null;
        throw e;
    }

    try {
        cftipClientHandler.issueLoginRequest(rqst);
    } catch (InvalidAlgorithmParameterException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught InvalidAlgorithmParameterException - " + e.getMessage(), e);
    } catch (BadPaddingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught BadPaddingException - " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught IllegalBlockSizeException - " + e.getMessage(), e);
    } catch (InvalidKeyException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught InvalidKeyException - " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException - " + e.getMessage(), e);
    } catch (NoSuchPaddingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchPaddingException - " + e.getMessage(), e);
    } catch (RuntimeException e) {
        clientContext = null;
        throw e;
    }
    // The response handler sets up the authorization
    ICFTipResponseHandler responseHandler = cftipClientHandler.getResponseHandler();
    CFLibRuntimeException exceptionRaised = responseHandler.getExceptionRaised();
    if (exceptionRaised != null) {
        clientContext = null;
        throw exceptionRaised;
    }
    // If we got a response instead of an exception, we succeeded at logging in.
    return (true);
}

From source file:com.fortmoon.utils.CSVDBLoader.java

public CSVDBLoader() {
    log.info("called");
    try {//from   ww w .  jav a  2  s. c  o m
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        log.error("Exception getting instance of MD5 MessageDigest: " + e.getMessage(), e);
        throw new RuntimeException("Can't get instance of MD5, aborting.");
    }

}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();

    final String ids_string = getMediaIds(pics, twitter);

    if (ids_string == null) {
        return false;
    }//from   w w w  .j  a  va 2s . c  o  m

    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                        twitter_endpoint_path);

                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);

                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message",
                        "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {

    }
    return true;
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Loader constructor. Loads an existing MyCareNet session key.
 * //from  w  w w.j av  a  2 s  .  c o m
 * @param encodedPrivateKey
 * @param encodedPublicKey
 * @param encodedCertificate
 * @param notBefore
 * @param notAfter
 */
public SessionKey(byte[] encodedPrivateKey, byte[] encodedPublicKey, byte[] encodedCertificate, Date notBefore,
        Date notAfter) {
    this.notBefore = notBefore;
    this.notAfter = notAfter;

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA", e);
    }
    PublicKey publicKey;
    try {
        publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid public key: " + e.getMessage(), e);
    }

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey;
    try {
        privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid private key: " + e.getMessage(), e);
    }

    this.keyPair = new KeyPair(publicKey, privateKey);

    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}