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:com.geoxp.oss.client.OSSClient.java

License:Apache License

public static void putSecret(String ossURL, String secretname, byte[] secret, String sshKeyFingerprint)
        throws OSSException {

    SSHAgentClient agent = null;/*  w w  w .ja v  a2 s. c  om*/

    HttpClient httpclient = null;

    try {
        agent = new SSHAgentClient();

        List<SSHKey> sshkeys = agent.requestIdentities();

        //
        // If no SSH Key fingerprint was provided, try all SSH keys available in the agent
        //

        List<String> fingerprints = new ArrayList<String>();

        if (null == sshKeyFingerprint) {
            for (SSHKey key : sshkeys) {
                fingerprints.add(key.fingerprint);
            }
        } else {
            fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", ""));
        }

        int idx = 0;

        for (String fingerprint : fingerprints) {
            idx++;

            //
            // Ask the SSH agent for the SSH key blob
            //

            byte[] keyblob = null;

            for (SSHKey key : sshkeys) {
                if (key.fingerprint.equals(fingerprint)) {
                    keyblob = key.blob;
                    break;
                }
            }

            //
            // Throw an exception if this condition is encountered as it can only happen if
            // there was a provided fingerprint which is not in the agent.
            //

            if (null == keyblob) {
                throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent.");
            }

            //
            // Retrieve OSS RSA key
            //

            RSAPublicKey pubkey = getOSSRSA(ossURL);

            //
            // Build the token
            //
            // <TS> <<WRAPPED_SECRET><ENCRYPTED_WRAPPING_KEY>> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

            token.write(CryptoHelper.encodeNetworkString(tsdata));

            ByteArrayOutputStream subtoken = new ByteArrayOutputStream();

            subtoken.write(CryptoHelper.encodeNetworkString(secretname.getBytes("UTF-8")));
            subtoken.write(CryptoHelper.encodeNetworkString(secret));

            token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray()));

            token.write(CryptoHelper.encodeNetworkString(keyblob));

            byte[] sigblob = agent.sign(keyblob, token.toByteArray());

            token.write(CryptoHelper.encodeNetworkString(sigblob));

            //
            // Encrypt the token with a random AES256 key
            //

            byte[] aeskey = new byte[32];
            CryptoHelper.getSecureRandom().nextBytes(aeskey);

            byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray());

            //
            // Encrypt the random key with OSS' RSA key
            //

            byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey);

            //
            // Create the token
            //

            token.reset();

            token.write(CryptoHelper.encodeNetworkString(wrappedtoken));
            token.write(CryptoHelper.encodeNetworkString(sealedaeskey));

            //
            // Base64 encode the encryptedtoken
            //

            String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8");

            //
            // Send request to OSS
            //

            URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_PUT_SECRET);

            builder.addParameter("token", b64token);

            URI uri = builder.build();

            String qs = uri.getRawQuery();

            HttpPost post = new HttpPost(
                    uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath());

            post.setHeader("Content-Type", "application/x-www-form-urlencoded");

            post.setEntity(new StringEntity(qs));

            httpclient = new DefaultHttpClient();

            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            String content = EntityUtils.toString(resEntity, "UTF-8");

            post.reset();

            if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) {
                // Only throw an exception if this is the last SSH key we could try
                if (idx == fingerprints.size()) {
                    throw new OSSException("None of the provided keys (" + idx
                            + ") could be used to store the secret. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            return;
        }
    } catch (OSSException osse) {
        throw osse;
    } catch (Exception e) {
        throw new OSSException(e);
    } finally {
        if (null != httpclient) {
            httpclient.getConnectionManager().shutdown();
        }
        if (null != agent) {
            agent.close();
        }
    }
}

From source file:com.geoxp.oss.client.OSSClient.java

License:Apache License

private static void changeACL(boolean remove, String ossURL, String sshKeyFingerprint, String secretname,
        List<String> keyfpr) throws OSSException {

    SSHAgentClient agent = null;/*from  w w w  .j  a v a 2 s  .  c o m*/

    HttpClient httpclient = null;

    try {
        agent = new SSHAgentClient();

        List<SSHKey> sshkeys = agent.requestIdentities();

        //
        // If no SSH Key fingerprint was provided, try all SSH keys available in the agent
        //

        List<String> fingerprints = new ArrayList<String>();

        if (null == sshKeyFingerprint) {
            for (SSHKey key : sshkeys) {
                fingerprints.add(key.fingerprint);
            }
        } else {
            fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", ""));
        }

        int idx = 0;

        for (String fingerprint : fingerprints) {
            idx++;

            //
            // Ask the SSH agent for the SSH key blob
            //

            byte[] keyblob = null;

            for (SSHKey key : sshkeys) {
                if (key.fingerprint.equals(fingerprint)) {
                    keyblob = key.blob;
                    break;
                }
            }

            //
            // Throw an exception if this condition is encountered as it can only happen if
            // there was a provided fingerprint which is not in the agent.
            //

            if (null == keyblob) {
                throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent.");
            }

            //
            // Retrieve OSS RSA key
            //

            RSAPublicKey pubkey = getOSSRSA(ossURL);

            //
            // Build the token
            //
            // <TS> <<SECRET_NAME><FINGERPRINT1>....<FINGERPRINTN>> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

            token.write(CryptoHelper.encodeNetworkString(tsdata));

            ByteArrayOutputStream subtoken = new ByteArrayOutputStream();

            subtoken.write(CryptoHelper.encodeNetworkString(secretname.getBytes("UTF-8")));

            for (String fpr : keyfpr) {
                subtoken.write(CryptoHelper
                        .encodeNetworkString(fpr.toLowerCase().replaceAll("[^a-f0-9]", "").getBytes("UTF-8")));
            }

            token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray()));
            token.write(CryptoHelper.encodeNetworkString(keyblob));

            byte[] sigblob = agent.sign(keyblob, token.toByteArray());

            token.write(CryptoHelper.encodeNetworkString(sigblob));

            //
            // Encrypt the token with a random AES256 key
            //

            byte[] aeskey = new byte[32];
            CryptoHelper.getSecureRandom().nextBytes(aeskey);

            byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray());

            //
            // Encrypt the random key with OSS' RSA key
            //

            byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey);

            //
            // Create the token
            //

            token.reset();

            token.write(CryptoHelper.encodeNetworkString(wrappedtoken));
            token.write(CryptoHelper.encodeNetworkString(sealedaeskey));

            //
            // Base64 encode the encryptedtoken
            //

            String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8");

            //
            // Send request to OSS
            //

            URIBuilder builder = new URIBuilder(ossURL + (remove ? GuiceServletModule.SERVLET_PATH_REMOVE_ACL
                    : GuiceServletModule.SERVLET_PATH_ADD_ACL));

            builder.addParameter("token", b64token);

            URI uri = builder.build();

            String qs = uri.getRawQuery();

            HttpPost post = new HttpPost(
                    uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath());

            post.setHeader("Content-Type", "application/x-www-form-urlencoded");

            post.setEntity(new StringEntity(qs));

            httpclient = new DefaultHttpClient();

            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            String content = EntityUtils.toString(resEntity, "UTF-8");

            post.reset();

            if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) {
                // Only throw an exception if this is the last SSH key we could try
                if (idx == fingerprints.size()) {
                    throw new OSSException("None of the provided keys (" + idx
                            + ") could be used to modify ACL. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            return;
        }
    } catch (OSSException osse) {
        throw osse;
    } catch (Exception e) {
        throw new OSSException(e);
    } finally {
        if (null != httpclient) {
            httpclient.getConnectionManager().shutdown();
        }
        if (null != agent) {
            agent.close();
        }
    }
}

From source file:com.geoxp.oss.client.OSSClient.java

License:Apache License

public static List<String> getACL(String ossURL, String sshKeyFingerprint, String secretName)
        throws OSSException {

    SSHAgentClient agent = null;/*from  w ww . j  av a  2 s  . c  o m*/

    HttpClient httpclient = null;

    try {
        agent = new SSHAgentClient();

        List<SSHKey> sshkeys = agent.requestIdentities();

        //
        // If no SSH Key fingerprint was provided, try all SSH keys available in the agent
        //

        List<String> fingerprints = new ArrayList<String>();

        if (null == sshKeyFingerprint) {
            for (SSHKey key : sshkeys) {
                fingerprints.add(key.fingerprint);
            }
        } else {
            fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", ""));
        }

        int idx = 0;

        for (String fingerprint : fingerprints) {
            idx++;

            //
            // Check if the signing key is available in the agent
            //

            byte[] keyblob = null;

            for (SSHKey key : sshkeys) {
                if (key.fingerprint.equals(fingerprint)) {
                    keyblob = key.blob;
                    break;
                }
            }

            //
            // Throw an exception if this condition is encountered as it can only happen if
            // there was a provided fingerprint which is not in the agent.
            //

            if (null == keyblob) {
                throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent.");
            }

            //
            // Generate temporary RSA key pair
            //

            RSAKeyPairGenerator rsagen = new RSAKeyPairGenerator();
            RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"),
                    CryptoHelper.getSecureRandom(), 2048, 64);
            rsagen.init(params);
            final AsymmetricCipherKeyPair keypair = rsagen.generateKeyPair();

            RSAPrivateKey rsapriv = new RSAPrivateKey() {
                public BigInteger getModulus() {
                    return ((RSAKeyParameters) keypair.getPrivate()).getModulus();
                }

                public String getFormat() {
                    return "PKCS#8";
                }

                public byte[] getEncoded() {
                    return null;
                }

                public String getAlgorithm() {
                    return "RSA";
                }

                public BigInteger getPrivateExponent() {
                    return ((RSAKeyParameters) keypair.getPrivate()).getExponent();
                }
            };

            RSAPublicKey rsapub = new RSAPublicKey() {
                public BigInteger getModulus() {
                    return ((RSAKeyParameters) keypair.getPublic()).getModulus();
                }

                public String getFormat() {
                    return "PKCS#8";
                }

                public byte[] getEncoded() {
                    return null;
                }

                public String getAlgorithm() {
                    return "RSA";
                }

                public BigInteger getPublicExponent() {
                    return ((RSAKeyParameters) keypair.getPublic()).getExponent();
                }
            };

            //
            // Build OSS Token
            //
            // <TS> <<SECRET_NAME> <RSA_ENC_KEY>> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

            token.write(CryptoHelper.encodeNetworkString(tsdata));

            ByteArrayOutputStream subtoken = new ByteArrayOutputStream();

            subtoken.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8")));
            subtoken.write(CryptoHelper.encodeNetworkString(CryptoHelper.sshKeyBlobFromPublicKey(rsapub)));

            token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray()));

            token.write(CryptoHelper.encodeNetworkString(keyblob));

            //
            // Generate signature
            //

            byte[] sigblob = agent.sign(keyblob, token.toByteArray());

            token.write(CryptoHelper.encodeNetworkString(sigblob));

            String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8");

            //
            // Send request
            //

            httpclient = new DefaultHttpClient();

            URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GET_ACL);

            builder.addParameter("token", b64token);

            URI uri = builder.build();

            String qs = uri.getRawQuery();

            HttpPost post = new HttpPost(
                    uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath());

            post.setHeader("Content-Type", "application/x-www-form-urlencoded");

            post.setEntity(new StringEntity(qs));

            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            String content = EntityUtils.toString(resEntity, "UTF-8");
            post.reset();

            if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) {
                // Only throw an exception if this is the last SSH key we could try
                if (idx == fingerprints.size()) {
                    throw new OSSException("None of the provided keys (" + idx
                            + ") could be used to retrieve ACLs. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            //
            // Extract encrypted list of fingerprints and sealed key
            //

            byte[] fprandsealedkey = Base64.decode(content);

            byte[] encryptedfpr = CryptoHelper.decodeNetworkString(fprandsealedkey, 0);
            byte[] sealedkey = CryptoHelper.decodeNetworkString(fprandsealedkey, 4 + encryptedfpr.length);

            //
            // Unseal key
            //

            byte[] wrappingkey = CryptoHelper.decryptRSA(rsapriv, sealedkey);

            //
            // Unwrap fingerprints
            //

            byte[] fpr = CryptoHelper.unwrapAES(wrappingkey, encryptedfpr);

            int offset = 0;

            List<String> res = new ArrayList<String>();

            while (offset < fpr.length) {
                byte[] f = CryptoHelper.decodeNetworkString(fpr, offset);

                if (null == f) {
                    break;
                }

                offset += 4 + f.length;

                if (0 < f.length) {
                    res.add(new String(Hex.encode(f), "UTF-8").replaceAll("([0-9a-f]{2})", "$1:"));
                }
            }

            return res;
        }
    } catch (OSSException osse) {
        throw osse;
    } catch (Exception e) {
        throw new OSSException(e);
    } finally {
        if (null != httpclient) {
            httpclient.getConnectionManager().shutdown();
        }
        if (null != agent) {
            agent.close();
        }
    }

    return null;
}

From source file:com.geoxp.oss.CryptoHelperTest.java

License:Apache License

@Test
public void testSSHKeyBlobFromPublicKey_RSA() {
    String rsapubkey = "AAAAB3NzaC1yc2EAAAABIwAAAIEA08xecCRox1yCUudqFB4EKTgfp0SkOAXv9o2OxUN8ADsQnw4FFq0qZBC5mJXlaszSHCYb/F2gG3v5iGOvcwp79JiCKx3NkMwYxHarySJi43K3ukciR5dlKv4rnStIV7SkoQE9HxSszYDki4LYnA+6Ct9aDp4cBgNs5Cscy/o3S9k=";
    PublicKey key = CryptoHelper.sshKeyBlobToPublicKey(Base64.decode(rsapubkey.getBytes()));
    String blob = new String(Base64.encode(CryptoHelper.sshKeyBlobFromPublicKey(key)));
    Assert.assertEquals(rsapubkey, blob);
}

From source file:com.geoxp.oss.CryptoHelperTest.java

License:Apache License

@Test
public void testSSHKeyBlobFromPublicKey_DSA() {
    String dsapubkey = "AAAAB3NzaC1kc3MAAACBAMCN5PhMDoTyfaxwAdBLyxt9QPPYKB36nfEdD/NxkeblbUHAVvTy9paesjHOzXaLFaGA7MIGOMK71OokmExothsxMNjA044TLwonwR/Uy25ig2LVpZlrlrJgrF64AV84Y6rO9UXW9WAwhuvp4a3qPX5hLdhro2a34fbOhUeWNbKvAAAAFQDD3f1U20+RA07jriYJMR8zROr8vQAAAIEArzx1ehDtiCB+gkSMzCl3eYHV7y23rmp524xgxrjL9xlboI2/L69zdpyGM9J+IVAYJARQ9fWKOfMATMu+bvuO2Q6TFvMg1NSEW8MzI+6YGKZt0+muC8gwTdogSrMA0Nh45BAigsU/tjSUYaRFUO/CbnLVulUe2O1Uta4CoraOpCEAAACBAKHWahSYbnDtepBX7tE/lNuAuHAU3Pr8pWHzXI6+SlioNhSEmclG+kr8cI0MXvAgWbKe4dR8ro9sFQY70LeBkdEbhiKOkZ7Tjt3KvxOSo5T727V2P7VuFVOqI7EDlYbysp4BeT5iB0k0qrKp+73qHSv1Py2tr0GAzIAkqufDU3Po";
    PublicKey key = CryptoHelper.sshKeyBlobToPublicKey(Base64.decode(dsapubkey.getBytes()));
    String blob = new String(Base64.encode(CryptoHelper.sshKeyBlobFromPublicKey(key)));
    Assert.assertEquals(dsapubkey, blob);
}

From source file:com.geoxp.oss.pig.PigSecretStore.java

License:Apache License

public PigSecretStore(String... args) {
    ///*from  ww w  .  ja  va2s. c o m*/
    // If PSS_FILE is null, attempt to read it from UDFContext
    //

    synchronized (secrets) {
        if (secrets.isEmpty()) {
            Properties props = UDFContext.getUDFContext().getUDFProperties(PigSecretStore.class);

            //
            // If props contains a key PSS_FILE, we are executing on the backend
            //

            if (props.containsKey(PSS_FILE)) {

                //
                // We're on the backend
                //

                //
                // Open PSS_File
                //

                try {
                    //
                    // Retrieve one half of the secrets
                    //

                    InputStream pssis = PigSecretStore.class.getClassLoader()
                            .getResourceAsStream(props.getProperty(PSS_FILE));
                    BufferedReader br = new BufferedReader(new InputStreamReader(pssis));

                    //
                    // Read zknode
                    //

                    String zknode = br.readLine();

                    //
                    // Read all secret halves
                    //

                    while (true) {
                        String line = br.readLine();

                        if (null == line) {
                            break;
                        }

                        String[] tokens = line.split(" ");

                        if (2 != tokens.length) {
                            throw new RuntimeException("Invalid PSS_FILE content.");
                        }

                        secrets.put(tokens[0], Base64.decode(tokens[1].getBytes("UTF-8")));
                    }

                    br.close();

                    //
                    // Read ZooKeeper to retrieve second half of secrets
                    //

                    ZooKeeper zk = new ZooKeeper(
                            UDFContext.getUDFContext().getClientSystemProps().getProperty(PSS_ZK_QUORUM), 5000,
                            null);
                    String zkdata = new String(zk.getData(zknode, false, null), "UTF-8");
                    zk.close();

                    br = new BufferedReader(new StringReader(zkdata));

                    //
                    // Read all secret halves
                    //

                    while (true) {
                        String line = br.readLine();

                        if (null == line) {
                            break;
                        }

                        String[] tokens = line.split(" ");

                        if (2 != tokens.length) {
                            throw new RuntimeException("Invalid PSS_FILE content.");
                        }

                        byte[] otp = Base64.decode(tokens[1].getBytes("UTF-8"));

                        //
                        // Apply XOR
                        //

                        for (int i = 0; i < otp.length; i++) {
                            secrets.get(tokens[0])[i] = (byte) (secrets.get(tokens[0])[i] ^ otp[i]);
                        }
                    }
                    br.close();
                } catch (InterruptedException ie) {
                    throw new RuntimeException(ie);
                } catch (KeeperException ke) {
                    throw new RuntimeException(ke);
                } catch (IOException ioe) {
                    throw new RuntimeException(ioe);
                }
            } else {

                //
                // We're on the frontend
                //

                //
                // File is the first argument
                //          
                props.setProperty(PSS_FILE, args[0]);

                List<String> secrets = Arrays.asList(args).subList(1, args.length);

                try {
                    //
                    // StringBuilder for ZK content
                    //

                    StringBuilder sb = new StringBuilder();

                    String uuid = UUID.randomUUID().toString();
                    String zknode = System.getProperty(PSS_ZK_ROOT) + "/" + uuid;

                    //
                    // Open PSS_FILE for writing
                    //            
                    PrintWriter pw = new PrintWriter(args[0], "UTF-8");

                    // Write zknode first

                    pw.println(zknode);

                    //
                    // Attempt to retrieve each listed secret from OSS and split them in two
                    // halves using a OTP
                    //

                    for (String secretname : secrets) {
                        byte[] secret = OSSClient.getSecret(System.getProperty(PSS_OSS_URL), secretname,
                                System.getProperty(PSS_OSS_SSHKEY));

                        //
                        // Generate OTP
                        //

                        byte[] otp = new byte[secret.length];
                        CryptoHelper.getSecureRandom().nextBytes(otp);

                        //
                        // Do an XOR between secret and OTP
                        //

                        for (int i = 0; i < secret.length; i++) {
                            secret[i] = (byte) (secret[i] ^ otp[i]);
                        }

                        //
                        // Output first half to file, second to sb for ZK
                        //

                        pw.print(secretname);
                        pw.print(" ");
                        pw.println(new String(Base64.encode(secret), "UTF-8"));

                        sb.append(secretname);
                        sb.append(" ");
                        sb.append(new String(Base64.encode(otp), "UTF-8"));
                        sb.append("\n");
                    }

                    pw.close();

                    //
                    // Write zookeeper content
                    //

                    ZooKeeper zk = new ZooKeeper(System.getProperty(PSS_ZK_QUORUM), 5000, null);

                    List<ACL> acls = new ArrayList<ACL>();
                    acls.add(new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.ANYONE_ID_UNSAFE));
                    zk.create(zknode, sb.toString().getBytes("UTF-8"), acls, CreateMode.EPHEMERAL);
                } catch (InterruptedException ie) {
                    throw new RuntimeException(ie);
                } catch (KeeperException ke) {
                    throw new RuntimeException(ke);
                } catch (IOException ioe) {
                    throw new RuntimeException(ioe);
                } catch (OSSException osse) {
                    throw new RuntimeException(osse);
                }
            }
        }
    }
}

From source file:com.geoxp.oss.servlet.GetSecretServlet.java

License:Apache License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!OSS.isInitialized()) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Open Secret Server not yet initialized.");
        return;/* ww w.  j  a v a  2  s .  c  om*/
    }

    //
    // Extract token
    //

    String token = req.getParameter("token");

    if (null == token) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'token'.");
    }

    //
    // Decode token
    //

    byte[] tokendata = Base64.decode(token);

    //
    // Extract OSS Token
    //

    OSSToken osstoken = null;

    try {
        osstoken = OSS.checkToken(tokendata);
    } catch (OSSException osse) {
        LOGGER.error("doPost", osse);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, osse.getMessage());
        return;
    }

    //
    // Extract secretname and RSA pub key from secret
    //

    byte[] secretname = CryptoHelper.decodeNetworkString(osstoken.getSecret(), 0);
    byte[] rsapubblob = CryptoHelper.decodeNetworkString(osstoken.getSecret(), secretname.length + 4);

    //
    // Retrieve secret
    //

    byte[] secret = null;

    try {
        secret = OSS.getKeyStore().getSecret(new String(secretname, "UTF-8"),
                new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob()))));
    } catch (OSSException osse) {
        LOGGER.error("doPost", osse);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, osse.getMessage());
        return;
    }

    //
    // Unwrap secret
    //

    secret = CryptoHelper.unwrapBlob(OSS.getMasterSecret(), secret);

    if (null == secret) {
        LOGGER.error("[" + new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob())))
                + "] failed to retrieve secret '" + new String(secretname, "UTF-8")
                + "', integrity check failed.");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Secret integrity failed.");
        return;
    }

    //
    // Wrap secret (excluding nonce) with a temporary AES key
    //

    byte[] wrappingkey = new byte[32];
    CryptoHelper.getSecureRandom().nextBytes(wrappingkey);

    secret = CryptoHelper.wrapAES(wrappingkey, secret, OSS.NONCE_BYTES, secret.length - OSS.NONCE_BYTES, false);

    //
    // Seal wrapping key with provided RSA pub key
    //

    PublicKey rsapub = CryptoHelper.sshKeyBlobToPublicKey(rsapubblob);

    byte[] sealedwrappingkey = CryptoHelper.encryptRSA(rsapub, wrappingkey);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(CryptoHelper.encodeNetworkString(secret));
    baos.write(CryptoHelper.encodeNetworkString(sealedwrappingkey));

    resp.setStatus(HttpServletResponse.SC_OK);

    resp.getWriter().println(new String(Base64.encode(baos.toByteArray()), "UTF-8"));

    LOGGER.info("[" + new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob())))
            + "] retrieved " + (secret.length - OSS.NONCE_BYTES) + " bytes of secret '"
            + new String(secretname, "UTF-8") + "'.");
}

From source file:com.github.adanac.framework.sso.common.util.Base64Util.java

License:Apache License

/**
 * <p>/*  w w  w .ja  va2s.  c  om*/
 * ??BASE64
 * </p>
 * 
 * @param bytes
 * @return
 * @throws Exception
 */
public static String encode(byte[] bytes) throws Exception {
    return new String(Base64.encode(bytes));
}

From source file:com.github.cmisbox.remote.AlfrescoWebscripts.java

License:Open Source License

public static Changes getChangeLog(List<String> rootIds) throws Exception {
    String urlString = Config.getInstance().getRepositoryUrl() + "/service/cmisbox/changes?id="
            + rootIds.toString().replaceAll("\\[", "").replaceAll("\\]", "");

    if (Config.getInstance().getChangeLogToken() != null) {
        urlString += "&token=" + Config.getInstance().getChangeLogToken();
    }//from  ww  w.  ja v  a  2 s.  c  om
    String name = Config.getInstance().getRepositoryUsername();
    String password = Config.getInstance().getRepositoryPassword();

    String authString = name + ":" + password;
    byte[] authEncBytes = Base64.encode(authString.getBytes());
    String authStringEnc = new String(authEncBytes);

    URL url = new URL(urlString);
    URLConnection urlConnection = url.openConnection();
    urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
    InputStream is = urlConnection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);

    Gson gson = new Gson();
    Changes c = gson.fromJson(isr, Changes.class);

    return c;
}

From source file:com.google.bitcoin.core.ECKey.java

License:Apache License

/**
 * Signs a text message using the standard Bitcoin messaging signing format and returns the signature as a base64
 * encoded string./*from w w w . ja va2s.  com*/
 *
 * @throws IllegalStateException if this ECKey does not have the private part.
 * @throws KeyCrypterException if this ECKey is encrypted and no AESKey is provided or it does not decrypt the ECKey.
 */
public String signMessage(String message, @Nullable KeyParameter aesKey) throws KeyCrypterException {
    if (priv == null)
        throw new IllegalStateException("This ECKey does not have the private key necessary for signing.");
    byte[] data = Utils.formatMessageForSigning(message);
    Sha256Hash hash = Sha256Hash.createDouble(data);
    ECDSASignature sig = sign(hash, aesKey);
    // Now we have to work backwards to figure out the recId needed to recover the signature.
    int recId = -1;
    for (int i = 0; i < 4; i++) {
        ECKey k = ECKey.recoverFromSignature(i, sig, hash, isCompressed());
        if (k != null && Arrays.equals(k.pub, pub)) {
            recId = i;
            break;
        }
    }
    if (recId == -1)
        throw new RuntimeException("Could not construct a recoverable key. This should never happen.");
    int headerByte = recId + 27 + (isCompressed() ? 4 : 0);
    byte[] sigData = new byte[65]; // 1 header + 32 bytes for R + 32 bytes for S
    sigData[0] = (byte) headerByte;
    System.arraycopy(Utils.bigIntegerToBytes(sig.r, 32), 0, sigData, 1, 32);
    System.arraycopy(Utils.bigIntegerToBytes(sig.s, 32), 0, sigData, 33, 32);
    return new String(Base64.encode(sigData), Charset.forName("UTF-8"));
}