public void run() { try { input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); output = new PrintWriter(clientSocket.getOutputStream(), true); InputStream in = clientSocket.getInputStream(); objIn = new ObjectInputStream(in); String outputLine; String inputLine; long time = System.currentTimeMillis(); // Inicia la comunicación con el cliente ProtocoloClinica kkp = new ProtocoloClinica(bean); outputLine = kkp.processMessage(null); output.println(outputLine); // Continua la comunicación con el cliente while ((inputLine = input.readLine()) != null) { outputLine = kkp.processMessage(inputLine); if (outputLine.equals("RECIBIDA")) { leer(); } else { output.println(outputLine); } if (outputLine.equals("OVER")) break; } killFrijolito(); System.out.println("Request processed: " + time); } catch (IOException e) { // report exception somewhere. e.printStackTrace(); } }
public void close() { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
public void write(int i) { try { out.write(i); out.flush(); } catch (IOException e) { e.printStackTrace(); } }
private void parseKeyBits() throws InvalidKeyException { try { DerInputStream in = new DerInputStream(this.key); this.y = in.getBigInteger(); } catch (IOException e) { throw new InvalidKeyException("Error parsing key encoding: " + e.toString()); } }
public void writeString(String s) { int len = s.length(); byte[] buf = new byte[len]; for (int i = 0; i < buf.length; i++) buf[i] = (byte) s.charAt(i); try { write(len); out.write(buf); out.flush(); } catch (IOException e) { e.printStackTrace(); } }
public void write(SecureItemTable tbl, char[] password) throws IOException { OutputStream os = new FileOutputStream(file); OutputStream xmlout; if (password.length == 0) { xmlout = os; os = null; } else { PBEKeySpec keyspec = new PBEKeySpec(password); Cipher c; try { SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = fac.generateSecret(keyspec); c = Cipher.getInstance("PBEWithMD5AndDES"); c.init(Cipher.ENCRYPT_MODE, key, pbeSpec); } catch (java.security.GeneralSecurityException exc) { os.close(); IOException ioe = new IOException("Security exception during write"); ioe.initCause(exc); throw ioe; } CipherOutputStream out = new CipherOutputStream(os, c); xmlout = out; } try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource src = new DOMSource(tbl.getDocument()); StringWriter writer = new StringWriter(); StreamResult sr = new StreamResult(writer); t.transform(src, sr); OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8); osw.write(writer.toString()); osw.close(); } catch (Exception exc) { IOException ioe = new IOException("Unable to serialize XML"); ioe.initCause(exc); throw ioe; } finally { xmlout.close(); if (os != null) os.close(); } tbl.setDirty(false); return; }
/* * Generate PBE key */ private SecretKey getPBEKey(char[] password) throws IOException { SecretKey skey = null; try { PBEKeySpec keySpec = new PBEKeySpec(password); SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE"); skey = skFac.generateSecret(keySpec); } catch (Exception e) { IOException ioe = new IOException("getSecretKey failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return skey; }
public void run() // loop utama, utk nerima user input n kirim ke server&client laen { while (thread != null) { try { String a = console.readLine(); String b = cryptor.encrypt(a); streamOut.writeUTF(cryptor.encrypt(a)); streamOut.flush(); } catch (IOException ioe) { System.out.println("Sending error: " + ioe.getMessage()); stop(); } } }
public ChatClient(InetAddress iAddress, int serverPort) { System.out.println("Establishing connection. Please wait ..."); try { socket = new Socket(iAddress, serverPort); cryptor = new EDCrypt(); System.out.println("Connected: " + socket); start(); } catch (UnknownHostException uhe) { System.out.println("Host unknown: " + uhe.getMessage()); } catch (IOException ioe) { System.out.println("Unexpected exception: " + ioe.getMessage()); } }
/* * Generate PBE Algorithm Parameters */ private AlgorithmParameters getAlgorithmParameters(String algorithm) throws IOException { AlgorithmParameters algParams = null; // create PBE parameters from salt and iteration count PBEParameterSpec paramSpec = new PBEParameterSpec(getSalt(), iterationCount); try { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(paramSpec); } catch (Exception e) { IOException ioe = new IOException("getAlgorithmParameters failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return algParams; }
/* * parse Algorithm Parameters */ private AlgorithmParameters parseAlgParameters(DerInputStream in) throws IOException { AlgorithmParameters algParams = null; try { DerValue params; if (in.available() == 0) { params = null; } else { params = in.getDerValue(); if (params.tag == DerValue.tag_Null) { params = null; } } if (params != null) { algParams = AlgorithmParameters.getInstance("PBE"); algParams.init(params.toByteArray()); } } catch (Exception e) { IOException ioe = new IOException("parseAlgParameters failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return algParams; }
public boolean delete(String filename, UserToken token) { try { String remotePath; if (filename.charAt(0) == '/') { remotePath = filename.substring(1); } else { remotePath = filename; } Envelope env = new Envelope("DELETEF"); // Success env.addObject(remotePath); env.addObject(token); String concat = remotePath + token.toString() + "DELETEF" + nonce; // concatinates all of the objects in envelope byte[] hasharray = concat.getBytes(); // turn the concat into a byte array Mac mac = Mac.getInstance("HmacSHA1"); mac.init(HMACkey); mac.update(hasharray); String stringhash = new String(mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision! env.addObject(stringhash); env.addObject(nonce); nonce++; byte[] envBytes = Envelope.toByteArray(env); // Encrypt envelope w/ AES Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, AESkey); byte[] cipherBytes = cipher.doFinal(envBytes); output.writeObject(cipherBytes); byte[] responseCipherBytes = (byte[]) input.readObject(); // Decrypt response cipher.init(Cipher.DECRYPT_MODE, AESkey); byte[] responseBytes = cipher.doFinal(responseCipherBytes); env = Envelope.getEnvelopefromBytes(responseBytes); System.out.println(env.getMessage()); if ((Integer) env.getObjContents().get(1) == nonce) { String hash = (String) env.getObjContents().get(0); concat = env.getMessage() + nonce; // reconstructs the hash hasharray = concat.getBytes(); mac = Mac.getInstance("HmacSHA1"); File HASHfile = new File("FHASHKey.bin"); FileInputStream fis = new FileInputStream(HASHfile); ObjectInputStream ois = new ObjectInputStream(fis); Key HMACkey = (Key) ois.readObject(); mac.init(HMACkey); mac.update(hasharray); String newhash = new String(mac.doFinal(), "UTF8"); nonce++; if (hash.equals(newhash) != true) // check hashes for equality { System.out.println("HASH EQUALITY FAIL"); return false; } if (env.getMessage().compareTo("OK") == 0) { System.out.printf("File %s deleted successfully\n", filename); } else { System.out.printf("Error deleting file %s (%s)\n", filename, env.getMessage()); return false; } } } catch (IllegalBlockSizeException ex) { ex.printStackTrace(System.err); } catch (BadPaddingException ex) { ex.printStackTrace(System.err); } catch (InvalidKeyException ex) { ex.printStackTrace(System.err); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(System.err); } catch (NoSuchPaddingException ex) { ex.printStackTrace(System.err); } catch (IOException e1) { e1.printStackTrace(System.err); } catch (ClassNotFoundException e1) { e1.printStackTrace(System.err); } return true; }
/** * Make a DH public key from its DER encoding (X.509). * * @param encodedKey the encoded key * @exception InvalidKeyException if the encoded key does not represent a Diffie-Hellman public * key */ DHPublicKey(byte[] encodedKey) throws InvalidKeyException { InputStream inStream = new ByteArrayInputStream(encodedKey); try { DerValue derKeyVal = new DerValue(inStream); if (derKeyVal.tag != DerValue.tag_Sequence) { throw new InvalidKeyException("Invalid key format"); } /* * Parse the algorithm identifier */ DerValue algid = derKeyVal.data.getDerValue(); if (algid.tag != DerValue.tag_Sequence) { throw new InvalidKeyException("AlgId is not a SEQUENCE"); } DerInputStream derInStream = algid.toDerInputStream(); ObjectIdentifier oid = derInStream.getOID(); if (oid == null) { throw new InvalidKeyException("Null OID"); } if (derInStream.available() == 0) { throw new InvalidKeyException("Parameters missing"); } /* * Parse the parameters */ DerValue params = derInStream.getDerValue(); if (params.tag == DerValue.tag_Null) { throw new InvalidKeyException("Null parameters"); } if (params.tag != DerValue.tag_Sequence) { throw new InvalidKeyException("Parameters not a SEQUENCE"); } params.data.reset(); this.p = params.data.getBigInteger(); this.g = params.data.getBigInteger(); // Private-value length is OPTIONAL if (params.data.available() != 0) { this.l = params.data.getInteger(); } if (params.data.available() != 0) { throw new InvalidKeyException("Extra parameter data"); } /* * Parse the key */ this.key = derKeyVal.data.getBitString(); parseKeyBits(); if (derKeyVal.data.available() != 0) { throw new InvalidKeyException("Excess key data"); } this.encodedKey = (byte[]) encodedKey.clone(); } catch (NumberFormatException e) { throw new InvalidKeyException("Private-value length too big"); } catch (IOException e) { throw new InvalidKeyException("Error parsing key encoding: " + e.toString()); } }
/** * Callback method from _scanKeychain. If an identity is found, this method will be called to * create Java certificate and private key objects from the keychain data. */ private void createKeyEntry( String alias, long creationDate, long secKeyRef, long[] secCertificateRefs, byte[][] rawCertData) throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException { KeyEntry ke = new KeyEntry(); // First, store off the private key information. This is the easy part. ke.protectedPrivKey = null; ke.keyRef = secKeyRef; // Make a creation date. if (creationDate != 0) ke.date = new Date(creationDate); else ke.date = new Date(); // Next, create X.509 Certificate objects from the raw data. This is complicated // because a certificate's public key may be too long for Java's default encryption strength. List<CertKeychainItemPair> createdCerts = new ArrayList<>(); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int i = 0; i < rawCertData.length; i++) { try { InputStream input = new ByteArrayInputStream(rawCertData[i]); X509Certificate cert = (X509Certificate) cf.generateCertificate(input); input.close(); // We successfully created the certificate, so track it and its corresponding // SecCertificateRef. createdCerts.add(new CertKeychainItemPair(secCertificateRefs[i], cert)); } catch (CertificateException e) { // The certificate will be skipped. System.err.println("KeychainStore Ignored Exception: " + e); } } } catch (CertificateException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); // How would this happen? } // We have our certificates in the List, so now extract them into an array of // Certificates and SecCertificateRefs. CertKeychainItemPair[] objArray = createdCerts.toArray(new CertKeychainItemPair[0]); Certificate[] certArray = new Certificate[objArray.length]; long[] certRefArray = new long[objArray.length]; for (int i = 0; i < objArray.length; i++) { CertKeychainItemPair addedItem = objArray[i]; certArray[i] = addedItem.mCert; certRefArray[i] = addedItem.mCertificateRef; } ke.chain = certArray; ke.chainRefs = certRefArray; // If we don't have already have an item with this item's alias // create a new one for it. int uniqueVal = 1; String originalAlias = alias; while (entries.containsKey(alias.toLowerCase())) { alias = originalAlias + " " + uniqueVal; uniqueVal++; } entries.put(alias.toLowerCase(), ke); }
public static void main(String[] args) { try { if (args[0].equals("-genkey")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-encrypt")) { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); // wrap with RSA public key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key publicKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] wrappedKey = cipher.wrap(key); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); out.writeInt(wrappedKey.length); out.write(wrappedKey); InputStream in = new FileInputStream(args[1]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } else { DataInputStream in = new DataInputStream(new FileInputStream(args[1])); int length = in.readInt(); byte[] wrappedKey = new byte[length]; in.read(wrappedKey, 0, length); // unwrap with RSA private key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key privateKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.UNWRAP_MODE, privateKey); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); OutputStream out = new FileOutputStream(args[2]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }