Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Encrypt data to a Plain text without Special character in java

I need a encryption algorithm by whick I can encrypt the data to a simple plain text.

Currently i am using AES encrypting algorithm which converts to encrypt string contains Special character.

Here if i send this string through a query string in url I am missing some character like- "+".

So i need a encrypt logic which is secure and contains only alphabet.

Here is my encryption logic :

      public static String encrypt(String Data) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(Data.getBytes());
        String encryptedValue = new BASE64Encoder().encode(encVal);
        return encryptedValue;
    }

    @SuppressWarnings("restriction")
    public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

Here I am getting an encrypted String "TEj+TWBQExpz8/p5SAjIhA=="

while I am sending through query string as

localhost:8080/myproject/home?code=TEj+TWBQExpz8/p5SAjIhA==

i am getting the String in controller as-
"TEj TWBQExpz8/p5SAjIhA=="

"+" symbol is missing thats why i am getting issue while decryption.

Please suggest any new Algorithm or any solution to avoid the Special character.

Thank you.

like image 801
Sachi-17 Avatar asked May 07 '15 04:05

Sachi-17


2 Answers

You can encode your crypted part with URLEncoder

URLEncoder.encode("TEj+TWBQExpz8/p5SAjIhA==", "UTF-8")

to make it valid for the URL.

http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html

like image 59
Kai Mechel Avatar answered Nov 14 '22 23:11

Kai Mechel


You should try Apache Commons Base64 URL safe encoder, which will generate what you need.

Hope it helps,

Jose Luis

like image 45
jbarrueta Avatar answered Nov 14 '22 21:11

jbarrueta