Example usage for java.security Security insertProviderAt

List of usage examples for java.security Security insertProviderAt

Introduction

In this page you can find the example usage for java.security Security insertProviderAt.

Prototype

public static synchronized int insertProviderAt(Provider provider, int position) 

Source Link

Document

Adds a new provider, at a specified position.

Usage

From source file:cli.Main.java

public static void main(String[] args) {
    // Workaround for BKS truststore
    Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);

    Namespace ns = parseArgs(args);
    if (ns == null) {
        System.exit(1);/*w  w  w . j a va 2s  .  co  m*/
    }

    final String username = ns.getString("username");
    final Manager m = new Manager(username);
    if (m.userExists()) {
        try {
            m.load();
        } catch (Exception e) {
            System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage());
            System.exit(2);
        }
    }

    switch (ns.getString("command")) {
    case "register":
        if (!m.userHasKeys()) {
            m.createNewIdentity();
        }
        try {
            m.register(ns.getBoolean("voice"));
        } catch (IOException e) {
            System.err.println("Request verify error: " + e.getMessage());
            System.exit(3);
        }
        break;
    case "verify":
        if (!m.userHasKeys()) {
            System.err.println("User has no keys, first call register.");
            System.exit(1);
        }
        if (m.isRegistered()) {
            System.err.println("User registration is already verified");
            System.exit(1);
        }
        try {
            m.verifyAccount(ns.getString("verificationCode"));
        } catch (IOException e) {
            System.err.println("Verify error: " + e.getMessage());
            System.exit(3);
        }
        break;
    case "send":
        if (!m.isRegistered()) {
            System.err.println("User is not registered.");
            System.exit(1);
        }
        String messageText = ns.getString("message");
        if (messageText == null) {
            try {
                messageText = IOUtils.toString(System.in);
            } catch (IOException e) {
                System.err.println("Failed to read message from stdin: " + e.getMessage());
                System.exit(1);
            }
        }

        final List<String> attachments = ns.getList("attachment");
        List<TextSecureAttachment> textSecureAttachments = null;
        if (attachments != null) {
            textSecureAttachments = new ArrayList<>(attachments.size());
            for (String attachment : attachments) {
                try {
                    File attachmentFile = new File(attachment);
                    InputStream attachmentStream = new FileInputStream(attachmentFile);
                    final long attachmentSize = attachmentFile.length();
                    String mime = Files.probeContentType(Paths.get(attachment));
                    textSecureAttachments
                            .add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null));
                } catch (IOException e) {
                    System.err.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage());
                    System.err.println("Aborting sending.");
                    System.exit(1);
                }
            }
        }

        List<TextSecureAddress> recipients = new ArrayList<>(ns.<String>getList("recipient").size());
        for (String recipient : ns.<String>getList("recipient")) {
            try {
                recipients.add(m.getPushAddress(recipient));
            } catch (InvalidNumberException e) {
                System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage());
                System.err.println("Aborting sending.");
                System.exit(1);
            }
        }
        sendMessage(m, messageText, textSecureAttachments, recipients);
        break;
    case "receive":
        if (!m.isRegistered()) {
            System.err.println("User is not registered.");
            System.exit(1);
        }
        try {
            m.receiveMessages(5, true, new ReceiveMessageHandler(m));
        } catch (IOException e) {
            System.err.println("Error while receiving message: " + e.getMessage());
            System.exit(3);
        } catch (AssertionError e) {
            System.err.println("Failed to receive message (Assertion): " + e.getMessage());
            System.err.println(e.getStackTrace());
            System.err.println(
                    "If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
            System.exit(1);
        }
        break;
    }
    m.save();
    System.exit(0);
}

From source file:org.asamk.signal.Main.java

public static void main(String[] args) {
    // Workaround for BKS truststore
    Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);

    Namespace ns = parseArgs(args);
    if (ns == null) {
        System.exit(1);/* ww w  . j  a  va2 s  . co m*/
    }

    final String username = ns.getString("username");
    Manager m;
    Signal ts;
    DBusConnection dBusConn = null;
    try {
        if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
            try {
                m = null;
                int busType;
                if (ns.getBoolean("dbus_system")) {
                    busType = DBusConnection.SYSTEM;
                } else {
                    busType = DBusConnection.SESSION;
                }
                dBusConn = DBusConnection.getConnection(busType);
                ts = (Signal) dBusConn.getRemoteObject(SIGNAL_BUSNAME, SIGNAL_OBJECTPATH, Signal.class);
            } catch (DBusException e) {
                e.printStackTrace();
                if (dBusConn != null) {
                    dBusConn.disconnect();
                }
                System.exit(3);
                return;
            }
        } else {
            String settingsPath = ns.getString("config");
            if (TextUtils.isEmpty(settingsPath)) {
                settingsPath = System.getProperty("user.home") + "/.config/signal";
                if (!new File(settingsPath).exists()) {
                    String legacySettingsPath = System.getProperty("user.home") + "/.config/textsecure";
                    if (new File(legacySettingsPath).exists()) {
                        settingsPath = legacySettingsPath;
                    }
                }
            }

            m = new Manager(username, settingsPath);
            ts = m;
            if (m.userExists()) {
                try {
                    m.load();
                } catch (Exception e) {
                    System.err
                            .println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage());
                    System.exit(2);
                    return;
                }
            }
        }

        switch (ns.getString("command")) {
        case "register":
            if (dBusConn != null) {
                System.err.println("register is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.userHasKeys()) {
                m.createNewIdentity();
            }
            try {
                m.register(ns.getBoolean("voice"));
            } catch (IOException e) {
                System.err.println("Request verify error: " + e.getMessage());
                System.exit(3);
            }
            break;
        case "verify":
            if (dBusConn != null) {
                System.err.println("verify is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.userHasKeys()) {
                System.err.println("User has no keys, first call register.");
                System.exit(1);
            }
            if (m.isRegistered()) {
                System.err.println("User registration is already verified");
                System.exit(1);
            }
            try {
                m.verifyAccount(ns.getString("verificationCode"));
            } catch (IOException e) {
                System.err.println("Verify error: " + e.getMessage());
                System.exit(3);
            }
            break;
        case "link":
            if (dBusConn != null) {
                System.err.println("link is not yet implemented via dbus");
                System.exit(1);
            }

            // When linking, username is null and we always have to create keys
            m.createNewIdentity();

            String deviceName = ns.getString("name");
            if (deviceName == null) {
                deviceName = "cli";
            }
            try {
                System.out.println(m.getDeviceLinkUri());
                m.finishDeviceLink(deviceName);
                System.out.println("Associated with: " + m.getUsername());
            } catch (TimeoutException e) {
                System.err.println("Link request timed out, please try again.");
                System.exit(3);
            } catch (IOException e) {
                System.err.println("Link request error: " + e.getMessage());
                System.exit(3);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                System.exit(3);
            } catch (UserAlreadyExists e) {
                System.err.println("The user " + e.getUsername() + " already exists\nDelete \""
                        + e.getFileName() + "\" before trying again.");
                System.exit(3);
            }
            break;
        case "addDevice":
            if (dBusConn != null) {
                System.err.println("link is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                m.addDeviceLink(new URI(ns.getString("uri")));
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                System.exit(2);
            } catch (URISyntaxException e) {
                e.printStackTrace();
                System.exit(2);
            }
            break;
        case "listDevices":
            if (dBusConn != null) {
                System.err.println("listDevices is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                List<DeviceInfo> devices = m.getLinkedDevices();
                for (DeviceInfo d : devices) {
                    System.out.println("Device " + d.getId()
                            + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
                    System.out.println(" Name: " + d.getName());
                    System.out.println(" Created: " + d.getCreated());
                    System.out.println(" Last seen: " + d.getLastSeen());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            }
            break;
        case "removeDevice":
            if (dBusConn != null) {
                System.err.println("removeDevice is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                int deviceId = ns.getInt("deviceId");
                m.removeLinkedDevices(deviceId);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            }
            break;
        case "send":
            if (dBusConn == null && !m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            if (ns.getBoolean("endsession")) {
                if (ns.getList("recipient") == null) {
                    System.err.println("No recipients given");
                    System.err.println("Aborting sending.");
                    System.exit(1);
                }
                try {
                    ts.sendEndSessionMessage(ns.<String>getList("recipient"));
                } catch (IOException e) {
                    handleIOException(e);
                } catch (EncapsulatedExceptions e) {
                    handleEncapsulatedExceptions(e);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                } catch (DBusExecutionException e) {
                    handleDBusExecutionException(e);
                } catch (UntrustedIdentityException e) {
                    e.printStackTrace();
                }
            } else {
                String messageText = ns.getString("message");
                if (messageText == null) {
                    try {
                        messageText = IOUtils.toString(System.in);
                    } catch (IOException e) {
                        System.err.println("Failed to read message from stdin: " + e.getMessage());
                        System.err.println("Aborting sending.");
                        System.exit(1);
                    }
                }

                try {
                    List<String> attachments = ns.getList("attachment");
                    if (attachments == null) {
                        attachments = new ArrayList<>();
                    }
                    if (ns.getString("group") != null) {
                        byte[] groupId = decodeGroupId(ns.getString("group"));
                        ts.sendGroupMessage(messageText, attachments, groupId);
                    } else {
                        ts.sendMessage(messageText, attachments, ns.<String>getList("recipient"));
                    }
                } catch (IOException e) {
                    handleIOException(e);
                } catch (EncapsulatedExceptions e) {
                    handleEncapsulatedExceptions(e);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                } catch (GroupNotFoundException e) {
                    handleGroupNotFoundException(e);
                } catch (AttachmentInvalidException e) {
                    System.err.println("Failed to add attachment: " + e.getMessage());
                    System.err.println("Aborting sending.");
                    System.exit(1);
                } catch (DBusExecutionException e) {
                    handleDBusExecutionException(e);
                } catch (UntrustedIdentityException e) {
                    e.printStackTrace();
                }
            }

            break;
        case "receive":
            if (dBusConn != null) {
                try {
                    dBusConn.addSigHandler(Signal.MessageReceived.class,
                            new DBusSigHandler<Signal.MessageReceived>() {
                                @Override
                                public void handle(Signal.MessageReceived s) {
                                    System.out
                                            .print(String.format("Envelope from: %s\nTimestamp: %d\nBody: %s\n",
                                                    s.getSender(), s.getTimestamp(), s.getMessage()));
                                    if (s.getGroupId().length > 0) {
                                        System.out.println("Group info:");
                                        System.out.println("  Id: " + Base64.encodeBytes(s.getGroupId()));
                                    }
                                    if (s.getAttachments().size() > 0) {
                                        System.out.println("Attachments: ");
                                        for (String attachment : s.getAttachments()) {
                                            System.out.println("-  Stored plaintext in: " + attachment);
                                        }
                                    }
                                    System.out.println();
                                }
                            });
                } catch (DBusException e) {
                    e.printStackTrace();
                }
                while (true) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        System.exit(0);
                    }
                }
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            int timeout = 60;
            if (ns.getInt("timeout") != null) {
                timeout = ns.getInt("timeout");
            }
            boolean returnOnTimeout = true;
            if (timeout < 0) {
                returnOnTimeout = false;
                timeout = 3600;
            }
            try {

                for (int i = 0; i < 10; i++) {
                    System.out.println("Numero di threads: " + Thread.activeCount());
                    m.receiveMessages(timeout, returnOnTimeout, new ReceiveMessageHandler(m));
                }

            } catch (IOException e) {
                System.err.println("Error while receiving messages: " + e.getMessage());
                System.exit(3);
            } catch (AssertionError e) {
                handleAssertionError(e);
            }
            break;
        case "quitGroup":
            if (dBusConn != null) {
                System.err.println("quitGroup is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            try {
                m.sendQuitGroupMessage(decodeGroupId(ns.getString("group")));
            } catch (IOException e) {
                handleIOException(e);
            } catch (EncapsulatedExceptions e) {
                handleEncapsulatedExceptions(e);
            } catch (AssertionError e) {
                handleAssertionError(e);
            } catch (GroupNotFoundException e) {
                handleGroupNotFoundException(e);
            } catch (UntrustedIdentityException e) {
                e.printStackTrace();
            }

            break;
        case "updateGroup":
            if (dBusConn != null) {
                System.err.println("updateGroup is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            try {
                byte[] groupId = null;
                if (ns.getString("group") != null) {
                    groupId = decodeGroupId(ns.getString("group"));
                }
                byte[] newGroupId = m.sendUpdateGroupMessage(groupId, ns.getString("name"),
                        ns.<String>getList("member"), ns.getString("avatar"));
                if (groupId == null) {
                    System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" ");
                }
            } catch (IOException e) {
                handleIOException(e);
            } catch (AttachmentInvalidException e) {
                System.err.println("Failed to add avatar attachment for group\": " + e.getMessage());
                System.err.println("Aborting sending.");
                System.exit(1);
            } catch (GroupNotFoundException e) {
                handleGroupNotFoundException(e);
            } catch (EncapsulatedExceptions e) {
                handleEncapsulatedExceptions(e);
            } catch (UntrustedIdentityException e) {
                e.printStackTrace();
            }

            break;
        case "daemon":
            if (dBusConn != null) {
                System.err.println("Stop it.");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            DBusConnection conn = null;
            try {
                try {
                    int busType;
                    if (ns.getBoolean("system")) {
                        busType = DBusConnection.SYSTEM;
                    } else {
                        busType = DBusConnection.SESSION;
                    }
                    conn = DBusConnection.getConnection(busType);
                    conn.exportObject(SIGNAL_OBJECTPATH, m);
                    conn.requestBusName(SIGNAL_BUSNAME);
                } catch (DBusException e) {
                    e.printStackTrace();
                    System.exit(3);
                }
                try {
                    m.receiveMessages(3600, false, new DbusReceiveMessageHandler(m, conn));
                } catch (IOException e) {
                    System.err.println("Error while receiving messages: " + e.getMessage());
                    System.exit(3);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }

            break;
        }
        System.exit(0);
    } finally {
        if (dBusConn != null) {
            dBusConn.disconnect();
        }
    }
}

From source file:com.aqnote.shared.cryptology.util.ProviderUtil.java

public static void resetToProvider(Provider provider) {
    removeAllProvider();
    Security.insertProviderAt(provider, 1);
}

From source file:com.aqnote.shared.cryptology.util.ProviderUtil.java

public static void addProvider(Provider provider) throws Exception {
    if (provider == null || Security.getProvider(provider.getName()) != null)
        return;/* w ww .  j a v a  2 s .  co  m*/
    Security.insertProviderAt(provider, 1);
}

From source file:Main.java

private static void loadProviderIfNecessary(String providerClassName) {
    if (providerClassName == null) {
        return;//from   w ww .j  av a 2s .co  m
    }

    final Class<?> klass;
    try {
        final ClassLoader sysLoader = ClassLoader.getSystemClassLoader();
        if (sysLoader != null) {
            klass = sysLoader.loadClass(providerClassName);
        } else {
            klass = Class.forName(providerClassName);
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        System.exit(1);
        return;
    }

    Constructor<?> constructor = null;
    for (Constructor<?> c : klass.getConstructors()) {
        if (c.getParameterTypes().length == 0) {
            constructor = c;
            break;
        }
    }
    if (constructor == null) {
        System.err.println("No zero-arg constructor found for " + providerClassName);
        System.exit(1);
        return;
    }

    final Object o;
    try {
        o = constructor.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
        return;
    }
    if (!(o instanceof Provider)) {
        System.err.println("Not a Provider class: " + providerClassName);
        System.exit(1);
    }

    Security.insertProviderAt((Provider) o, 1);
}

From source file:com.grantedbyme.example.ServletUtils.java

public static GrantedByMe getSDK(HttpServlet context) throws IOException {
    // read private key
    String privateKey = null;/*from  w w w .jav  a 2s . c o m*/
    InputStream privateKeyInputStream = context.getClass().getResourceAsStream("/private_key.pem");
    try {
        privateKey = IOUtils.toString(privateKeyInputStream);
    } finally {
        privateKeyInputStream.close();
    }
    // read server key
    String serverKey = null;
    InputStream serverKeyInputStream = context.getClass().getResourceAsStream("/server_key.pem");
    try {
        serverKey = IOUtils.toString(serverKeyInputStream);
    } finally {
        serverKeyInputStream.close();
    }
    // _log(serverKey);
    // initialize BouncyCastle security provider
    Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 0);
    // create sdk
    GrantedByMe sdk = new GrantedByMe(privateKey, serverKey);
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            //No need to implement.
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            //No need to implement.
        }
    } };
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // set SDK parameters
    sdk.apiURL = "https://api-dev.grantedby.me/v1/service/";
    //sdk.isDebug = true;
    return sdk;
}

From source file:com.yosanai.java.swing.config.FileBackedConfigDialog.java

public void init(String... keys) {
    if (null == configuration) {
        ConfigPasswordDialog dialog = new ConfigPasswordDialog(null, true);
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
            Security.insertProviderAt(new BouncyCastleProvider(), 1);
        }/*from  w w w.  ja v  a2s  . c o m*/
        encryptor.setAlgorithm(DEFAULT_ALGORITHM);
        dialog.setEncryptor(encryptor);
        dialog.setVisible(true);
        if (ConfigPasswordDialog.RET_OK == dialog.getReturnStatus()) {
            try {
                configuration = new EncryptedXMLConfiguration(encryptor);
                configuration.setFileName(file);
                configuration.load(file);
            } catch (ConfigurationException e) {
                try {
                    String defaultPath = System.getProperty("user.home") + "/" + file;
                    new File(defaultPath).createNewFile();
                    FileInputStream ins = new FileInputStream(defaultPath);
                    String entries = IOUtils.toString(ins);
                    IOUtils.closeQuietly(ins);
                    if (StringUtils.isBlank(entries)) {
                        configuration = new EncryptedXMLConfiguration(encryptor);
                        configuration.setFileName(defaultPath);
                        try {
                            configuration.save();
                        } catch (ConfigurationException cfEx) {
                            Logger.getLogger(FileBackedConfigDialog.class.getName()).log(Level.SEVERE, null,
                                    cfEx);
                        }
                    }
                } catch (IOException ioEx) {
                    Logger.getLogger(FileBackedConfigDialog.class.getName()).log(Level.SEVERE, null, ioEx);
                }
            }
        }
    }
    if (null != configuration) {
        configuration.setAutoSave(true);
        load(keys);
    }
}

From source file:com.grantedbyme.example.ServletCallback.java

public void doProcess(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json; charset=UTF-8");
    // setup default response
    HashMap<String, Object> resultHashMap = new HashMap<>();
    resultHashMap.put("success", false);
    resultHashMap.put("error", 0);
    JSONObject result = null;// www .j a va  2s  .c om
    // get request parameters
    String reqSignature = request.getParameter("signature");
    String reqPayload = request.getParameter("payload");
    String reqMessage = request.getParameter("message");
    // process request
    if (reqSignature != null && reqPayload != null) {
        // read private key
        String privateKey = null;
        InputStream privateKeyInputStream = getClass().getResourceAsStream("/private_key.pem");
        try {
            privateKey = IOUtils.toString(privateKeyInputStream);
        } finally {
            privateKeyInputStream.close();
        }
        // read server key
        String serverKey = null;
        InputStream serverKeyInputStream = getClass().getResourceAsStream("/server_key.pem");
        try {
            serverKey = IOUtils.toString(serverKeyInputStream);
        } finally {
            serverKeyInputStream.close();
        }
        // _log(serverKey);
        // initialize BouncyCastle security provider
        Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 0);
        // decrypt request
        HashMap<String, Object> params = new HashMap<>();
        params.put("signature", reqSignature);
        params.put("payload", reqPayload);
        params.put("message", reqMessage);
        /*System.out.println("Signature: " + reqSignature);
        System.out.println("Payload: " + reqPayload);
        System.out.println("Message: " + reqMessage);*/
        JSONObject requestJSON = CryptoUtil.decryptAndVerify(new JSONObject(params), serverKey, privateKey);
        if (requestJSON != null) {
            _log(requestJSON.toJSONString());
            if (requestJSON.containsKey("operation")) {
                String operation = (String) requestJSON.get("operation");
                if (operation.equals("ping")) {
                    resultHashMap.put("success", true);
                } else if (operation.equals("unlink_account")) {
                    if (requestJSON.containsKey("authenticator_secret_hash")) {
                        // TODO: implement
                    }
                    resultHashMap.put("success", false);
                } else if (operation.equals("rekey_account")) {
                    if (requestJSON.containsKey("authenticator_secret_hash")) {
                        // TODO: implement
                    }
                    resultHashMap.put("success", false);
                } else if (operation.equals("revoke_challenge")) {
                    if (requestJSON.containsKey("challenge")) {
                        // TODO: implement
                    }
                    resultHashMap.put("success", false);
                } else {
                    // operation not handled
                }
            }
        }
        result = CryptoUtil.encryptAndSign(new JSONObject(resultHashMap), serverKey, privateKey);
    }
    // write out response
    PrintWriter out = response.getWriter();
    if (result != null) {
        out.print(result.toJSONString());
    } else {
        out.print(new JSONObject(resultHashMap).toJSONString());
    }
    out.close();
}

From source file:cybervillains.ca.KeyStoreManager.java

@SuppressWarnings("unchecked")
public KeyStoreManager(File root) {
    this.root = root;

    Security.insertProviderAt(new BouncyCastleProvider(), 2);

    _sr = new SecureRandom();

    try {//  w ww .j  a  v  a  2s . c  om
        _rsaKpg = KeyPairGenerator.getInstance(RSA_KEYGEN_ALGO);
        _dsaKpg = KeyPairGenerator.getInstance(DSA_KEYGEN_ALGO);
    } catch (Throwable t) {
        throw new Error(t);
    }

    try {

        File privKeys = new File(root, KEYMAP_SER_FILE);

        if (!privKeys.exists()) {
            _rememberedPrivateKeys = new HashMap<PublicKey, PrivateKey>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(privKeys));
            // Deserialize the object
            _rememberedPrivateKeys = (HashMap<PublicKey, PrivateKey>) in.readObject();
            in.close();
        }

        File pubKeys = new File(root, PUB_KEYMAP_SER_FILE);

        if (!pubKeys.exists()) {
            _mappedPublicKeys = new HashMap<PublicKey, PublicKey>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(pubKeys));
            // Deserialize the object
            _mappedPublicKeys = (HashMap<PublicKey, PublicKey>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // check for file exists, won't happen.
        e.printStackTrace();
    } catch (IOException e) {
        // we could correct, but this probably indicates a corruption
        // of the serialized file that we want to know about; likely
        // synchronization problems during serialization.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // serious problem.
        e.printStackTrace();
        throw new Error(e);
    }

    _rsaKpg.initialize(1024, _sr);
    _dsaKpg.initialize(1024, _sr);

    try {
        _ks = KeyStore.getInstance("JKS");

        reloadKeystore();
    } catch (FileNotFoundException fnfe) {
        try {
            createKeystore();
        } catch (Exception e) {
            throw new Error(e);
        }
    } catch (Exception e) {
        throw new Error(e);
    }

    try {

        File file = new File(root, CERTMAP_SER_FILE);

        if (!file.exists()) {
            _certMap = new HashMap<String, String>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            // Deserialize the object
            _certMap = (HashMap<String, String>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // won't happen, check file.exists()
        e.printStackTrace();
    } catch (IOException e) {
        // corrupted file, we want to know.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // something very wrong, exit
        e.printStackTrace();
        throw new Error(e);
    }

    try {

        File file = new File(root, SUBJMAP_SER_FILE);

        if (!file.exists()) {
            _subjectMap = new HashMap<String, String>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            // Deserialize the object
            _subjectMap = (HashMap<String, String>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // won't happen, check file.exists()
        e.printStackTrace();
    } catch (IOException e) {
        // corrupted file, we want to know.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // something very wrong, exit
        e.printStackTrace();
        throw new Error(e);
    }

}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

private NicosClient() {
    // private constructor -> Singleton
    Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
    callbackHandlers = Collections.synchronizedList(new CopyOnWriteArrayList<NicosCallbackHandler>());
    socket = null;/*from w  w w .  j a  v a  2 s  . c o  m*/
    eventSocket = null;
    connected = false;
    disconnecting = false;
    last_reqno = null;
    viewonly = true;
    user_level = -1;
    MessageDigest md5 = getMD5();
    if (md5 != null) {
        client_id = getMD5().digest(getUniqueID().getBytes());
    }

    // Add debug printer for signals.
    // callbackHandlers.add(new SignalDebugPrinter());
    Unpickler.registerConstructor("nicos.utils", "readonlylist", new ReadOnlyListConstructor());
    Unpickler.registerConstructor("nicos.utils", "readonlydict", new ReadOnlyDictConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "ConfigurationError",
            new ConfigurationErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "CommunicationError",
            new CommunicationErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "NicosError", new NicosErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "InvalidValueError", new InvalidValueErrorConstructor());
    Unpickler.registerConstructor("__builtin__", "str", new strErrorConstructor());
}