/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package buzzerproxy; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.CryptoException; /** * * @author Enger */ public class Crypto { private byte[] key = null; /** * @param key */ public Crypto(byte[] key) { if ( key == null ) throw new NullPointerException( "key == null !!!" ); this.key = key; } /** * @return */ public static byte[] generateSessionID(int dep) { SecureRandom randomr = new SecureRandom(); randomr.setSeed(System.currentTimeMillis()); return randomr.generateSeed( dep ); } /** * @param key * @param plainText * @return */ public String performEncrypt(String plainText) { if ( plainText == null ) { Logger.getLogger( Crypto.class.getName() ).log( Level.SEVERE, null ); throw new NullPointerException( "plainText == null" ); } byte[] ptBytes = plainText.getBytes(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CBCBlockCipher( new AESEngine() ) ); System.out.println(key.length); cipher.init( true, new KeyParameter( key ) ); byte[] rv = new byte[cipher.getOutputSize( ptBytes.length )]; int oLen = cipher.processBytes( ptBytes, 0, ptBytes.length, rv, 0 ); try { cipher.doFinal( rv, oLen ); } catch ( CryptoException ce ) { System.out.println( ce.toString() ); Logger.getLogger( Crypto.class.getName() ).log( Level.SEVERE, null, ce ); } return new String( Hex.encode( rv ) ); } /** * @param key * @param st * @return */ public String performDecrypt(String st) { if ( st == null ) { Logger.getLogger( Crypto.class.getName() ).log( Level.SEVERE, null ); throw new NullPointerException( "plainText == null" ); } byte[] cipherText = Hex.decode( st ); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CBCBlockCipher( new AESEngine() ) ); cipher.init( false, new KeyParameter( key ) ); byte[] rv = new byte[cipher.getOutputSize( cipherText.length )]; int oLen = cipher.processBytes( cipherText, 0, cipherText.length, rv, 0 ); try { cipher.doFinal( rv, oLen ); } catch ( CryptoException ce ) { System.out.println( ce.toString() ); Logger.getLogger( Crypto.class.getName() ).log( Level.SEVERE, null, ce ); } return new String( rv ).trim(); } /* * Testklasse */ public static void main(String[] args) { Crypto crypto = new Crypto( generateSessionID( 16 )); String erg = crypto.performEncrypt( "Test String" ); System.out.println("performEncrypt = " + erg); String back = crypto.performDecrypt( erg ); System.out.println("performDecrypt = " + back); } }