needs bouncycastle library:
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.51</version> </dependency>
java codes:
import org.bouncycastle.crypto.engines.CAST5Engine; =
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.encoders.Hex;
public void testCipher() throws UnsupportedEncodingException {
String plain = "I am a plain String, yohoo!";
int blockSize = 8;
byte[] oBytes = plain.getBytes();
byte[] enBytes = new byte[oBytes.length];
log.debug("plain :"+plain);
String key = "Iamakey";
//encryption
boolean doEn = true;
CAST5Engine cast5 = new CAST5Engine();
Random r = new Random(new Date().getTime());
byte[] iv = new byte[8];
r.nextBytes(iv);
ParametersWithIV ivPara = new ParametersWithIV(new KeyParameter(Strings.toByteArray(key)), iv);
CFBBlockCipher cfbCipher = new CFBBlockCipher(cast5, blockSize);
cfbCipher.init(doEn, ivPara);
for(int i=0;i<oBytes.length;i++)
cfbCipher.processBlock(oBytes, i, enBytes, i);
enBytes = Bytes.concat(iv, enBytes);
String enStr = Hex.toHexString(enBytes);
log.debug("Encrypted :"+ enStr);
//decryption from String
doEn = false;
enBytes = Hex.decode(enStr);
iv = Arrays.copyOfRange(enBytes, 0, 8);
byte[] msgArray = Arrays.copyOfRange(enBytes, 8, enBytes.length);
cfbCipher = new CFBBlockCipher(cast5, 8);
cfbCipher.init(doEn, new ParametersWithIV(new KeyParameter(key.getBytes()),iv ));
byte[] deBytes = new byte[msgArray.length];
for(int i=0;i<msgArray.length;i++)
cfbCipher.processBlock(msgArray, i, deBytes, i);
log.debug("Decrypted :" + Strings.fromByteArray(deBytes));
assertEquals(plain, Strings.fromByteArray(deBytes));
}