Example usage for org.bouncycastle.util.encoders Base64 toBase64String

List of usage examples for org.bouncycastle.util.encoders Base64 toBase64String

Introduction

In this page you can find the example usage for org.bouncycastle.util.encoders Base64 toBase64String.

Prototype

public static String toBase64String(byte[] data) 

Source Link

Usage

From source file:benapp.sshare.ShareAdapter.java

License:Open Source License

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    final ViewHolder viewHolder;

    if (convertView == null) {
        convertView = LayoutInflater.from(this.getContext()).inflate(R.layout.share_adapter_layout, parent,
                false);//from   w ww  . j av a2 s . c  o m

        viewHolder = new ViewHolder();
        viewHolder.share = (TextView) convertView.findViewById(R.id.share_edit_text);

        convertView.setTag(viewHolder);

    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    ShareHolder item = getItem(position);
    if (item != null) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(item);
            objectOutputStream.close();
        } catch (IOException e) {
            viewHolder.share.setText(e.getMessage());
        }
        viewHolder.share.setText(Base64.toBase64String(byteArrayOutputStream.toByteArray()));
    }

    return convertView;
}

From source file:bisq.common.crypto.Sig.java

License:Open Source License

/**
 * @param privateKey//w  w w.j  a  v a 2 s.  c o m
 * @param message    UTF-8 encoded message to sign
 * @return Base64 encoded signature
 */
public static String sign(PrivateKey privateKey, String message) throws CryptoException {
    byte[] sigAsBytes = sign(privateKey, message.getBytes(Charsets.UTF_8));
    return Base64.toBase64String(sigAsBytes);
}

From source file:ch.cyberduck.core.azure.AzureSession.java

License:Open Source License

@Override
public CloudBlobClient connect(final HostKeyCallback callback) throws BackgroundException {
    try {//ww  w.j a  v a2  s.c o  m
        final StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(
                host.getCredentials().getUsername(), Base64.toBase64String("null".getBytes()));
        // Client configured with no credentials
        final URI uri = new URI(String.format("%s://%s", Scheme.https, host.getHostname()));
        final CloudBlobClient client = new CloudBlobClient(uri, credentials);
        client.setDirectoryDelimiter(String.valueOf(Path.DELIMITER));
        final BlobRequestOptions options = client.getDefaultRequestOptions();
        options.setTimeoutIntervalInMs(this.timeout());
        options.setRetryPolicyFactory(new RetryNoRetry());
        context.setLoggingEnabled(true);
        context.setLogger(LoggerFactory.getLogger(log.getName()));
        context.setUserHeaders(new HashMap<String, String>(
                Collections.singletonMap(HttpHeaders.USER_AGENT, new PreferencesUseragentProvider().get())));
        context.getSendingRequestEventHandler().addListener(listener = new StorageEvent<SendingRequestEvent>() {
            @Override
            public void eventOccurred(final SendingRequestEvent event) {
                if (event.getConnectionObject() instanceof HttpsURLConnection) {
                    final HttpsURLConnection connection = (HttpsURLConnection) event.getConnectionObject();
                    connection.setSSLSocketFactory(new CustomTrustSSLProtocolSocketFactory(trust, key));
                    connection.setHostnameVerifier(new DisabledX509HostnameVerifier());
                }
            }
        });
        final Proxy proxy = ProxyFactory.get().find(host);
        switch (proxy.getType()) {
        case SOCKS: {
            if (log.isInfoEnabled()) {
                log.info(String.format("Configured to use SOCKS proxy %s", proxy));
            }
            final java.net.Proxy socksProxy = new java.net.Proxy(java.net.Proxy.Type.SOCKS,
                    new InetSocketAddress(proxy.getHostname(), proxy.getPort()));
            context.setProxy(socksProxy);
            break;
        }
        case HTTP:
        case HTTPS: {
            if (log.isInfoEnabled()) {
                log.info(String.format("Configured to use HTTP proxy %s", proxy));
            }
            final java.net.Proxy httpProxy = new java.net.Proxy(java.net.Proxy.Type.HTTP,
                    new InetSocketAddress(proxy.getHostname(), proxy.getPort()));
            context.setProxy(httpProxy);
            break;
        }
        }
        return client;
    } catch (URISyntaxException e) {
        throw new LoginFailureException(e.getMessage(), e);
    }
}

From source file:ch.cyberduck.core.azure.AzureWriteFeature.java

License:Open Source License

@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status,
        final ConnectionCallback callback) throws BackgroundException {
    try {//  w  w w .  ja  va  2  s  .  c om
        final CloudAppendBlob blob = session.getClient()
                .getContainerReference(containerService.getContainer(file).getName())
                .getAppendBlobReference(containerService.getKey(file));
        if (StringUtils.isNotBlank(status.getMime())) {
            blob.getProperties().setContentType(status.getMime());
        }
        final HashMap<String, String> headers = new HashMap<>();
        // Add previous metadata when overwriting file
        headers.putAll(status.getMetadata());
        blob.setMetadata(headers);
        // Remove additional headers not allowed in metadata and move to properties
        if (headers.containsKey(HttpHeaders.CACHE_CONTROL)) {
            blob.getProperties().setCacheControl(headers.get(HttpHeaders.CACHE_CONTROL));
            headers.remove(HttpHeaders.CACHE_CONTROL);
        }
        if (headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
            blob.getProperties().setCacheControl(headers.get(HttpHeaders.CONTENT_TYPE));
            headers.remove(HttpHeaders.CONTENT_TYPE);
        }
        final Checksum checksum = status.getChecksum();
        if (Checksum.NONE != checksum) {
            switch (checksum.algorithm) {
            case md5:
                try {
                    blob.getProperties().setContentMD5(
                            Base64.toBase64String(Hex.decodeHex(status.getChecksum().hash.toCharArray())));
                    headers.remove(HttpHeaders.CONTENT_MD5);
                } catch (DecoderException e) {
                    // Ignore
                }
                break;
            }
        }
        final BlobRequestOptions options = new BlobRequestOptions();
        options.setConcurrentRequestCount(1);
        options.setStoreBlobContentMD5(preferences.getBoolean("azure.upload.md5"));
        final BlobOutputStream out;
        if (status.isAppend()) {
            options.setStoreBlobContentMD5(false);
            out = blob.openWriteExisting(AccessCondition.generateEmptyCondition(), options, context);
        } else {
            out = blob.openWriteNew(AccessCondition.generateEmptyCondition(), options, context);
        }
        return new VoidStatusOutputStream(out) {
            @Override
            protected void handleIOException(final IOException e) throws IOException {
                if (StringUtils.equals(SR.STREAM_CLOSED, e.getMessage())) {
                    log.warn(String.format("Ignore failure %s", e));
                    return;
                }
                final Throwable cause = ExceptionUtils.getRootCause(e);
                if (cause instanceof StorageException) {
                    throw new IOException(e.getMessage(),
                            new AzureExceptionMappingService().map((StorageException) cause));
                }
                throw e;
            }
        };
    } catch (StorageException e) {
        throw new AzureExceptionMappingService().map("Upload {0} failed", e, file);
    } catch (URISyntaxException e) {
        throw new NotfoundException(e.getMessage(), e);
    }
}

From source file:ch.cyberduck.core.sftp.PreferencesHostKeyVerifier.java

License:Open Source License

@Override
public boolean verify(final String hostname, final int port, final PublicKey key)
        throws ConnectionCanceledException, ChecksumException {
    final String lookup = preferences.getProperty(this.getFormat(hostname, key));
    if (StringUtils.equals(Base64.toBase64String(key.getEncoded()), lookup)) {
        if (log.isInfoEnabled()) {
            log.info(String.format("Accepted host key %s matching %s", key, lookup));
        }/* ww w.  j  a v a 2s  .  c  o m*/
        return true;
    }
    final boolean accept;
    if (null == lookup) {
        accept = this.isUnknownKeyAccepted(hostname, key);
    } else {
        accept = this.isChangedKeyAccepted(hostname, key);
    }
    return accept;
}

From source file:ch.cyberduck.core.sftp.PreferencesHostKeyVerifier.java

License:Open Source License

@Override
protected void allow(final String hostname, final PublicKey key, final boolean persist) {
    if (persist) {
        preferences.setProperty(this.getFormat(hostname, key), Base64.toBase64String(key.getEncoded()));
    }/*from w  ww . j a v a2 s  .  c  o m*/
}

From source file:classLibrary.StringEncrypt.java

public String encrypt(String unencryptedString) {
    String encryptedString = null;
    try {//from w  ww  .  j a  va2  s.  c  o m
        cipher.init(Cipher.ENCRYPT_MODE, key);
        //?  bytes
        byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
        byte[] encryptedText = cipher.doFinal(plainText);
        encryptedString = new String(Base64.toBase64String(encryptedText));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encryptedString;
}

From source file:com.afrisoftech.funsoft.mobilepay.Base64Encoding.java

public static String encodetoBase64String(String stringtoEncode) {

    String appKeySecret = com.afrisoftech.hospital.HospitalMain.oAuthKey;
    //    String appKeySecret = app_key + ":" + app_secret;
    System.out.println("Consumer Secret keys : [" + com.afrisoftech.hospital.HospitalMain.oAuthKey + "]");
    byte[] bytes = null;
    try {// ww  w  .j  a  v a 2 s  .  com
        bytes = appKeySecret.getBytes("ISO-8859-1");
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Base64Encoding.class.getName()).log(Level.SEVERE, null, ex);
    }
    String auth = Base64.toBase64String(bytes);

    OkHttpClient client = new OkHttpClient();
    System.out.println("New oAuth Access Token : [" + auth + "]");

    Request request = null;
    System.out.println("OkHttpClient : [" + client + "]");
    if (com.afrisoftech.hospital.HospitalMain.mobileTxTest) {
        request = new Request.Builder()
                .url("https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials").get()
                .addHeader("authorization", "Basic " + auth).addHeader("cache-control", "no-cache").build();
    } else {
        request = new Request.Builder()
                .url("https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials").get()
                .addHeader("authorization", "Basic " + auth).addHeader("cache-control", "no-cache").build();
    }

    String accessToken = null;

    Response response;

    try {
        response = client.newCall(request).execute();
        JSONObject myObject = null;
        try {

            myObject = new JSONObject(response.body().string());

        } catch (JSONException ex) {
            Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("Response : " + myObject.toString());

        try {
            System.out.println("Access Token : [" + myObject.getString("access_token") + "]");

            accessToken = myObject.getString("access_token");

        } catch (JSONException e) {
            e.printStackTrace();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(null,
                "There is a problem connecting to mobile payments service provider. Please contact system administrator");
    }

    return accessToken;

}

From source file:com.afrisoftech.funsoft.mobilepay.MobilePayAPI.java

public String encryptInitiatorPassword(String securityCertificate, String password) {
    String encryptedPassword = "safaricom329!";
    try {/*from ww  w .j a v a  2s.  c  o  m*/
        try {
            try {
                try {
                    try {
                        try {
                            try {
                                try {

                                    Security.addProvider(
                                            new org.bouncycastle.jce.provider.BouncyCastleProvider());
                                    byte[] input = password.getBytes();

                                    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
                                    FileInputStream fin = new FileInputStream(new File(securityCertificate));
                                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                                    X509Certificate certificate = (X509Certificate) cf.generateCertificate(fin);
                                    PublicKey pk = certificate.getPublicKey();
                                    cipher.init(Cipher.ENCRYPT_MODE, pk);

                                    byte[] cipherText = cipher.doFinal(input);

                                    // Convert the resulting encrypted byte array into a string using base64 encoding
                                    encryptedPassword = Base64.toBase64String(cipherText);

                                } catch (NoSuchAlgorithmException ex) {
                                    Logger.getLogger(PasswordUtil.class.getName()).log(Level.SEVERE, null, ex);
                                }
                            } catch (NoSuchProviderException ex) {

                                Logger.getLogger(PasswordUtil.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } catch (NoSuchPaddingException ex) {
                            Logger.getLogger(PasswordUtil.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(PasswordUtil.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } catch (CertificateException ex) {
                    Logger.getLogger(PasswordUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (InvalidKeyException ex) {
                Logger.getLogger(PasswordUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(PasswordUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (BadPaddingException ex) {
        Logger.getLogger(PasswordUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    return encryptedPassword;
}

From source file:com.afrisoftech.funsoft.mobilepay.MobilePayAPI.java

public static boolean sendProcessRequest(String accessToken, String accountNo, String payerMobilePhone,
        String billedAmount, String shortCode) {
    boolean checkoutRequestStatus = true;
    OkHttpClient client = new OkHttpClient();
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    dateFormat.setCalendar(calendar);/*from www .  j a v a 2s  .  co m*/
    String timeStamp = dateFormat.format(calendar.getTime());
    System.out.println("Timestamp : [" + dateFormat.format(calendar.getTime()) + "]");
    System.out.println("Shortcode : [" + shortCode + "]");
    String password = shortCode + com.afrisoftech.hospital.HospitalMain.passKey + timeStamp;
    //        String password = shortCode + "48d34200abe6ebbcbc3bc644487c3651936d129f2274f6ee95" + timeStamp;
    //            json.put("CallBackURL", "https://192.162.85.226:17933/FunsoftWebServices/funsoft/InvoiceService/mpesasettlement");
    //        String password = shortCode + "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919" + timeStamp; // for testing purposes
    String encodedPassword = Base64.toBase64String(password.getBytes());
    System.out.println("Unencoded password : [" + password + "]");
    System.out.println("Encoded password : [" + encodedPassword + "]");
    MediaType mediaType = MediaType.parse("application/json");

    String message = null;
    JSONObject json = new JSONObject();
    try {
        json.put("BusinessShortCode", shortCode);
        json.put("Password", encodedPassword);
        json.put("Timestamp", timeStamp);
        json.put("TransactionType", "CustomerPayBillOnline");
        json.put("Amount", billedAmount);
        json.put("PartyA", payerMobilePhone);
        json.put("PartyB", shortCode);
        json.put("PhoneNumber", payerMobilePhone);
        json.put("CallBackURL", com.afrisoftech.hospital.HospitalMain.callBackURL);
        //            json.put("CallBackURL", "https://192.162.85.226:17933/FunsoftWebServices/funsoft/InvoiceService/mpesasettlement");
        json.put("AccountReference", accountNo);
        json.put("TransactionDesc", "Settlement for client bill");
        message = json.toString();
        System.out.println("This is the JSON String : " + message);

    } catch (JSONException ex) {
        Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    RequestBody body = RequestBody.create(mediaType, message);
    Request request = null;
    if (com.afrisoftech.hospital.HospitalMain.mobileTxTest) {
        request = new Request.Builder().url("https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest") // for sandbox test cases        
                .post(body).addHeader("authorization", "Bearer " + accessToken)
                .addHeader("content-type", "application/json").build();
    } else {
        request = new Request.Builder().url("https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest")
                .post(body).addHeader("authorization", "Bearer " + accessToken)
                .addHeader("content-type", "application/json").build();
    }
    try {
        Response response = client.newCall(request).execute();
        JSONObject myJsonObject = null;
        try {
            myJsonObject = new JSONObject(response.body().string());
        } catch (JSONException ex) {
            Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (myJsonObject.toString().contains("error")) {
            try {
                //                    checkoutRequestID = myJsonObject.getString("errorMessage");
                checkoutRequestStatus = false;
                System.out.println("Checkout Request ID : [" + myJsonObject.getString("errorMessage") + "]");
                javax.swing.JOptionPane.showMessageDialog(null,
                        "Payment Request Error : " + myJsonObject.getString("errorMessage") + ". Try again.");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (myJsonObject.toString().contains("Success")) {
            try {
                checkoutRequestStatus = true;
                com.afrisoftech.hospital.GeneralBillingIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.hospinventory.PatientsBillingIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.accounting.InpatientDepositIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.accounting.InpatientRecpIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.hospital.HospitalMain.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.accounting.GovBillPaymentsIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                System.out
                        .println("Checout Request ID : [" + myJsonObject.getString("CheckoutRequestID") + "]");

            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("Response for Process Request : [" + myJsonObject.toString() + "]");

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return checkoutRequestStatus;
}