Advertisement
Guest User

Untitled

a guest
Sep 13th, 2013
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.io.OutputStream;
  3.  
  4. import javax.crypto.Cipher;
  5. import javax.crypto.CipherOutputStream;
  6. import javax.crypto.Mac;
  7.  
  8. public class CipherHmacOutputStream_PLAINTEXT_HMAC extends CipherOutputStream {
  9.     private Cipher cipher;
  10.     private Mac mac;
  11.     private byte[] iv;
  12.    
  13.     public CipherHmacOutputStream_PLAINTEXT_HMAC(OutputStream os, Cipher c, Mac m, byte[] iv) {
  14.         super(os, c);
  15.         cipher = c;
  16.         mac = m;
  17.     }
  18.  
  19.     @Override
  20.     public void write(int b) throws IOException {
  21.         mac.update((byte) b);
  22.         super.write(b);
  23.     }
  24.  
  25.     @Override
  26.     public void write(byte[] b) throws IOException {
  27.         mac.update(b);
  28.         super.write(b);
  29.     }
  30.  
  31.     @Override
  32.     public void write(byte[] b, int off, int len) throws IOException {
  33.         mac.update(b, off, len);
  34.         super.write(b, off, len);
  35.     }
  36.  
  37.     @Override
  38.     public void close() throws IOException {
  39.         writeHmac();       
  40.         super.close();
  41.     }
  42.    
  43.     private void writeHmac() throws IOException {
  44.         // Add IV & algorithm details
  45.         try {
  46.             mac.update(iv);
  47.             mac.update(cipher.getAlgorithm().getBytes("UTF8"));
  48.             mac.update(cipher.getParameters().getEncoded());
  49.            
  50.             byte[] macBytes = mac.doFinal();
  51.             super.write(macBytes);
  52.         }
  53.         catch (Exception e) {
  54.             throw new IOException(e);
  55.         }      
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement