예제 #1
0
  /*
   * 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;
  }
예제 #2
0
  // creates an crypto object that uses PBE based DES encryption.... and yeah, DES is horrid, but
  // its what we've got right now
  Encrypter(String password) {
    try {
      // key... like the one I don't to the office... which means I get locked out post 5
      KeySpec keySpec = new PBEKeySpec(password.toCharArray());
      SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

      encryptionCipher = Cipher.getInstance(key.getAlgorithm());
      decryptionCipher = Cipher.getInstance(key.getAlgorithm());
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

      encryptionCipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
      decryptionCipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (Exception e) {
      System.out.println("Encryption Object Error: " + e);
    }
  }
예제 #3
0
  public EncryDes() {
    try {
      // Create the key,"hshundsun2008"为随即初始化密文
      String passPhrase = "hshundsun2008";
      /* 生成秘钥 */
      KeySpec keySpec = new DESKeySpec(passPhrase.getBytes());
      SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
      // SecretKeySpec key = new
      // SecretKeySpec(passPhrase.getBytes(),"DES");
      /* 初始化加解密实例 */
      ecipher = Cipher.getInstance(key.getAlgorithm());
      dcipher = Cipher.getInstance(key.getAlgorithm());

      // Prepare the parameter to the ciphers
      // AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
      // iterationCount);
      // Create the ciphers
      ecipher.init(Cipher.ENCRYPT_MODE, key);
      dcipher.init(Cipher.DECRYPT_MODE, key);

    } 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();
  }
예제 #5
0
  /**
   * Reads the raw data from the SecretKey File, creates a SecretKey from that raw data, reads the
   * raw data from the input File, and then decrypts and saves its contents to the output File.
   *
   * @param input the File to be read and decrypted
   * @param output the File the decrypted data will be saved to
   * @param keyFile the File the SecretKey data will be loaded from
   * @throws InvalidKeyException if the given key material is shorter than 8 bytes or if the given
   *     key is inappropriate for initializing this cipher, or if this cipher is being initialized
   *     for decryption and requires algorithm parameters that cannot be determined from the given
   *     key, or if the given key has a keysize that exceeds the maximum allowable keysize (as
   *     determined from the configured jurisdiction policy files).
   * @throws IOException if any of the files do not exist, are a directory rather than a regular
   *     file, or for some other reason cannot be opened for reading or if an I/O error occurs.
   * @throws IllegalBlockSizeException if the cipher is a block cipher, no padding has been
   *     requested (only in encryption mode), and the total input length of the data processed by
   *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
   *     process the input data provided.
   * @throws BadPaddingException if the cipher is in decryption mode, and (un)padding has been
   *     requested, but the decrypted data is not bounded by the appropriate padding bytes.
   * @throws NoSuchAlgorithmException if no Provider supports a SecretKeyFactorySpi implementation
   *     for the specified algorithm.
   * @throws InvalidKeySpecException if the given key specification is inappropriate for this
   *     secret-key factory to produce a secret key.
   * @throws UnsupportedOperationException if algorithm is not DES or DESede
   */
  public void decrypt(File input, File output, File keyFile)
      throws InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException,
          NoSuchAlgorithmException, InvalidKeySpecException {
    if (debug) {
      System.out.println("Loading key...");
    }
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(keyFile);
      data = new byte[fis.available()];
      fis.read(data);
    } finally {
      if (fis != null) {
        fis.close();
      }
    }
    switch (Algorithm.valueOf(algorithm)) {
      case DES:
        key = SecretKeyFactory.getInstance(algorithm).generateSecret(new DESKeySpec(data));
        break;
      case DESede:
        key = SecretKeyFactory.getInstance(algorithm).generateSecret(new DESedeKeySpec(data));
        break;
      default:
        throw new UnsupportedOperationException("Unsupported decryption algorithm");
    }

    if (debug) {
      System.out.println("Initializing decryption...");
    }
    cipher.init(Cipher.DECRYPT_MODE, key);
    if (debug) {
      System.out.println("Reading data...");
    }
    fis = null;
    try {
      fis = new FileInputStream(input);
      data = new byte[(int) input.length()];
      fis.read(data);
    } finally {
      if (fis != null) {
        fis.close();
      }
    }
    if (debug) {
      System.out.println("Decrypting data...");
    }
    data = cipher.doFinal(data);
    if (debug) {
      System.out.println("Saving data...");
    }
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(output);
      fos.write(data);
    } finally {
      if (fos != null) {
        fos.close();
      }
    }
    if (debug) {
      System.out.println("Decryption complete!");
    }
    data = null;
  }