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:bluecrystal.service.v1.icpbr.IcpbrServiceImpl.java

License:Open Source License

public String extractSignerCert(String signb64) throws Exception {
    LogDebug("extractSignCompare: " + "\nsignb64 (" + signb64 + ")");
    try {/*  w  ww  . jav  a  2 s . c  om*/
        byte[] sign = Base64.decode(signb64);
        X509Certificate certEE = certServ.decodeEE(sign);
        return new String(Base64.encode(certEE.getEncoded()));
    } catch (Exception e) {
        LOG.error("ERRO: ", e);
        throw e;
    }
}

From source file:bluecrystal.service.v1.rebuilder.EnvelopeRebuildServiceImpl.java

License:Open Source License

@Override
public String rebuildEnvelope(int format, String envelopeb64) throws Exception {
    byte[] ret = null;
    Base64 b64 = new Base64();

    switch (format) {
    case CMS_WITH_CHAIN:
        ret = cmsWithChain.rebuildEnvelope(b64.decode(envelopeb64));
        break;/*from  w ww  .  j  a v  a2s. c  o m*/

    default:
        break;
    }

    return new String(b64.encode(ret));
}

From source file:br.gov.jfrj.siga.base.Correio.java

License:Open Source License

private static void enviarParaServidor(final String servidorEmail, String remetente,
        final String[] destinatarios, final String assunto, final String conteudo, final String conteudoHTML)
        throws Exception {
    // Cria propriedades a serem usadas na sesso.
    final Properties props = new Properties();

    // Define propriedades da sesso.
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", servidorEmail);
    props.put("mail.host", servidorEmail);
    props.put("mail.mime.charset", "UTF-8");

    // Cria sesso. setDebug(true)  interessante pois
    // mostra os passos do envio da mensagem e o
    // recebimento da mensagem do servidor no console.
    Session session = null;//from w ww . j a v a2  s  . c  o m
    if (Boolean.valueOf(SigaBaseProperties.getString("servidor.smtp.auth"))) {
        props.put("mail.smtp.auth", "true");
        final String usuario = SigaBaseProperties.getString("servidor.smtp.auth.usuario");
        final String senha = SigaBaseProperties.getString("servidor.smtp.auth.senha");
        session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(usuario, senha);
            }
        });
    } else {
        session = Session.getInstance(props);
    }

    final boolean debug = Boolean.parseBoolean("false");
    // final boolean debug = Boolean.parseBoolean(Mensagens
    // .getString("servidor.smtp.debug"));
    session.setDebug(debug);
    // Cria mensagem e seta alguns valores que constituem
    // os seus headers.
    final Message msg = new MimeMessage(session);

    try {
        if (destinatarios.length == 1) {
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(destinatarios[0]));

        } else {
            Set<String> destSet = new HashSet<String>();
            for (String s : destinatarios) {
                if (!destSet.contains(s))
                    destSet.add(s);
            }

            final InternetAddress[] endereco = new InternetAddress[destSet.size()];
            int i = 0;
            for (String email : destSet) {
                endereco[i] = new InternetAddress(email);
                i++;
            }
            msg.setRecipients(Message.RecipientType.TO, endereco);
        }
        msg.setFrom(new InternetAddress(remetente));
        msg.setSubject(assunto);

        if (conteudoHTML == null) {
            // msg.setText(conteudo);
            msg.setSubject(assunto);
            msg.setContent(conteudo, "text/plain;charset=UTF-8");
        } else {
            Multipart mp = new MimeMultipart("alternative");

            // Add text version
            InternetHeaders ihs = new InternetHeaders();
            ihs.addHeader("Content-Type", "text/plain; charset=UTF-8");
            ihs.addHeader("Content-Transfer-Encoding", "base64");
            MimeBodyPart mb1 = new MimeBodyPart(ihs, Base64.encode(conteudo.getBytes("utf-8")));
            mp.addBodyPart(mb1);

            // Do the same with the HTML part
            InternetHeaders ihs2 = new InternetHeaders();
            ihs2.addHeader("Content-Type", "text/html; charset=UTF-8");
            ihs2.addHeader("Content-Transfer-Encoding", "base64");
            MimeBodyPart mb2 = new MimeBodyPart(ihs2, Base64.encode(conteudoHTML.getBytes("utf-8")));
            mp.addBodyPart(mb2);

            // Set the content for the message and transmit
            msg.setContent(mp);
        }

        // Envia mensagem.
        //Transport.send(msg);

        Transport tr = new br.gov.jfrj.siga.base.SMTPTransport(session, null);
        tr.connect(servidorEmail, Integer.valueOf(SigaBaseProperties.getString("servidor.smtp.porta")), null,
                null);
        msg.saveChanges(); // don't forget this
        tr.sendMessage(msg, msg.getAllRecipients());
        tr.close();

    } catch (final Exception e) {
        throw e;
    }
}

From source file:br.gov.jfrj.siga.base.Criptografia.java

License:Open Source License

public static void main(String[] args) throws Exception {

    if (args.length != 2) {
        throw new Exception("Parmetros invlidos!\n"
                + "Use: Criptografia [mensagem que sera criptografada] [chave da criptografia]");
    }// w  w  w  .  j  av a 2s  .  c  o m

    String mensagem = args[0];
    String chave = new String(Base64.encode(args[1].getBytes()));

    byte[] msgCriptografada = Criptografia.criptografar(mensagem, chave);

    System.out.println("mensagem criptografada com " + ALGORITMO_CRIPTOGRAFICO + " Em Hex: "
            + asHex(msgCriptografada) + " Em Base64 " + new String(Base64.encode(msgCriptografada)));

    byte[] msgDescriptografada = Criptografia.desCriptografar(msgCriptografada, chave);

    String msgOriginal = new String(msgDescriptografada);

    System.out.println("mensagem original: " + msgOriginal + "  Em HEX:" + asHex(msgDescriptografada));
}

From source file:brooklyn.util.text.DataUriSchemeParserTest.java

License:Apache License

@Test
public void testBase64() {
    Assert.assertEquals(//  w ww . ja  v  a 2s  .  c o  m
            DataUriSchemeParser.toString("data:;base64," + new String(Base64.encode("hello".getBytes()))),
            "hello");
}

From source file:cc.telepath.phage.Phage.java

License:GNU General Public License

/**
 * Write config file.// w  w  w  .ja  v  a 2s .c om
 * Must be encrypted with password.
 * @param configFile
 * @param password
 */
public void writeConfig(String configFile, String password) {
    try {
        Base64 base64 = new Base64();
        Crypto c = new Crypto();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this.communities);
        String key = c.passwordToAESKey(password);
        byte[] encryptedObj = c.AESEncrypt(bos.toByteArray(), key);
        BufferedWriter bw = new BufferedWriter(new FileWriter(configFile));
        bw.write(new String(base64.encode(encryptedObj)));
        bw.close();
        oos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cc.telepath.phage.Phage.java

License:GNU General Public License

public static void main(String args[])
        throws IOException, FcpException, IllegalBlockSizeException, BadPaddingException,
        NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        SignatureException, InvalidKeyException, InvalidSigException, InvalidAlgorithmParameterException {
    final PhageFCPClient pcl = new PhageFCPClient();
    pcl.connect("127.0.0.1");
    Phage p = new Phage();
    Crypto c = new Crypto();
    Base64 base64 = new Base64();
    String encryptedText = new String(base64.encode(
            c.AESEncrypt("This is a test AES Encrypted message.".getBytes(), c.passwordToAESKey("Dongs"))));
    System.out.println(new String(c.AESDecrypt(base64.decode(encryptedText), c.passwordToAESKey("Dongs"))));
    boolean passphraseProvided = false;
    HashMap<String, String> keys = pcl.generateKeypair();
    KeyPair k = c.generateKeypair();
    PhageIdentity a = new PhageIdentity(k.getPublic(), k.getPrivate(), keys.get("public"), keys.get("private"));
    keys = pcl.generateKeypair();/*  w  w  w.ja  v a 2  s.c o m*/
    k = c.generateKeypair();
    PhageIdentity b = new PhageIdentity(k.getPublic(), k.getPrivate(), keys.get("public"), keys.get("private"));
    keys = pcl.generateKeypair();
    k = c.generateKeypair();
    PhageIdentity d = new PhageIdentity(k.getPublic(), k.getPrivate(), keys.get("public"), keys.get("private"));
    keys = pcl.generateKeypair();
    k = c.generateKeypair();
    PhageIdentity e = new PhageIdentity(k.getPublic(), k.getPrivate(), keys.get("public"), keys.get("private"));
    k = c.generateKeypair();
    keys = pcl.generateKeypair();
    PhageGroup pg = new PhageGroup(k.getPublic(), k.getPrivate(), keys.get("public"), keys.get("private"),
            "TestGroup");
    pg.generateEpochKey();
    pg.importIdentity(a);
    pg.importIdentity(b);
    //        pg.importIdentity(d);
    //        pg.importIdentity(e);
    pg.membershipAnnouncement(pcl);
    pg.advertiseChannel(a, pcl);
    pg.advertiseChannel(b, pcl);
    //        pg.advertiseChannel(d, pcl);
    //        pg.advertiseChannel(e, pcl);
    a.discoverSecretChannel(new String(base64.encode(pg.getPublicKey().getEncoded())), pcl);
    b.discoverSecretChannel(new String(base64.encode(pg.getPublicKey().getEncoded())), pcl);
    //        d.discoverSecretChannel(new String(base64.encode(pg.getPublicKey().getEncoded())),pcl);
    //        e.discoverSecretChannel(new String(base64.encode(pg.getPublicKey().getEncoded())),pcl);
    pg.newEpochAnnouncement(pg.getEpochKeys().get(pg.getEpochKeys().size() - 1), pcl);

    final String URI = pg.getFreenetPublicKey().replace("SSK@", "USK@") + "0";
    Thread t = new Thread() {
        public void run() {
            try {
                pcl.subscribeUSK(URI);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (FcpException e) {
                e.printStackTrace();
            }
        }

    };
    t.start();
    //pg.membershipAnnouncement(pcl);
    byte[] memberlistbytes = pcl.getData(a.getContactChannel());
    String memberlist = new String(memberlistbytes);
    System.out.println("Recovered key: " + c.decryptMessage(a.getPrivkey(), memberlist.split(":")[0]));
    String recoveredKey = c.decryptMessage(a.getPrivkey(), memberlist.split(":")[0]);
    System.out.println("MEMBERLIST DATA: " + memberlist);
    //        System.out.println("Second half:" + memberlist.split(":")[1]);
    //        String AESDecryptedMessage = c.AESDecrypt()
    System.out.println(new String(c.AESDecrypt(base64.decode(memberlist.split(":")[2]),
            c.decryptMessage(a.getPrivkey(), memberlist.split(":")[0]))));
    //System.out.println("Recovered message:" + new String(c.AESDecrypt(base64.decode(memberlist.split(":")[1]),recoveredKey)));
    //pcl.putData(null, "This is some more test data".getBytes(), keys.get("private"), "messages", "text/plain", true);
    pcl.close();
    System.exit(0);

    //
    //        port(8890);
    //        staticFiles.location("/public");
    //
    //        get("/create", (req, res) -> {
    //            return null;
    //        });
    //
    //        get("/config", (req, res) -> {return null;});
    //
    //        post("/create", (req, res) -> {
    //            System.out.println(req.queryParams("communityname"));
    //            return req.queryParams("communityname");
    //        });
    //
    //        get("/", (req, res) -> {
    //            Map<Object, String> model = new HashMap<>();
    //            model.put("passphraseProvided", passphraseProvided);
    //            return new ModelAndView(new HashMap<>(), "main.vm");
    //        }, new VelocityTemplateEngine());
    //
    //        get("/hello", (req, res) -> {
    //            Map<String, Object> model = new HashMap<>();
    //            model.put("message", "Fuck the police!");
    //
    //            // The vm files are located under the resources directory
    //            return new ModelAndView(model, "hello.vm");
    //        }, new VelocityTemplateEngine());
    //
    //        get("/shutdown", (req, res) -> {
    //            stop();
    //            System.exit(0);
    //            return null;
    //        });

}

From source file:cc.telepath.phage.PhageGroup.java

License:GNU General Public License

/**
 * Establish a secure channel with a specific PhageIdentity.
 * The original contact point is determinitstic - take the hash of both keys concatenatd in descending order.
 * Return the secret channel being used to share the current communication AES keys.
 * @param i//from   w  w  w . ja v  a 2s .  com
 * @return secretchannel
 */
public String advertiseChannel(PhageIdentity i, PhageFCPClient pcl)
        throws IOException, FcpException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    Base64 base64 = new Base64();
    Hex hex = new Hex();
    String ownkey = new String(base64.encode(this.PublicKey.getEncoded()));
    String identkey = new String(base64.encode(i.getPubkey().getEncoded()));

    String combination = null;
    if (ownkey.compareTo(identkey) < 0) {
        combination = ownkey + identkey;
    } else {
        combination = identkey + ownkey;
    }

    // Generate a 100 character random KSK for us to meet at
    RandomStringUtils rsu = new RandomStringUtils();
    String channel = rsu.randomAlphanumeric(100);

    Cipher cipher = Cipher.getInstance(i.getPubkey().getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, i.getPubkey());
    String secretchannel = "KSK@" + channel;
    byte[] encryptData = cipher.doFinal(secretchannel.getBytes());

    Signature sig = Signature.getInstance("SHA512withRSA");
    sig.initSign(PrivateKey);
    sig.update(new String(base64.encode(encryptData)).getBytes());
    byte[] signatureBytes = sig.sign();
    String encryptedMessage = new String(base64.encode(encryptData));
    String signature = new String(base64.encode(signatureBytes));

    MessageDigest md = MessageDigest.getInstance("SHA-512");
    md.update(combination.getBytes());
    byte[] rendezvousbytes = md.digest();

    String rendezvous = new String(hex.encode(rendezvousbytes));
    String URI = pcl.putData(rendezvous, (encryptedMessage + ":" + signature).getBytes(), null, null,
            "text/plain", false);
    this.privateChannels.put(i.getFreenetPubkey(), secretchannel);
    return secretchannel;
}

From source file:cc.telepath.phage.PhageGroup.java

License:GNU General Public License

/**
 * Announce a new AES Key on all private channels.
 *//* ww  w  .  j a va  2  s.c  o m*/
public void newEpochAnnouncement(String newKey, PhageFCPClient pcl)
        throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException,
        SignatureException, InvalidKeyException, IOException, FcpException, NoSuchProviderException {
    Crypto c = new Crypto();
    Base64 base64 = new Base64();
    GsonBuilder b = new GsonBuilder();
    b.disableHtmlEscaping();
    Gson g = b.create();
    for (PhageIdentity pi : identityList) {
        EpochAnnouncement announcement = new EpochAnnouncement(newKey, identityList);
        String stringAnnouncement = g.toJson(announcement);
        String AESkey = c.generateAESKey();
        byte[] encryptedAnnouncement = c.AESEncrypt(stringAnnouncement.getBytes(), AESkey);
        //EncrypotAndSign adds a colon to the string so we've been checking the wrong string
        //FIXME
        String encryptedKey = c.encryptAndSign(pi.getPubkey(), this.PrivateKey, AESkey);
        try {
            System.out.println(
                    c.AESDecrypt(base64.decode(new String(base64.encode(encryptedAnnouncement))), AESkey));
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        System.out.println("Membership announcement on "
                + pcl.putData(privateChannels.get(pi.getFreenetPubkey()).replace("KSK@", ""),
                        (encryptedKey + ":" + new String(base64.encode(encryptedAnnouncement))).getBytes(),
                        null, null, "text/plain", false));
    }
}

From source file:cc.telepath.phage.PhageGroup.java

License:GNU General Public License

/**
 * Use the most recent epoch key to encrypt and publish a full list of member public keys and Freenet publickeys
 * @param pcl//w  ww.j  av a  2 s .c om
 */
public void membershipAnnouncement(PhageFCPClient pcl) {
    Crypto c = new Crypto();
    Base64 base64 = new Base64();
    String membershipList = "";
    for (PhageIdentity i : this.identityList) {
        membershipList += i + "\n";
    }
    String encryptedList = new String(
            base64.encode(c.AESEncrypt(membershipList.getBytes(), this.epochKeys.get(epochKeys.size() - 1))));
    System.out.println("Announcement on: " + pcl.putData(null, encryptedList.getBytes(), this.freenetPrivateKey,
            "memberList", "text/plain", true));

}