Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Encryption & Decryption of String

843810Mar 17 2003 — edited Mar 18 2003
Hi

I'm having troubles encrypting/decrypting text strings. It works fine if the string is shorter than 56 bytes, but with longer strings I get an
javax.crypto.IllegalBlockSizeException: Input length (with padding) not multiple of 8 bytes
when I try to decrypt the encrypted string.
Shouldn't it be possible to encrypt/decrypt strings larger than the key size (56 bytes for DES right??)?
The exception occures on the line
byte[] stringBytes = cipher.doFinal(raw)
Thanks for any help!

Tobias

This is the code handling the encryption/decryption:
private static String encrypt(String string) {
	Key key = getKey();
	if(key == null) {
		return null;	
	}
	try {
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] stringBytes = string.getBytes("UTF-8");
		byte[] raw = cipher.doFinal(stringBytes);
		BASE64Encoder b64e = new BASE64Encoder();
		string = b64e.encode(raw);
	} catch(Exception e) {
		System.out.println("ERROR");
		return null;
	}
	return string;
}

private static String decrypt(String string) {		
	Key key = getKey();
	if(key == null) {
		return null;	
	}
	try {
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, key);
		BASE64Decoder b64d = new BASE64Decoder();
		byte[] raw = b64d.decodeBuffer(string);
		byte[] stringBytes = cipher.doFinal(raw);
		string = new String(stringBytes, "UTF-8");
	} catch(Exception e) {
			System.out.println("ERROR");
			return null;
	}
	return string;
}

private static void createKey() {
	try{
		KeyGenerator generator = KeyGenerator.getInstance("DES");
		generator.init(new SecureRandom());
		Key key = generator.generateKey();
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("key.txt"));
		out.writeObject(key);
		out.flush();
		out.close();
	}	catch(Exception ex) {
		System.out.println("ERROR");
	}
}

private static Key getKey() {
	Key key = null;
	
	try{
		File keyFile = new File("key.txt");
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("key.txt");
		key = (Key)in.readObject();
		in.close();
	}	catch(Exception e){
		System.out.println("ERROR");
	}
	return key;
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 15 2003
Added on Mar 17 2003
2 comments
328 views