Example usage for java.security InvalidKeyException InvalidKeyException

List of usage examples for java.security InvalidKeyException InvalidKeyException

Introduction

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

Prototype

public InvalidKeyException() 

Source Link

Document

Constructs an InvalidKeyException with no detail message.

Usage

From source file:be.fedict.commons.eid.jca.BeIDSignature.java

@Override
protected void engineInitSign(final PrivateKey privateKey) throws InvalidKeyException {
    LOG.debug("engineInitSign");
    if (false == privateKey instanceof BeIDPrivateKey) {
        throw new InvalidKeyException();
    }// w  w w .ja  va  2  s  . c o  m
    this.privateKey = (BeIDPrivateKey) privateKey;
    if (null != this.messageDigest) {
        this.messageDigest.reset();
    }
}

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

public void connect(ConnectionData connData, Object[] eventmask) throws RuntimeException {
    if (connected) {
        throw new RuntimeException("client already connected");
    }//from www  .java 2 s  .co  m
    disconnecting = false;

    SocketAddress sockaddr;
    try {
        // If ANY code of this scope failes, communication is entirely impossible.
        // That means, no need to catch all exceptions one by one.
        InetAddress addr = InetAddress.getByName(connData.getHost());
        sockaddr = new InetSocketAddress(addr, connData.getPort());

        // Initialize empty socket.
        socket = new Socket();

        // Connects this socket to the server with a specified timeout value
        // If timeout occurs, SocketTimeoutException is thrown
        socket.connect(sockaddr, TIMEOUT);
        socketOut = socket.getOutputStream();
        socketIn = socket.getInputStream();

        // Write client identification: we are a new client
        socketOut.write(client_id);
    } catch (Exception e) {
        String msg;
        if (e instanceof IOException) {
            // "null reference" error messages won't help the user.
            msg = "Socket communication failed (server not responding).";
        } else {
            msg = "Server connection failed: " + e.getMessage() + ".";
        }
        signal("failed", msg);
        return;
    }

    // read banner
    try {
        TupleOfTwo<Byte, Object> response = _read();
        byte ret = response.getFirst();
        if (ret != daemon.STX) {
            throw new ProtocolError("invalid response format");
        }
        nicosBanner = (HashMap) response.getSecond();
        if (!nicosBanner.containsKey("daemon_version")) {
            throw new ProtocolError("daemon version missing from response");
        }
        int daemon_proto = (int) nicosBanner.get("protocol_version");
        if (!daemon.isProtoVersionCompatible(daemon_proto)) {
            throw new ProtocolError("daemon uses protocol " + String.valueOf(daemon_proto)
                    + ", but this client requires protocol " + String.valueOf(daemon.PROTO_VERSIONS[0]));
        }
    } catch (Exception e) {
        signal("failed", "Server(" + connData.getHost() + ":" + String.valueOf(connData.getPort())
                + ") handshake failed: " + e.getMessage());
        return;
    }

    // log-in sequence
    char[] password = connData.getPassword();
    Object unwrap = nicosBanner.get("pw_hashing");
    String pw_hashing = "sha1";
    if (unwrap != null) {
        pw_hashing = unwrap.toString();
    }

    String encryptedPassword = null;
    boolean supportsRSA = false;
    try {
        String rsaSupportString = pw_hashing.substring(0, 4);
        supportsRSA = rsaSupportString.equals("rsa,");
    } catch (StringIndexOutOfBoundsException e) {
        // Does not start with "rsa," -> does not support RSA encryption.
        // boolean supportsRSA stays at false.
    }
    if (supportsRSA) {
        byte[] keyBytes = Base64.decode(nicosBanner.get("rsakey").toString(), Base64.DEFAULT);
        String publicKeyString = new String(keyBytes, StandardCharsets.UTF_8);
        PublicKey publicKey = extractPublicKey(publicKeyString);

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
            // Cannot happen.
        }
        try {
            if (cipher != null) {
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            } else {
                throw new InvalidKeyException();
            }
        } catch (InvalidKeyException e) {
            throw new RuntimeException("The server's RSA key is invalid or incompatible.");
        }

        byte[] encrypted;
        try {
            encrypted = cipher.doFinal(String.valueOf(password).getBytes());
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
            encrypted = new byte[0];
        }
        encryptedPassword = "RSA:" + Base64.encodeToString(encrypted, Base64.DEFAULT);
    }

    if (pw_hashing.equals("sha1")) {
        encryptedPassword = new String(Hex.encodeHex(DigestUtils.sha1(String.valueOf(password))));
    }

    else if (pw_hashing.equals("md5")) {
        encryptedPassword = new String(Hex.encodeHex(DigestUtils.md5(String.valueOf(password))));
    }

    HashMap<String, String> credentials = new HashMap<>();
    credentials.put("login", connData.getUser());
    credentials.put("passwd", encryptedPassword);
    credentials.put("display", "");

    // Server requires credentials to be wrapped in a tuple with 1 item
    // e.g. python: payload = (credentials,)
    // Pyrolite library matches java.lang.Object arrays to tuples with the array's length.
    Object[] data = { credentials };
    Object untypedAuthResponse = ask("authenticate", data);
    if (untypedAuthResponse == null) {
        return;
    }

    // Login was successful.
    HashMap authResponse = (HashMap) untypedAuthResponse;
    user_level = (int) authResponse.get("user_level");

    if (eventmask != null) {
        tell("eventmask", eventmask);
    }

    // connect to event port
    eventSocket = new Socket();
    try {
        eventSocket.connect(sockaddr);
        OutputStream eventSocketOut = eventSocket.getOutputStream();
        eventSocketIn = eventSocket.getInputStream();
        eventSocketOut.write(client_id);
    } catch (IOException e) {
        signal("failed", "Event connection failed: " + e.getMessage() + ".", e);
        return;
    }

    // Start event handler
    final Thread event_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            // equals event_handler.
            event_handler();
        }
    });
    event_thread.start();

    connected = true;
    viewonly = connData.getViewonly();
    signal("connected");
}

From source file:org.kaaproject.kaa.client.persistence.KaaClientPropertiesState.java

private KeyPair getOrInitKeyPair(boolean isAutogeneratedKeys) {
    LOG.debug("Check if key pair exists {}, {}", clientPublicKeyFileLocation, clientPrivateKeyFileLocation);
    if (keyPair != null) {
        return keyPair;
    }/*w  ww.  ja va  2  s. c om*/
    if (storage.exists(clientPublicKeyFileLocation) && storage.exists(clientPrivateKeyFileLocation)) {
        InputStream publicKeyInput = null;
        InputStream privateKeyInput = null;
        try {
            publicKeyInput = storage.openForRead(clientPublicKeyFileLocation);
            privateKeyInput = storage.openForRead(clientPrivateKeyFileLocation);

            PublicKey publicKey = KeyUtil.getPublic(publicKeyInput);
            PrivateKey privateKey = KeyUtil.getPrivate(privateKeyInput);

            if (publicKey != null && privateKey != null) {
                keyPair = new KeyPair(publicKey, privateKey);
                if (!KeyUtil.validateKeyPair(keyPair)) {
                    throw new InvalidKeyException();
                }

                return keyPair;
            }
        } catch (InvalidKeyException ex) {
            keyPair = null;
            LOG.error("Unable to parse client RSA keypair. Generating new keys.. Reason {}", ex);
        } catch (Exception ex) {
            LOG.error("Error loading client RSA keypair. Reason {}", ex);
            throw new RuntimeException(ex); // NOSONAR
        } finally {
            IOUtils.closeQuietly(publicKeyInput);
            IOUtils.closeQuietly(privateKeyInput);
        }
    }
    if (isAutogeneratedKeys) {
        LOG.debug("Generating Client Key pair");
        OutputStream privateKeyOutput = null;
        OutputStream publicKeyOutput = null;
        try {
            privateKeyOutput = storage.openForWrite(clientPrivateKeyFileLocation);
            publicKeyOutput = storage.openForWrite(clientPublicKeyFileLocation);
            keyPair = KeyUtil.generateKeyPair(privateKeyOutput, publicKeyOutput);
        } catch (IOException ex) {
            LOG.error("Error generating Client Key pair", ex);
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(privateKeyOutput);
            IOUtils.closeQuietly(publicKeyOutput);
        }
    } else {
        LOG.debug("Error loading key pair!", "Key pair is not found and key strategy is default");
        throw new KaaRuntimeException("Key pair is not found and your key strategy is default");
    }
    return keyPair;
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

public static X509Key getPublicX509ECCKey(byte encoded[]) throws InvalidKeyException {
    try {// ww  w.j a va2 s. c  o m
        return X509Key.parse(new DerValue(encoded));
    } catch (IOException e) {
        throw new InvalidKeyException();
    }
}