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:org.oep.ssomgt.app.service.impl.SSOAppServiceImpl.java

License:Open Source License

@JSONWebService(value = "syncDateAccounts")
@AccessControlled(guestAccessEnabled = true)
public String syncDateAccounts(String appCode, String pin, Date checkpoint) {
    CacheRegistryUtil.clear();//from  w w  w .  j  a  va  2  s . c  o m
    JSONObject resObj = JSONFactoryUtil.createJSONObject();

    JSONArray accounts = JSONFactoryUtil.createJSONArray();
    Application app = null;
    String aesKey = SecurityUtil.randomKeyBase64();

    try {
        app = ApplicationLocalServiceUtil.getByAppCode(appCode);
        if (app == null) {
            return resObj.toString();
        } else if (!app.getAppPin().equals(pin)) {
            resObj.put("success", false);
            resObj.put("errorCode", 3);
            return resObj.toString();
        }

        List<UserSync> lstSyncs = UserSyncLocalServiceUtil.findByApplicationCheckPoint(app.getApplicationId(),
                checkpoint);
        KeyFactory kFactory;
        Cipher cipher = null;
        try {
            kFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
            // decode base64 of your key
            byte yourKey[] = Base64.decode(app.getPublicKey());
            X509EncodedKeySpec spec = new X509EncodedKeySpec(yourKey);
            PublicKey publicKey = (PublicKey) kFactory.generatePublic(spec);
            //Cipher cipher = Cipher.getInstance("RSA");
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            //resObj.put("success", true);
            //return new String(Base64.encode(cipherData));
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resObj.put("success", false);
            resObj.put("errorCode", 2);
            return resObj.toString();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resObj.put("success", false);
            resObj.put("errorCode", 2);
            return resObj.toString();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resObj.put("success", false);
            resObj.put("errorCode", 2);
            return resObj.toString();
        }

        byte[] cipherData = null;
        try {
            cipherData = cipher.doFinal(Base64.decode(aesKey));
            resObj.put("key", new String(Base64.encode(cipherData)));
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resObj.put("success", false);
            resObj.put("errorCode", 2);
            return resObj.toString();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resObj.put("success", false);
            resObj.put("errorCode", 2);
            return resObj.toString();
        }

        for (UserSync us : lstSyncs) {
            User user = UserLocalServiceUtil.getUser(us.getUserId());
            JSONObject account = JSONFactoryUtil.createJSONObject();

            account.put("ssousername", us.getSsoUserName());
            account.put("appusername", us.getAppUserName());
            account.put("fullname", us.getFullName());
            account.put("accessiblestatus", us.getAccessibleStatus());
            account.put("email", user.getEmailAddress());
            account.put("password", user.getPassword());
            account.put("checkpoint", us.getCheckpoint().getTime() / 1000);
            account.put("roles", us.getRoles());
            accounts.put(account);
        }
    } catch (NoSuchApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        resObj.put("success", false);
        resObj.put("errorCode", 1);
        return resObj.toString();
    } catch (SystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        resObj.put("success", false);
        resObj.put("errorCode", 1);
        return resObj.toString();
    } catch (PortalException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        resObj.put("success", false);
        resObj.put("errorCode", 1);
        return resObj.toString();
    }

    String text = accounts.toString();
    System.out.println("Accounts: " + text);
    resObj.put("success", true);
    resObj.put("data", SecurityUtil.encrypt(text, new String(Base64.decode(aesKey))));
    return resObj.toString();
}

From source file:org.opcfoundation.ua.builtintypes.ExpandedNodeId.java

License:Open Source License

@Override
public String toString() {
    try {// w  ww. j  av  a 2 s .  c o  m
        String srvPart = serverIndex != null && serverIndex.getValue() != 0 ? "srv=" + serverIndex + ";" : "";
        String nsPart = namespaceUri != null ? "nsu=" + URLEncoder.encode(namespaceUri, "ISO8859-1") + ";"
                : namespaceIndex > 0 ? "ns=" + namespaceIndex + ";" : "";
        if (type == IdType.Numeric)
            return srvPart + nsPart + "i=" + value;
        if (type == IdType.String)
            return srvPart + nsPart + "s=" + value;
        if (type == IdType.Guid)
            return srvPart + nsPart + "g=" + value;
        if (type == IdType.Opaque) {
            if (value == null)
                return srvPart + nsPart + "b=null";
            return srvPart + nsPart + "b=" + new String(Base64.encode((byte[]) value));
        }
    } catch (UnsupportedEncodingException e) {
    }
    return "error";
}

From source file:org.opcfoundation.ua.builtintypes.NodeId.java

License:Open Source License

@Override
public String toString() {
    String nsPart = namespaceIndex > 0 ? "ns=" + namespaceIndex + ";" : "";
    if (type == IdType.Numeric)
        return nsPart + "i=" + value;
    if (type == IdType.String)
        return nsPart + "s=" + value;
    if (type == IdType.Guid)
        return nsPart + "g=" + value;
    if (type == IdType.Opaque) {
        if (value == null)
            return nsPart + "b=null";
        return nsPart + "b=" + new String(Base64.encode((byte[]) value));
    }/*w  w  w.  j av a  2  s  . c o  m*/
    return "error";
}

From source file:org.opcfoundation.ua.transport.security.BcCryptoProvider.java

License:Open Source License

@Override
public String base64Encode(byte[] bytes) {
    try {//  w  ww .  jav a2  s.c  om
        return new String(Base64.encode(bytes), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.opcfoundation.ua.utils.BouncyCastleUtils.java

License:Open Source License

public static String base64Encode(byte[] bytes) {
    try {/*w ww  .j ava 2  s  . co m*/
        return new String(Base64.encode(bytes), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.opencadc.cavern.files.CavernURLGenerator.java

License:Open Source License

private List<URI> handleDataNode(VOSURI target, DataNode node, Protocol protocol) {
    String scheme = null;/* w  w  w.j av  a 2 s . c  o m*/
    Direction dir = null;
    try {
        switch (protocol.getUri()) {
        case VOS.PROTOCOL_HTTP_GET:
            scheme = "http";
            dir = Direction.pullFromVoSpace;
            break;
        case VOS.PROTOCOL_HTTP_PUT:
            scheme = "http";
            dir = Direction.pushToVoSpace;
            break;
        case VOS.PROTOCOL_HTTPS_GET:
            scheme = "https";
            dir = Direction.pullFromVoSpace;
            break;
        case VOS.PROTOCOL_HTTPS_PUT:
            scheme = "https";
            dir = Direction.pushToVoSpace;
            break;
        }

        List<URL> baseURLs = getBaseURLs(target, protocol.getSecurityMethod(), scheme);
        if (baseURLs == null || baseURLs.isEmpty()) {
            log.debug("no matching interfaces ");
            return new ArrayList<URI>(0);
        }

        // create the metadata and signature segments
        StringBuilder metaSb = new StringBuilder();
        metaSb.append(KEY_META_NODE).append("=").append(target.toString());
        metaSb.append("&");
        metaSb.append(KEY_META_DIRECTION).append("=").append(dir.getValue());
        byte[] metaBytes = metaSb.toString().getBytes();

        RsaSignatureGenerator sg = new RsaSignatureGenerator(PRIV_KEY_FILENAME);
        String sig;
        try {
            byte[] sigBytes = sg.sign(new ByteArrayInputStream(metaBytes));
            sig = new String(Base64.encode(sigBytes));
            log.debug("Created signature: " + sig + " for meta: " + metaSb.toString());
        } catch (InvalidKeyException | IOException | RuntimeException e) {
            throw new IllegalStateException("Could not sign url", e);
        }
        String meta = new String(Base64.encode(metaBytes));
        log.debug("meta: " + meta);
        log.debug("sig: " + sig);

        // build the request path
        StringBuilder path = new StringBuilder();
        String metaURLEncoded = base64URLEncode(meta);
        String sigURLEncoded = base64URLEncode(sig);

        log.debug("metaURLEncoded: " + metaURLEncoded);
        log.debug("sigURLEncoded: " + sigURLEncoded);

        path.append("/");
        path.append(metaURLEncoded);
        path.append("/");
        path.append(sigURLEncoded);
        if (Direction.pushToVoSpace.equals(dir)) {
            // put to resolved path
            path.append(node.getUri().getPath());
        } else {
            // get from unresolved path so filename at end of url is correct
            path.append(target.getURI().getPath());
        }
        log.debug("Created request path: " + path.toString());

        // add the request path to each of the base URLs
        List<URI> returnList = new ArrayList<URI>(baseURLs.size());
        for (URL baseURL : baseURLs) {
            URI next;
            try {
                next = new URI(baseURL.toString() + path.toString());
                log.debug("Added url: " + next);
                returnList.add(next);
            } catch (URISyntaxException e) {
                throw new IllegalStateException("Could not generate trannsfer endpoint uri", e);
            }
        }

        return returnList;
    } finally {
    }
}

From source file:org.openmaji.implementation.server.security.auth.PasswordFile.java

License:Open Source License

private void save() {
    String majitekDirectory = System.getProperty(Common.PROPERTY_MAJI_HOME);

    try {//from   w ww  . j  a  va 2  s.  c  o  m
        BufferedWriter rOut = new BufferedWriter(new FileWriter(majitekDirectory + fileName));

        Iterator it = passwords.keySet().iterator();

        while (it.hasNext()) {
            String userID = (String) it.next();

            rOut.write(userID);
            rOut.write(":");
            rOut.write(new String(Base64.encode((byte[]) passwords.get(userID))));

            rOut.newLine();
        }

        rOut.close();
    } catch (IOException e) {
        throw new RuntimeException("unable to save group file.", e);
    }
}

From source file:org.openremote.beehive.account.client.AccountManagerClient.java

License:Open Source License

private void authenticate(Invocation.Builder invocation) {
    invocation.header("Authorization",
            "Basic " + new String(Base64.encode((username + ":" + new String(credentials)).getBytes(UTF8))));
}

From source file:org.ourfilesystem.utilities.BBytes.java

License:Open Source License

public String toString() {
    String str = new String(Base64.encode(getBytes()));
    return str;
}

From source file:org.ow2.jonas.jpaas.vm.configurator.providers.chef.manager.osgi.ChefManagerImpl.java

License:Apache License

/**
 * Encrypt a message with SHA algorithm and encode it in base64
 *
 * @param message/*from   w  w w.ja v  a2 s . co m*/
 *            the message to encrypt
 * @throws ChefManagerException if an error occurs
 *
 * @return the encrypted message
 */
private String encrypt(String message) throws ChefManagerException {
    MessageDigest md;
    String hash;
    try {
        md = MessageDigest.getInstance("SHA");
        md.update(message.getBytes("UTF-8"));
        byte raw[] = md.digest();
        byte[] coded = Base64.encode(raw);
        hash = new String(coded);
    } catch (Exception e) {
        throw new ChefManagerException("Error during encryption", e);
    }
    return hash;
}