Node:Assembly Example, Previous:Assembly, Up:Assemblies



Example

The following example shows an Assembly that compresses its input data, before encrypting it with a Blowfish algorithm, in OFB mode, with PKCS7 padding.

 import gnu.crypto.Registry;
 import gnu.crypto.util.Util;
 import gnu.crypto.assembly.Assembly;
 import gnu.crypto.assembly.Cascade;
 import gnu.crypto.assembly.Direction;
 import gnu.crypto.assembly.Stage;
 import gnu.crypto.assembly.Transformer;
 import gnu.crypto.assembly.TransformerException;
 import gnu.crypto.cipher.Blowfish;
 import gnu.crypto.cipher.IBlockCipher;
 import gnu.crypto.mode.IMode;
 import gnu.crypto.mode.ModeFactory;
 import gnu.crypto.pad.IPad;
 import gnu.crypto.pad.PadFactory;
 
 
 HashMap attributes = new HashMap();
 HashMap modeAttributes = new HashMap();
 
 Cascade ofbBlowfish = new Cascade();
 Object modeNdx = ofbBlowfish.append(
 Stage.getInstance(
 ModeFactory.getInstance(Registry.OFB_MODE, new Blowfish(), 8),
 Direction.FORWARD));
 
 attributes.put(modeNdx, modeAttributes);
 IPad pkcs7 = PadFactory.getInstance(Registry.PKCS7_PAD);
 
 Assembly asm = new Assembly();
 asm.addPreTransformer(Transformer.getCascadeTransformer(ofbBlowfish));
 asm.addPreTransformer(Transformer.getPaddingTransformer(pkcs7));
 asm.addPreTransformer(Transformer.getDeflateTransformer());
 
 // plaintext and key material
 byte[] km = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8};
 byte[] iv = new byte[] {-1, -2, -3, -4, -5, -6, -7, -8, -9};
 byte[] pt = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
 byte[] tpt = new byte[11 * pt.length];
 
 // forward transformation
 modeAttributes.put(IBlockCipher.KEY_MATERIAL, km);
 modeAttributes.put(IMode.IV, iv);
 attributes.put(Assembly.DIRECTION, Direction.FORWARD);
 try
 {
 asm.init(attributes);
 }
 catch (TransformerException x)
 {
 x.printStackTrace(System.err);
 }
 
 byte[] ct = null;
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 try
 {
 for (int i = 0; i < 10; i++)
 { // transform in parts of 12-byte a time
 System.arraycopy(pt, 0, tpt, i * pt.length, pt.length);
 ct = asm.update(pt);
 baos.write(ct, 0, ct.length);
 }
 }
 catch (TransformerException x)
 {
 x.printStackTrace(System.err);
 }
 
 try
 {
 System.arraycopy(pt, 0, tpt, 10 * pt.length, pt.length);
 ct = asm.lastUpdate(pt);
 }
 catch (TransformerException x)
 {
 x.printStackTrace(System.err);
 }
 
 baos.write(ct, 0, ct.length);
 ct = baos.toByteArray();
 
 // reversed transformation
 attributes.put(Assembly.DIRECTION, Direction.REVERSED);
 try
 {
 asm.init(attributes);
 }
 catch (TransformerException x)
 {
 x.printStackTrace(System.err);
 }
 
 byte[] ot = null;
 try
 {
 ot = asm.lastUpdate(ct); // transform the lot in one go
 }
 catch (TransformerException x)
 {
 x.printStackTrace(System.err);
 }
 

AltStyle によって変換されたページ (->オリジナル) /