Example usage for javax.xml.bind DatatypeConverter printBase64Binary

List of usage examples for javax.xml.bind DatatypeConverter printBase64Binary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter printBase64Binary.

Prototype

public static String printBase64Binary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:org.fejoa.library.messages.PublicCryptoEnvelope.java

static public byte[] encrypt(byte[] data, boolean isRawData, KeyId keyId, PublicKey key, FejoaContext context)
        throws JSONException, CryptoException, IOException {
    JSONObject object = new JSONObject();
    object.put(Envelope.PACK_TYPE_KEY, CRYPTO_TYPE);
    if (isRawData)
        object.put(Envelope.CONTAINS_DATA_KEY, 1);

    ICryptoInterface crypto = context.getCrypto();
    CryptoSettings.Asymmetric pubKeySettings = context.getCryptoSettings().publicKey;
    CryptoSettings.Symmetric symSettings = context.getCryptoSettings().symmetric;
    byte[] iv = crypto.generateInitializationVector(symSettings.ivSize);
    String base64IV = DatatypeConverter.printBase64Binary(iv);
    SecretKey symKey = crypto.generateSymmetricKey(symSettings);

    // encrypt the key
    byte[] encSymKey = crypto.encryptAsymmetric(symKey.getEncoded(), key, pubKeySettings);
    String base64EncSymKey = DatatypeConverter.printBase64Binary(encSymKey);

    object.put(PUBLIC_KEY_ID_KEY, keyId.getKeyId());
    object.put(PUBLIC_KEY_SETTINGS_KEY, JsonCryptoSettings.toJson(pubKeySettings));
    object.put(IV_KEY, base64IV);//  w w  w.j av  a2 s  .  c  o m
    object.put(ENC_SYMMETRIC_KEY_KEY, base64EncSymKey);
    object.put(SYMMETRIC_SETTINGS_KEY, JsonCryptoSettings.toJson(symSettings));
    String header = object.toString() + "\n";

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    outStream.write(header.getBytes());
    OutputStream crytoStream = crypto.encryptSymmetric(outStream, symKey, iv, symSettings);
    crytoStream.write(data);
    crytoStream.flush();
    return outStream.toByteArray();
}

From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java

private static void addHTTPBasicAuthProperty(HttpsURLConnection conn) {
    String userpass = username + ":" + password;
    @SuppressWarnings("restriction")
    String basicAuth = "Basic " + new String(DatatypeConverter.printBase64Binary(userpass.getBytes()));
    conn.setRequestProperty("Authorization", basicAuth);
}

From source file:org.ligoj.app.plugin.km.confluence.ConfluencePluginResource.java

/**
 * Return the avatar PNG file from URL./*from   www  . j a v a 2  s  .co  m*/
 */
private void getAvatar(final CurlProcessor processor, final SpaceActivity activity, final String avatarUrl) {
    if (!avatarUrl.endsWith("/default.png")) {
        // Not default URL, get the PNG bytes
        processor.process(new CurlRequest("GET", avatarUrl, null, (req, res) -> {
            // PNG to DATA URL
            if (res.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
                activity.setAuthorAvatar("data:image/png;base64," + DatatypeConverter
                        .printBase64Binary(IOUtils.toByteArray(res.getEntity().getContent())));
            }
            return true;
        }));
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public String generateCertificateReq(final String keyStoreName, final String keyStorePwd, final String keyAlias,
        final String signAlg, final boolean withTag) {
    try {//w  ww. j  a  v  a2  s .com
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
        ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray());
        if (ctlKeyStore.containsAlias(keyAlias)) {
            final X509Certificate odlCert = (X509Certificate) ctlKeyStore.getCertificate(keyAlias);
            final PublicKey pubKey = odlCert.getPublicKey();
            final PrivateKey privKey = (PrivateKey) ctlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray());
            final String subject = odlCert.getSubjectDN().getName();
            final X509Name xname = new X509Name(subject);
            final String signatureAlgorithm = signAlg;
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname,
                    pubKey, null, privKey);
            final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST);
                sb.append("\n");
                sb.append(certReq);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST);
                return sb.toString();
            }
            return certReq;
        }
        LOG.info("{} KeyStore does not contain alias {}", keyStoreName, keyAlias);
        return null;
    } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException
            | UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException
            | SignatureException e) {
        LOG.error("Failed to generate certificate request {}", e.getMessage());
        return null;
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public String getCertificate(final String keyStoreName, final String keyStorePwd, final String certAlias,
        final boolean withTag) {
    try {// w w w  .j  a  v a 2  s  .  c  o m
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
        ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray());
        if (ctlKeyStore.containsAlias(certAlias)) {
            final X509Certificate odlCert = (X509Certificate) ctlKeyStore.getCertificate(certAlias);
            final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE);
                sb.append("\n");
                sb.append(cert);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE);
                return sb.toString();
            }
            return cert;
        }
        LOG.info("{} KeyStore does not contain alias {}", keyStoreName, certAlias);
        return null;
    } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException e) {
        LOG.error("Failed to get Certificate {}", e.getMessage());
        return null;
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public String generateCertificateReq(final KeyStore odlKeyStore, final String keyStorePwd,
        final String keyAlias, final String signAlg, final boolean withTag) {
    try {/*w w  w  . jav a 2  s  .c  o m*/
        if (odlKeyStore.containsAlias(keyAlias)) {
            final X509Certificate odlCert = (X509Certificate) odlKeyStore.getCertificate(keyAlias);
            final PublicKey pubKey = odlCert.getPublicKey();
            final PrivateKey privKey = (PrivateKey) odlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray());
            final String subject = odlCert.getSubjectDN().getName();
            final X509Name xname = new X509Name(subject);
            final String signatureAlgorithm = signAlg;
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname,
                    pubKey, null, privKey);
            final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST);
                sb.append("\n");
                sb.append(certReq);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST);
                return sb.toString();
            }
            return certReq;
        }
        LOG.info("KeyStore does not contain alias {}", keyAlias);
        return null;
    } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        LOG.error("Failed to generate certificate request", e);
        return null;
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public String getCertificate(final KeyStore keyStore, final String keyStorePwd, final String certAlias,
        final boolean withTag) {
    try {// w ww  .  j a  v  a2  s. c om
        if (keyStore.containsAlias(certAlias)) {
            final X509Certificate odlCert = (X509Certificate) keyStore.getCertificate(certAlias);
            final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE);
                sb.append("\n");
                sb.append(cert);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE);
                return sb.toString();
            }
            return cert;
        }
        LOG.info("KeyStore does not contain alias {}", certAlias);
        return null;
    } catch (final CertificateException | KeyStoreException e) {
        LOG.error("Failed to get Certificate", e);
        return null;
    }
}

From source file:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java

@Override
public String encrypt(String data) {
    // We could not instantiate the encryption key, hence no encryption or
    // decryption will be done.
    if (key == null) {
        LOG.warn("Encryption Key is NULL, will not encrypt data.");
        return data;
    }/* w ww . j  av a  2s.c  o m*/
    try {
        synchronized (encryptCipher) {
            byte[] cryptobytes = encryptCipher.doFinal(data.getBytes());
            String cryptostring = DatatypeConverter.printBase64Binary(cryptobytes);
            return cryptostring;
        }
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        LOG.error("Failed to encrypt data.", e);
    }
    return data;
}

From source file:org.openhab.action.openwebif.internal.impl.OpenWebIfCommunicator.java

/**
 * Executes the http request and parses the returned stream.
 *///from  w  w  w  .jav  a  2s  .co m
@SuppressWarnings("unchecked")
private <T> T executeRequest(OpenWebIfConfig config, String url, Class<T> clazz) throws IOException {
    HttpURLConnection con = null;
    try {
        logger.trace("Request [{}]: {}", config.getName(), url);

        con = (HttpURLConnection) new URL(url).openConnection();
        con.setConnectTimeout(CONNECTION_TIMEOUT);
        con.setReadTimeout(10000);

        if (config.hasLogin()) {
            String userpass = config.getUser() + ":" + config.getPassword();
            String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
            con.setRequestProperty("Authorization", basicAuth);
        }

        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sCon = (HttpsURLConnection) con;
            TrustManager[] trustManager = new TrustManager[] { new SimpleTrustManager() };
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(new KeyManager[0], trustManager, new SecureRandom());
            sCon.setSSLSocketFactory(context.getSocketFactory());
            sCon.setHostnameVerifier(new AllowAllHostnameVerifier());
        }
        StringWriter sw = new StringWriter();
        IOUtils.copy(con.getInputStream(), sw);
        con.disconnect();

        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String response = sw.toString();
            logger.trace("Response: [{}]: {}", config.getName(), response);

            Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
            return (T) um.unmarshal(new StringReader(response));
        } else {
            throw new IOException(con.getResponseMessage());
        }
    } catch (JAXBException ex) {
        throw new IOException(ex.getMessage(), ex);
    } catch (GeneralSecurityException ex) {
        throw new IOException(ex.getMessage(), ex);
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:org.openmrs.module.muzimabiometrics.panels.ScanFingerprint.java

private boolean IdentifyPatient() throws JSONException {
    service = new JavaScriptCallerService((Applet) this.getParent().getParent());
    String fingerprint = DatatypeConverter.printBase64Binary(subject.getTemplateBuffer().toByteArray());
    PatientFingerPrintModel patient = service.identifyPatient(fingerprint);
    if (patient != null) {
        return true;
    }/* w w  w  .  j ava2  s . c o  m*/
    return false;
}