Skip to Main Content

Java Programming

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!

Byte to String conversion for encryption and decryption

800309Dec 29 2008 — edited Dec 29 2008
Hi Friends ,

I am trying to encrypt a password string and then decrypt it .
The thing is i need to convert the encrypted String which is a byte array to a string . While decrypting i need to convert the encrypted string to a Byte .
I tried using String.getBytes() for converting a string to byte array , but this is giving an exception
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
Please find below my code
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
/**
 *
 * @author rajeshreddy
 */
public class Encrypt
{
    public static void main(String[] args)
    {
        try
        {
            
	   BASE64Encoder en = new BASE64Encoder();
	   BASE64Decoder en1 = new BASE64Decoder(); 
           
            String password = "S_@!et";
        
            KeyGenerator kg = KeyGenerator.getInstance("DESede");
            Key key = kg.generateKey();

            Cipher cipher = Cipher.getInstance("DESede");
            cipher.init(Cipher.ENCRYPT_MODE, key);

            // Encrypt password
            byte[] encrypted = cipher.doFinal(password.getBytes());
            String e = new String(encrypted);
            byte[] toDecrypt  = e.getBytes();
            // Create decryption cipher
            cipher.init(Cipher.DECRYPT_MODE, key);
            
            byte[] decrypted = cipher.doFinal(toDecrypt);

            // Convert byte[] to String
            String decryptedString = new String(decrypted);

            System.out.println("password: " + password);
            System.out.println("encrypted: " + encrypted);
            System.out.println("decrypted: " + decryptedString);

        } catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
}
I cab use sun.misc.BASE64Decoder and sun.misc.BASE64Encoder which avoids this error, but this packages are sun proprietery packages so there is a chance of removing these in future releases.

Please suggest me the best way to tackle this
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 26 2009
Added on Dec 29 2008
2 comments
715 views