/** * Sends the specified file to the client. File must exist or client and server threads will hang * indefinitely. Generates a session key to encrypt the file over transfer; session key is * encrypted using the client's public (asymmetric) key. * * @param aFile The name or path of the file to send. * @throws IOException Error reading from socket. */ private void sendFile(String aFile) throws IOException { try { // get client public key ObjectInputStream clientPubIn = new ObjectInputStream(connectedSocket.getInputStream()); PublicKey clientPublicKey = (PublicKey) clientPubIn.readObject(); // generate key string and send to client using their public key encrypted with RSA // (asymmetric) String keyString = generateKeyString(); Cipher keyCipher = Cipher.getInstance("RSA"); keyCipher.init(Cipher.ENCRYPT_MODE, clientPublicKey); SealedObject sealedKeyString = new SealedObject(keyString, keyCipher); ObjectOutputStream testOut = new ObjectOutputStream(outToClient); testOut.writeObject(sealedKeyString); testOut.flush(); // generate key spec from keyString SecretKeySpec keySpec = new SecretKeySpec(keyString.getBytes(), "DES"); // set up encryption Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); CipherOutputStream cipherOut = new CipherOutputStream(outToClient, cipher); // send file byte[] fileBuffer = new byte[BUFFER_SIZE]; InputStream fileReader = new BufferedInputStream(new FileInputStream(aFile)); int bytesRead; while ((bytesRead = fileReader.read(fileBuffer)) != EOF) { cipherOut.write(fileBuffer, 0, bytesRead); } cipherOut.flush(); cipherOut.close(); disconnect(); } catch (NoSuchPaddingException nspe) { System.out.println("No such padding."); } catch (NoSuchAlgorithmException nsae) { System.out.println("Invalid algorithm entered"); } catch (ClassNotFoundException cnfe) { System.out.println("Class not found."); } catch (InvalidKeyException ike) { System.out.println("Invalid key used for file encryption."); } catch (FileNotFoundException fnfe) { System.out.println("Invalid file entered."); return; } catch (IllegalBlockSizeException ibse) { System.out.println("Illegal block size used for encryption."); } }
/** * @param s * @return * @throws GeneralSecurityException * @throws UnsupportedEncodingException */ public static String decrypt(final String s) throws GeneralSecurityException, UnsupportedEncodingException { String decrypted = null; try { if (s != null) { final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); final SecretKey secretKey = secretKeyFactory.generateSecret(new PBEKeySpec(secret.toCharArray())); final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); cipher.init(Cipher.DECRYPT_MODE, secretKey, new PBEParameterSpec(SALT, 20)); final byte[] stringBytes = s.getBytes("UTF-8"); final byte[] decodedBytes = Base64.decode(stringBytes, Base64.DEFAULT); final byte[] decryptedBytes = cipher.doFinal(decodedBytes); decrypted = new String(decryptedBytes, "UTF-8"); } } catch (GeneralSecurityException x) { throw x; } catch (UnsupportedEncodingException x) { throw x; } catch (Exception x) { DBG.m(x); } return decrypted; }
public void run() { try { ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); BigInteger bg = dhSpec.getG(); BigInteger bp = dhSpec.getP(); oos.writeObject(bg); oos.writeObject(bp); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH"); kpg.initialize(1024); KeyPair kpa = (KeyPair) ois.readObject(); KeyAgreement dh = KeyAgreement.getInstance("DH"); KeyPair kp = kpg.generateKeyPair(); oos.writeObject(kp); dh.init(kp.getPrivate()); Key pk = dh.doPhase(kpa.getPublic(), true); MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); byte[] rawbits = sha256.digest(dh.generateSecret()); Cipher c = Cipher.getInstance(CIPHER_MODE); SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES"); byte ivbits[] = (byte[]) ois.readObject(); IvParameterSpec iv = new IvParameterSpec(ivbits); c.init(Cipher.DECRYPT_MODE, key, iv); Mac m = Mac.getInstance("HmacSHA1"); SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1"); m.init(mackey); byte ciphertext[], cleartext[], mac[]; try { while (true) { ciphertext = (byte[]) ois.readObject(); mac = (byte[]) ois.readObject(); if (Arrays.equals(mac, m.doFinal(ciphertext))) { cleartext = c.update(ciphertext); System.out.println(ct + " : " + new String(cleartext, "UTF-8")); } else { // System.exit(1); System.out.println(ct + "error"); } } } catch (EOFException e) { cleartext = c.doFinal(); System.out.println(ct + " : " + new String(cleartext, "UTF-8")); System.out.println("[" + ct + "]"); } finally { if (ois != null) ois.close(); if (oos != null) oos.close(); } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { // prompt user to enter a port number System.out.print("Enter the port number: "); Scanner scan = new Scanner(System.in); int port = scan.nextInt(); scan.nextLine(); System.out.print("Enter the host name: "); String hostName = scan.nextLine(); // Initialize a key pair generator with the SKIP parameters we sepcified, and genrating a pair // This will take a while: 5...15 seconrds System.out.println("Generating a Diffie-Hellman keypair: "); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH"); kpg.initialize(PARAMETER_SPEC); KeyPair keyPair = kpg.genKeyPair(); System.out.println("key pair has been made..."); // one the key pair has been generated, we want to listen on // a given port for a connection to come in // once we get a connection, we will get two streams, One for input // and one for output // open a port and wait for a connection ServerSocket ss = new ServerSocket(port); System.out.println("Listeining on port " + port + " ..."); Socket socket = ss.accept(); // use to output and input primitive data type DataOutputStream out = new DataOutputStream(socket.getOutputStream()); // next thing to do is send our public key and receive client's // this corresponds to server step 3 and step 4 in the diagram System.out.println("Sending my public key..."); byte[] keyBytes = keyPair.getPublic().getEncoded(); out.writeInt(keyBytes.length); out.write(keyBytes); System.out.println("Server public key bytes: " + CryptoUtils.toHex(keyBytes)); // receive the client's public key System.out.println("Receiving client's public key..."); DataInputStream in = new DataInputStream(socket.getInputStream()); keyBytes = new byte[in.readInt()]; in.readFully(keyBytes); // create client's public key KeyFactory kf = KeyFactory.getInstance("DH"); X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes); PublicKey clientPublicKey = kf.generatePublic(x509Spec); // print out client's public key bytes System.out.println( "Client public key bytes: " + CryptoUtils.toHex(clientPublicKey.getEncoded())); // we can now use the client's public key and // our own private key to perform the key agreement System.out.println("Performing the key agreement ... "); KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(keyPair.getPrivate()); ka.doPhase(clientPublicKey, true); // in a chat application, each character is sendt over the wire, separetly encrypted, // Instead of using ECB, we are goin to use CFB, with a block size of 8 bits(1byte) // to send each character. We will encrypt the same character in a different way // each time. But in order to use CFB8, we need an IVof 8 bytes. We will create // that IV randomly and and send it to the client. It doesn't matter if somoene // eavesdrops on the IV when it is sent over the wire. it's not sensitive info // creating the IV and sending it corresponds to step 6 and 7 byte[] iv = new byte[8]; SecureRandom sr = new SecureRandom(); sr.nextBytes(iv); out.write(iv); // we generate the secret byte array we share with the client and use it // to create the session key (Step 8) byte[] sessionKeyBytes = ka.generateSecret(); // create the session key SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede"); DESedeKeySpec DESedeSpec = new DESedeKeySpec(sessionKeyBytes); SecretKey sessionKey = skf.generateSecret(DESedeSpec); // printout session key bytes System.out.println("Session key bytes: " + CryptoUtils.toHex(sessionKey.getEncoded())); // now use tha that session key and IV to create a CipherInputStream. We will use them to read // all character // that are sent to us by the client System.out.println("Creating the cipher stream ..."); Cipher decrypter = Cipher.getInstance("DESede/CFB8/NoPadding"); IvParameterSpec spec = new IvParameterSpec(iv); decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec); CipherInputStream cipherIn = new CipherInputStream(socket.getInputStream(), decrypter); // we just keep reading the input and print int to the screen, until -1 sent over int theCharacter = 0; theCharacter = cipherIn.read(); while (theCharacter != -1) { System.out.print((char) theCharacter); theCharacter = cipherIn.read(); } // once -1 is received we want to close up our stream and exit cipherIn.close(); in.close(); out.close(); socket.close(); }