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

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

Introduction

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

Prototype

public static byte[] encode(byte[] data) 

Source Link

Document

encode the input data producing a base 64 encoded byte array.

Usage

From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java

License:Open Source License

public String getEncodedDataHash() {
    return new String(Base64.encode(this.dataHash));
}

From source file:it.trento.comune.j4sign.verification.VerifyResult.java

License:Open Source License

/**
 * Creates the base64 encoding of a byte array.
 * /*www  .jav a 2s. co  m*/
 * @param bytes
 *            byte[]
 * @return java.lang.String
 */
public String encodeFromBytes(byte[] bytes) {

    String encString = new String(Base64.encode(bytes));

    return encString;
}

From source file:it.trento.comune.j4sign.verification.X509CertRL.java

License:Open Source License

/**
 * Set proxy connection parameters to download CRL<br>
 * <br>//w ww  . j a v a2  s.co m
 * Imposta i parametri di connessione con il proxy verso Internet per lo
 * scarico delle CRL
 * 
 * @param proxy
 *            true is proxy is used
 * @param user
 *            proxy authenticated user
 * @param password
 *            password
 * @param proxyHost
 *            proxy
 * @param proxyPort
 *            proxy port
 * @return true se l'impostazione del collegamento col proxy e' terminata
 *         correttamente
 */

public boolean setUseproxy(boolean proxy, String user, String password, String proxyHost, String proxyPort) {
    if (proxy) {
        if (proxyHost != null && proxyPort != null) {
            this.useProxy = proxy;
            if (user != null && password != null) {
                String authString = user + ":" + password;
                auth = "Basic " + new String(Base64.encode(authString.getBytes()));
            }
            System.getProperties().put("proxySet", "true");
            System.getProperties().put("proxyHost", proxyHost);
            System.getProperties().put("proxyPort", proxyPort);
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort);
            log.info("setUseproxy - Abilitato l'uso del proxy (anche per https)");
            return true;
        } else {
            this.useProxy = proxy;
            log.info("setUseproxy - host o port nulli: disabilitato l'uso del proxy");
            return false;
        }
    } else {
        this.useProxy = proxy;
        log.info("setUseproxy - Settato il collegamento senza proxy");
        return false;
    }
}

From source file:it.treviso.provincia.freesigner.applet.FreeSignerSignApplet4.java

License:Open Source License

/**
 * Method invoked for saving//  w ww. jav a 2s. com
 */

public void doSave() {
    log.println("Saving signed message");

    String p7mFilePath = fileDaAprire + ".p7m";
    if (fileDaAprire.substring(fileDaAprire.lastIndexOf('.') + 1, fileDaAprire.length()).toLowerCase()
            .equalsIgnoreCase("p7m")) {
        p7mFilePath = fileDaAprire;
        log.println("Resigning, saving on " + p7mFilePath);
    }
    log.println("Saving on " + p7mFilePath);

    File file = new File(p7mFilePath);

    try {
        saved = save(Base64.encode(cms.getEncoded()), file);
    } catch (IOException ex1) {
        JOptionPane.showMessageDialog(null, "Errore di I/O durante il salvataggio di " + p7mFilePath, "Errore",
                JOptionPane.ERROR_MESSAGE);
    }

    if (saved) {
        log.println("Signed message saved to: " + file.getAbsolutePath());

        MessageDigest mdigest;
        String mhash = "";
        try {
            mdigest = MessageDigest.getInstance("SHA-512");
            mhash = calculateHash(mdigest, p7mFilePath);
        } catch (Exception e2) {
            e2.printStackTrace();
        }

        jso.eval("window.location.href='" + callBackUrl + "&mhash=" + mhash + "&signercn=" + this.signerCN
                + "'");

    }
}

From source file:it.yup.xmlstream.SASLAuthenticator.java

/**
 * Start the login process. The result is asynchronous, and in order to get it 
 * register a listener for the STREAM_CONNECTED event.
 *//*from  www.  jav  a 2 s.  c om*/
public void start(BasicXmlStream xmlStream) {

    this.stream = xmlStream;
    // Config cfg = xmlStream.config;
    // look for the best auth mechanism and start the auth (the first, the better)
    Element mechanisms = (Element) stream.features.get(namespace);

    Element auth = new Element(namespace, "auth");
    for (int i = 0; i < supportedMechanisms.length; i++) {
        Element[] children = mechanisms.getChildren();
        for (int j = 0; j < children.length; j++) {
            Element mechanism = children[j];
            if (supportedMechanisms[i].equals(mechanism.getText())) {
                if (supportedMechanisms[i].equals(MECHANISM_PLAIN)) {
                    auth.setAttribute("mechanism", MECHANISM_PLAIN);
                    try {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        String tmp = Contact.userhost(stream.jid);
                        bos.write(Utils.getBytesUtf8(tmp));
                        bos.write(0);
                        tmp = Contact.user(stream.jid);
                        bos.write(Utils.getBytesUtf8(tmp));
                        bos.write(0);
                        tmp = stream.password;
                        bos.write(Utils.getBytesUtf8(tmp));
                        /* base64 **SHOULD** be ASCII and doesn't need UTF-8 */
                        auth.addText(new String(Base64.encode(bos.toByteArray())));
                    } catch (UnsupportedEncodingException e) {
                        // YUPMidlet.yup.reportException("UnsupportedEncoding on SASLAutenticator", e, null);
                    } catch (IOException e) {
                        // YUPMidlet.yup.reportException("IO error on SASLAutenticator", e, null);
                    }

                    // listen for the result 
                    EventQuery pq = new EventQuery(EventQuery.ANY_PACKET, null, null);

                    BasicXmlStream.addOnetimeEventListener(pq, new PacketListener() {
                        public void packetReceived(Element e) {
                            if ("success".equals(e.name)) {
                                stream.restart();
                                stream.dispatchEvent(BasicXmlStream.STREAM_AUTHENTICATED, null);
                            } else {
                                stream.dispatchEvent(BasicXmlStream.STREAM_ERROR, "Cannot authenticate");
                            }
                        }
                    });
                    stream.send(auth, -1);
                    // started auth with this method, don't try the others
                    return;
                } else if (supportedMechanisms[i].equals(MECHANISM_DIGEST_MD5)) {
                    auth.setAttribute("mechanism", MECHANISM_DIGEST_MD5);
                    EventQuery pq = new EventQuery(EventQuery.ANY_PACKET, null, null);
                    BasicXmlStream.addOnetimeEventListener(pq, new PacketListener() {
                        public void packetReceived(Element e) {
                            if ("challenge".equals(e.name)) {
                                gotChallenge(e);
                                stream.dispatchEvent(BasicXmlStream.STREAM_AUTHENTICATED, null);
                            } else {
                                stream.dispatchEvent(BasicXmlStream.STREAM_ERROR, "Cannot authenticate");
                            }
                        }

                    });
                    stream.send(auth, -1);
                    return;
                } else if (supportedMechanisms[i].equals(MECHANISM_X_GOOGLE_TOKEN)) {
                    auth.setAttribute("mechanism", MECHANISM_X_GOOGLE_TOKEN);
                    String user = Contact.user(stream.jid);
                    String token = GoogleToken.getToken(user, stream.password);

                    try {
                        String jid = Contact.userhost(stream.jid);
                        byte jidbytes[] = Utils.getBytesUtf8(jid);
                        byte tokenbytes[] = Utils.getBytesUtf8(token);
                        byte buf[] = new byte[2 + jidbytes.length + tokenbytes.length];
                        buf[0] = 0;
                        System.arraycopy(jidbytes, 0, buf, 1, jidbytes.length);
                        buf[jidbytes.length + 1] = 0;
                        System.arraycopy(tokenbytes, 0, buf, jidbytes.length + 2, tokenbytes.length);
                        // #mdebug
                        //@                                                               System.out.println(new String(Base64.encode(buf)));
                        // #enddebug
                        auth.addText(new String(Base64.encode(buf)));
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    // listen for the result 
                    EventQuery pq = new EventQuery(EventQuery.ANY_PACKET, null, null);

                    BasicXmlStream.addOnetimeEventListener(pq, new PacketListener() {
                        public void packetReceived(Element e) {
                            if ("success".equals(e.name)) {
                                stream.restart();
                                stream.dispatchEvent(BasicXmlStream.STREAM_AUTHENTICATED, null);
                                return;
                            } else {
                                stream.dispatchEvent(BasicXmlStream.STREAM_ERROR, "Cannot authenticate");
                            }
                        }
                    });

                    stream.send(auth, -1);
                    return;
                }
            }
        }
    }
    // XXX here we should use a different event
    stream.dispatchEvent(BasicXmlStream.STREAM_ERROR, "Cannot find suitable mechanism for authentication");
}

From source file:it.yup.xmlstream.SASLAuthenticator.java

/**
 * Proceed with the challenge reveived from the server (digest md5 auth)
 * @param packet/*from  ww w  .ja  v  a 2  s  . c o m*/
 */
private void gotChallenge(Element packet) {
    try {
        // decode and parse the challenge
        String challengeMessage = new String(Base64.decode(packet.getText()));
        Hashtable challengeDirectives = parse(challengeMessage);

        String response_content;

        if (challengeDirectives.containsKey("rspauth")) {
            response_content = "";
        } else {

            // generate the response
            Hashtable responseDirectives = new Hashtable();
            String nonce = (String) challengeDirectives.get("nonce");
            responseDirectives.put("nonce", nonce);
            String nc = "00000001"; // response sequence number XXX handle subsequents
            responseDirectives.put("nc", nc);

            // XXX very unsecure, but good for now
            String cnonce = Utils.hexDigest("" + System.currentTimeMillis(), "md5");

            responseDirectives.put("cnonce", cnonce);
            String qop = "auth";
            responseDirectives.put("qop", qop);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bos.write(Utils.digest(
                    Contact.user(stream.jid) + ":" + Contact.domain(stream.jid) + ":" + stream.password,
                    "md5"));
            bos.write(Utils.getBytesUtf8(":" + nonce + ":" + cnonce));

            byte A1[] = bos.toByteArray();
            String digest_uri = "xmpp/" + Contact.domain(stream.jid); // XXX don't know if this is correct
            String A2 = ("AUTHENTICATE:" + digest_uri);

            String KD = Utils.bytesToHex(Utils.digest(A1, "md5")) + ":"
                    + (nonce + ":" + nc + ":" + cnonce + ":" + "auth" + ":" + Utils.hexDigest(A2, "md5"));
            String response = Utils.hexDigest(KD, "md5");
            responseDirectives.put("response", response);
            responseDirectives.put("charset", "utf-8");
            responseDirectives.put("digest-uri", digest_uri);
            responseDirectives.put("username", Contact.user(stream.jid));
            responseDirectives.put("realm", Contact.domain(stream.jid));

            // prepare the response putting together all the directives
            response_content = unparse(responseDirectives);
        }

        Element responseElement = new Element(namespace, "response");
        // responseElement.content = new String(Base64.encode(content.getBytes("utf-8")));
        // BASE64 **SHOULD** be UTF-8
        responseElement.addText(new String(Base64.encode(Utils.getBytesUtf8(response_content))));
        EventQuery pq = new EventQuery(EventQuery.ANY_PACKET, null, null);

        BasicXmlStream.addOnetimeEventListener(pq, new PacketListener() {
            public void packetReceived(Element e) {
                if ("success".equals(e.name)) {
                    stream.restart();
                } else if ("challenge".equals(e.name)) {
                    gotChallenge(e);
                } else if ("failure".equals(e.name)) {
                    Element child = e.getChildByName(null, "not-authorized");
                    if (child != null)
                        stream.dispatchEvent(BasicXmlStream.NOT_AUTHORIZED, "Cannot authenticate");
                    else
                        stream.dispatchEvent(BasicXmlStream.REGISTRATION_FAILED, "Cannot registrate");
                } else {
                    stream.dispatchEvent(BasicXmlStream.STREAM_ERROR, "Cannot authenticate");
                }
            }

        });
        stream.send(responseElement, -1);
    } catch (UnsupportedEncodingException e) {
        // YUPMidlet.yup.reportException("UnsupportedEncoding on gotChallenge in SASLAutenticator", e, null);
    } catch (IOException e1) {
        stream.dispatchEvent(BasicXmlStream.STREAM_ERROR,
                "Not enough memory for completing the authentication");
    }
}

From source file:it.yup.xmpp.XMPPClient.java

private String getCapVer() {
    Vector ss = new Vector();
    ss.addElement("client/");
    ss.addElement("phone/");
    ss.addElement("/")/* XXX should be the lang here */;
    ss.addElement("Lampiro " + cfg.getProperty(Config.VERSION) + "<");
    for (int i = 0; i < features.length; i++) {
        ss.addElement(features[i]);/*  ww  w  .  j  a  v  a2 s  .c  o m*/
        ss.addElement("<");
    }
    Enumeration en = ss.elements();
    String S = "";
    while (en.hasMoreElements()) {
        S += en.nextElement();
    }
    S = new String(Base64.encode(Utils.digest(S, "sha1")));
    return S;
}

From source file:jcifs.http.NtlmSsp.java

License:Open Source License

/**
 * Performs NTLM authentication for the servlet request.
 * // w  w w  .j a v  a2  s.  c om
 * @param tc
 *            context to use
 *
 * @param req
 *            The request being serviced.
 * @param resp
 *            The response.
 * @param challenge
 *            The domain controller challenge.
 * @return credentials passed in the servlet request
 * @throws IOException
 *             If an IO error occurs.
 */
public static NtlmPasswordAuthentication authenticate(CIFSContext tc, HttpServletRequest req,
        HttpServletResponse resp, byte[] challenge) throws IOException {
    String msg = req.getHeader("Authorization");
    if (msg != null && msg.startsWith("NTLM ")) {
        byte[] src = Base64.decode(msg.substring(5));
        if (src[8] == 1) {
            Type1Message type1 = new Type1Message(src);
            Type2Message type2 = new Type2Message(tc, type1, challenge, null);
            msg = new String(Base64.encode(type2.toByteArray()), "US-ASCII");
            resp.setHeader("WWW-Authenticate", "NTLM " + msg);
        } else if (src[8] == 3) {
            Type3Message type3 = new Type3Message(src);
            byte[] lmResponse = type3.getLMResponse();
            if (lmResponse == null)
                lmResponse = new byte[0];
            byte[] ntResponse = type3.getNTResponse();
            if (ntResponse == null)
                ntResponse = new byte[0];
            return new NtlmPasswordAuthentication(type3.getDomain(), type3.getUser(), challenge, lmResponse,
                    ntResponse);
        }
    } else {
        resp.setHeader("WWW-Authenticate", "NTLM");
    }
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    resp.setContentLength(0);
    resp.flushBuffer();
    return null;
}

From source file:jcrypter.JCrypterFrame.java

License:Apache License

private void encryptSymmetric() {
    try {//w  w  w. j  a  va 2 s .  c  o m
        //cipher field is initalized by the cmp dialog and at the beginning

        //Using BouncyCastle JCEs
        int bs = cipher.getBlockSize(); //Blocksize
        //Get data
        byte[] passwordBytes = new String(passwordField.getPassword()).getBytes();
        byte[] input;
        //Base64-decode the ciphertext
        input = inputField.getText().getBytes();

        //All data is written to this stream
        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        //Hash the password to fit it into the right size (with salt)
        byte[] salt = new byte[8];
        byte[] keyBytes = new byte[32]; //Assume a 256-bit key
        rand.nextBytes(salt);
        bout.write(salt); //Write the salt to the stream

        Digest digest = new SHA256Digest(); //Assume a 256-bit key
        digest.update(salt, 0, salt.length); //Add the salt...
        digest.update(passwordBytes, 0, passwordBytes.length); //...and the password to the generator
        digest.doFinal(keyBytes, 0); //Do the final hashing

        //Generate the iv and the IvParameter spec
        byte[] iv = new byte[cipher.getBlockSize()];
        rand.nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv, 0, bs);

        //Generate the secret key spec
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, cmpDialog.getCipher());
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

        CipherOutputStream cout = new CipherOutputStream(bout, cipher);

        //If print the IV into bout
        bout.write(iv);
        cout.write(input);
        //All data has been written so close the streams
        cout.close();
        bout.close();
        //Print the output into outputField and Base64-encode if we have to encrypt
        outputField.setText(new String(Base64.encode(bout.toByteArray())));
    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) //Must not occure
    {
        Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:jenkins.bouncycastle.api.PEMEncodable.java

License:Open Source License

/**
 * Encodes a {@link byte[]} in base 64 string
 * /*from  w w  w. j a  v  a2  s.c om*/
 * @param data to be encoded
 * @return base 64 formatted string
 */
@Nonnull
private static String encodeBase64(@Nonnull byte[] data) {
    return new String(Base64.encode(data), StandardCharsets.UTF_8);
}