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

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

Introduction

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

Prototype

Base64

Source Link

Usage

From source file:Util.java

License:Apache License

/**
 * // Takes a screen shot if the driver's capabilities include Screen Shots
 * @param driver        The Web Driver instance
 * @param outputType    Either FILE or Base64
 * @param folder        The folder for images
 * @param filename      The base file name (sans time stamp)
 * @return              Error string starting with ERROR: if failed to create file or the file name that was created
 *//*from ww w.  j a v  a2 s.c o  m*/
public static String takeScreenImage(WebDriver driver, String folder, String fileName) {
    String result = "";
    WebDriver theDriver = Driver.getDriver();

    if (!(theDriver instanceof WebDriver)) {
        return "ERROR: No Web Driver found at this step!";
    }

    if (!((HasCapabilities) theDriver).getCapabilities().is(CapabilityType.TAKES_SCREENSHOT)) {
        return "ERROR: Driver " + Util.sq(theDriver.toString())
                + " has no TAKES_SCREENSHOT capabilities.  Screen shot not taken";
    }

    String imagesFolder = (isBlank(folder)) ? DDTTestRunner.getReporter().sessionImagesFolderName() : folder;

    try {
        File testTempDir = new File(DDTSettings.asValidOSPath(imagesFolder, true));
        if (testTempDir.exists()) {
            if (!testTempDir.isDirectory()) {
                return "ERROR: Image path exists but is not a directory";
            }
        } else {
            testTempDir.mkdirs();
        }
    } catch (Exception e) {
        return "ERROR: File operation (mkdir) failed. " + e.getCause();
    }

    String actualFileName = fileName + " - " + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date())
            + ".png";

    // create screenshot using a casted driver
    TakesScreenshot snapper = (TakesScreenshot) theDriver;

    if (DDTSettings.Settings().isLocal()) {
        File tempImageFile = snapper.getScreenshotAs(OutputType.FILE);
        if (tempImageFile.length() < (1L)) {
            return "ERROR: Failed to take screen shot on remote driver";
        }

        File tmpFile = new File(imagesFolder, DDTSettings.asValidOSPath(actualFileName, true)); // testTempImage
        // move screenshot to our local store
        try {
            FileUtils.moveFile(tempImageFile, tmpFile);
        } catch (Exception e) {
            return "ERROR: Failed to move tmp file to image file. " + Util.sq(tmpFile.getAbsolutePath()) + " "
                    + e.getCause().toString();
        }

        if (tmpFile.length() < 1L) {
            return "ERROR: Failed to move tmp file to image file. " + Util.sq(tmpFile.getAbsolutePath());
        }

        result = tmpFile.getAbsolutePath();
    } else {
        // Create Base64 screen shot file on the remote driver and store it locally
        String tempImageFile = snapper.getScreenshotAs(OutputType.BASE64);
        if (tempImageFile.length() < (1L)) {
            return "ERROR: Failed to take screen shot on remote driver";
        }

        Base64 decoder = new Base64();
        byte[] imgBytes = (byte[]) decoder.decode(tempImageFile);

        File tmpFile = new File(imagesFolder, DDTSettings.asValidOSPath(actualFileName, true));

        FileOutputStream osf = null;
        try {
            osf = new FileOutputStream(tmpFile);
            osf.write(imgBytes);
            osf.flush();
        } catch (Exception e) {
            return "ERROR: Failed to create File Output Stream " + e.getCause();
        }

        if (tmpFile.length() < 1L) {
            return "ERROR: File created from  File Output Stream is empty!";
        }

        result = tmpFile.getAbsolutePath();
    }

    return result;
}

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  w  w .j  av  a2 s . co  m*/

    default:
        break;
    }

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

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

License:GNU General Public License

/**
 * Write config file.//from w  ww. j  a  v a  2s. c o m
 * 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

/**
 * Read config file./*from  www.j av  a 2 s  . c  o  m*/
 * Must be decrypted with password.
 * This is insanely unsafe but will at least make it harder to recovery sensitive info.
 * TODO: Convert to JSON
 * @param configFile
 * @param password
 */
public void readConfig(String configFile, String password) throws FileNotFoundException {
    try {
        Crypto c = new Crypto();
        Base64 base64 = new Base64();
        BufferedReader br = new BufferedReader(new FileReader(configFile));
        String encryptedConfig = br.readLine();
        String key = c.passwordToAESKey(password);
        byte[] encryptedObj = c.AESDecrypt(base64.decode(encryptedConfig), key);
        ByteArrayInputStream bis = new ByteArrayInputStream(encryptedObj);
        ObjectInputStream ois = new ObjectInputStream(bis);
        ArrayList<PhageGroup> communities = (ArrayList<PhageGroup>) ois.readObject();
        System.out.println(communities);
        this.communities = communities;
    } catch (BadPaddingException e) {
        System.out.println("Incorrect AES Key when decrypting config file.");
    } 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();/*from  ww w .ja v a  2  s  . co  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  .j a  v a  2 s.c o m*/
 * @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

/**
 * When it's time for a new Epoch, add a new key. Announcement comes separately.
 * @throws BadPaddingException//from  w w w.j  a v a2 s  .  co  m
 * @throws NoSuchAlgorithmException
 * @throws IllegalBlockSizeException
 * @throws NoSuchProviderException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 */
public void generateEpochKey() {
    Crypto c = new Crypto();
    Base64 base64 = new Base64();
    try {
        String newKey = c.generateAESKey();
        this.epochKeys.add(newKey);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

License:GNU General Public License

/**
 * Announce a new AES Key on all private channels.
 *///from w w w.jav  a 2 s.  com
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//from  w  ww. j  av  a2s.c  o m
 */
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));

}

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

License:GNU General Public License

/**
 * Takes a base64 encoded string//from w  w  w .  j a v a  2  s  .  c  o m
 * @param privateKey
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public void setPrivateKey(String privateKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    Base64 base64 = new Base64();
    this.PrivateKey = KeyFactory.getInstance("RSA", "BC")
            .generatePrivate(new X509EncodedKeySpec(base64.decode(privateKey)));
}