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:cc.telepath.phage.PhageIdentity.java

License:GNU General Public License

/**
 * Discover a secret channel that has been announced to our key.
 * @param PhageGroupPubKey/*from  ww w .  j ava2  s. c  om*/
 * @param pcl
 * @return
 * @throws IOException
 * @throws FcpException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 */
public void discoverSecretChannel(String PhageGroupPubKey, PhageFCPClient pcl) throws InvalidSigException,
        IOException, FcpException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException,
        NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, SignatureException {
    Base64 base64 = new Base64();
    Hex hex = new Hex();
    Crypto c = new Crypto();
    String ownkey = new String(base64.encode(this.pubKey.getEncoded()));
    String combination;
    if (PhageGroupPubKey.compareTo(ownkey) < 0) {
        combination = PhageGroupPubKey + ownkey;
    } else {
        combination = ownkey + PhageGroupPubKey;
    }
    MessageDigest md = MessageDigest.getInstance("SHA-512");
    md.update(combination.getBytes());
    byte[] rendezvousbytes = md.digest();
    String rendezvous = "KSK@" + new String(hex.encode(rendezvousbytes));
    String secretChannelAnnouncement = new String(pcl.getData(rendezvous));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey groupPk = kf.generatePublic(new X509EncodedKeySpec(base64.decode(PhageGroupPubKey)));
    boolean sigValid = c.sigValid(secretChannelAnnouncement.split(":")[0],
            secretChannelAnnouncement.split(":")[1], groupPk);
    String message = c.decryptMessage(this.getPrivkey(), secretChannelAnnouncement.split(":")[0]);
    System.out.println("SecretChannel: " + message);
    if (!sigValid) {
        throw new InvalidSigException("The message signature from " + PhageGroupPubKey
                + "failed!! Either invalid data was provided or somebody is impersonating this identity.");
    } else {
        this.contactChannel = message;
    }

}

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

License:GNU General Public License

@Override
public String toString() {
    Base64 base64 = new Base64();
    return base64.encode(this.getPubkey().getEncoded()) + ":" + this.getFreenetPubkey();
}

From source file:cc.telepath.phage.util.Crypto.java

License:GNU General Public License

/**
 * Returns a base64 encoded 256-bit AES Key
 * @return//from  w w w.  j  a va  2 s. com
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public String generateAESKey() throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
        NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
    SecureRandom sr = new SecureRandom();
    Base64 base64 = new Base64();
    byte[] keyBytes = new byte[32];
    sr.nextBytes(keyBytes);
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    return new String(base64.encode(key.getEncoded()));
}

From source file:cc.telepath.phage.util.Crypto.java

License:GNU General Public License

/**
 * Returns a base64 encoded pair of strings separated by a colon. The first is the encrypted message, the second is
 * the signature of that base64 encoded encrypted message.
 * @param pubkey/*from  w  ww. j  a  v a 2 s .  c om*/
 * @param privKey
 * @param message
 * @return
 * @throws InvalidKeyException
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 * @throws SignatureException
 */
public String encryptAndSign(PublicKey pubkey, PrivateKey privKey, String message)
        throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
        IllegalBlockSizeException, SignatureException {
    Base64 base64 = new Base64();
    Cipher cipher = Cipher.getInstance(pubkey.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, pubkey);

    byte[] encryptData = cipher.doFinal(message.getBytes());

    Signature sig = Signature.getInstance("SHA512withRSA");
    sig.initSign(privKey);
    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));
    return encryptedMessage + ":" + signature;
}

From source file:cc.telepath.phage.util.Crypto.java

License:GNU General Public License

/**
 * Convert an arbitrary length password to a base64 encoded 256-bit AES key.
 * @param password//from   ww w .  j  av a 2  s  .  c o  m
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public String passwordToAESKey(String password) throws NoSuchAlgorithmException, NoSuchProviderException {
    Base64 base64 = new Base64();
    MessageDigest md = MessageDigest.getInstance("SHA512", "BC");
    md.update(password.getBytes());
    byte[] passwordBytes = Arrays.copyOfRange(md.digest(), 0, 32);
    return new String(base64.encode(passwordBytes));
}

From source file:cf.monteux.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * converts a JCERSAPublicKey into PEM/PKCS1-encoding.
 *
 * @param rsaPublicKey/*w  w w.  j  av a2 s. c  o m*/
 * @return PEM-encoded RSA PUBLIC KEY
 */
public static String getPEMStringFromRSAPublicKey(final RSAPublicKey rsaPublicKey) {

    // mrk: this was awful to program. Remeber: There are two entirely
    // different
    // standard formats for rsa public keys. Bouncy castle does only support
    // the
    // one we can't use for TOR directories.

    final StringBuffer tmpDirSigningKey = new StringBuffer();

    try {

        tmpDirSigningKey.append("-----BEGIN RSA PUBLIC KEY-----\n");

        final byte[] base64Encoding = Base64.encode(getPKCS1EncodingFromRSAPublicKey(rsaPublicKey));
        for (int i = 0; i < base64Encoding.length; i++) {
            tmpDirSigningKey.append((char) base64Encoding[i]);
            if (((i + 1) % 64) == 0) {
                tmpDirSigningKey.append("\n");
            }
        }
        tmpDirSigningKey.append("\n");

        tmpDirSigningKey.append("-----END RSA PUBLIC KEY-----\n");
    } catch (final Exception e) {
        return null;
    }

    return tmpDirSigningKey.toString();
}

From source file:cn.ieclipse.pde.signer.util.BcpSigner.java

License:Apache License

/** Add the SHA1 of every file to the manifest, creating it if necessary. */
private static Manifest addDigestsToManifest(JarFile jar) throws IOException, GeneralSecurityException {
    Manifest input = jar.getManifest();
    Manifest output = new Manifest();
    Attributes main = output.getMainAttributes();
    if (input != null) {
        main.putAll(input.getMainAttributes());
    } else {/* w ww.  ja  v  a 2 s.c  o m*/
        main.putValue("Manifest-Version", "1.0");
        main.putValue("Created-By", CREATED);
    }

    MessageDigest md = MessageDigest.getInstance("SHA1");
    byte[] buffer = new byte[4096];
    int num;

    // We sort the input entries by name, and add them to the
    // output manifest in sorted order. We expect that the output
    // map will be deterministic.

    TreeMap<String, JarEntry> byName = new TreeMap<String, JarEntry>();

    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = e.nextElement();
        byName.put(entry.getName(), entry);
    }

    for (JarEntry entry : byName.values()) {
        String name = entry.getName();
        if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME)
                && !name.equals(CERT_RSA_NAME) && !name.equals(OTACERT_NAME)
                && (stripPattern == null || !stripPattern.matcher(name).matches())) {
            InputStream data = jar.getInputStream(entry);
            while ((num = data.read(buffer)) > 0) {
                md.update(buffer, 0, num);
            }

            Attributes attr = null;
            if (input != null)
                attr = input.getAttributes(name);
            attr = attr != null ? new Attributes(attr) : new Attributes();
            attr.putValue("SHA1-Digest", new String(Base64.encode(md.digest()), "ASCII"));
            output.getEntries().put(name, attr);
        }
    }

    return output;
}

From source file:cn.ieclipse.pde.signer.util.BcpSigner.java

License:Apache License

/**
 * Add a copy of the public key to the archive; this should exactly match
 * one of the files in /system/etc/security/otacerts.zip on the device. (The
 * same cert can be extracted from the CERT.RSA file but this is much easier
 * to get at.)//from  w  ww.j  av a  2s.  c om
 */
private static void addOtacert(JarOutputStream outputJar, File publicKeyFile, long timestamp, Manifest manifest)
        throws IOException, GeneralSecurityException {
    MessageDigest md = MessageDigest.getInstance("SHA1");

    JarEntry je = new JarEntry(OTACERT_NAME);
    je.setTime(timestamp);
    outputJar.putNextEntry(je);
    FileInputStream input = new FileInputStream(publicKeyFile);
    byte[] b = new byte[4096];
    int read;
    while ((read = input.read(b)) != -1) {
        outputJar.write(b, 0, read);
        md.update(b, 0, read);
    }
    input.close();

    Attributes attr = new Attributes();
    attr.putValue("SHA1-Digest", new String(Base64.encode(md.digest()), "ASCII"));
    manifest.getEntries().put(OTACERT_NAME, attr);
}

From source file:cn.ieclipse.pde.signer.util.BcpSigner.java

License:Apache License

/** Write a .SF file with a digest of the specified manifest. */
private static void writeSignatureFile(Manifest manifest, OutputStream out)
        throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", CREATED);

    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);/*from   w w w  .j  av  a 2  s .c  o  m*/
    print.flush();
    main.putValue("SHA1-Digest-Manifest", new String(Base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue("SHA1-Digest", new String(Base64.encode(md.digest()), "ASCII"));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }

    CountOutputStream cout = new CountOutputStream(out);
    sf.write(cout);

    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((cout.size() % 1024) == 0) {
        cout.write('\r');
        cout.write('\n');
    }
}

From source file:cn.ieclipse.pde.signer.util.SignApk.java

License:Apache License

/** Add the SHA1 of every file to the manifest, creating it if necessary. */
private static Manifest addDigestsToManifest(JarFile jar) throws IOException, GeneralSecurityException {
    Manifest input = jar.getManifest();
    Manifest output = new Manifest();
    Attributes main = output.getMainAttributes();
    if (input != null) {
        main.putAll(input.getMainAttributes());
    } else {//from ww  w  . j a va  2 s .  c  om
        main.putValue("Manifest-Version", "1.0");
        main.putValue("Created-By", "1.0 (Android SignApk)");
    }

    MessageDigest md = MessageDigest.getInstance("SHA1");
    byte[] buffer = new byte[4096];
    int num;

    // We sort the input entries by name, and add them to the
    // output manifest in sorted order. We expect that the output
    // map will be deterministic.

    TreeMap<String, JarEntry> byName = new TreeMap<String, JarEntry>();

    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = e.nextElement();
        byName.put(entry.getName(), entry);
    }

    for (JarEntry entry : byName.values()) {
        String name = entry.getName();
        if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME)
                && !name.equals(CERT_RSA_NAME) && !name.equals(OTACERT_NAME)
                && (stripPattern == null || !stripPattern.matcher(name).matches())) {
            InputStream data = jar.getInputStream(entry);
            while ((num = data.read(buffer)) > 0) {
                md.update(buffer, 0, num);
            }

            Attributes attr = null;
            if (input != null)
                attr = input.getAttributes(name);
            attr = attr != null ? new Attributes(attr) : new Attributes();
            attr.putValue("SHA1-Digest", new String(Base64.encode(md.digest()), "ASCII"));
            output.getEntries().put(name, attr);
        }
    }

    return output;
}