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

7

7

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.

Joaquin answered 7/5, 2015 at 4:38 Comment(5)
...send this string through a query string... What does it mean?Schizophyceous
IMO, special characters make encryption stronger. Any special reason why you want t avoid them? Why don't you write a simple encryption algorithm which will work for you?Contrastive
you just need to URL-encode the resultFerrand
Hi @Contrastive . I know that it is secure. Can you please suggest me how i can pass it from web url so that i will get all the character and it wont generate the exception.Joaquin
@Ferrand can you suggest me an example.Joaquin
S
6

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

Setser answered 7/5, 2015 at 4:58 Comment(0)
O
4

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

Hope it helps,

Jose Luis

Ovoviviparous answered 7/5, 2015 at 5:1 Comment(2)
that is encoding, not encryptingSchreibman
The question was how to URL Safe encode encrypted data, not how to encrypt it.Ovoviviparous
S
2

You have to use URLEncoder to encode the encrypted value, before sending it through URL.

and at decryption side, you have to use URLDecoder first to decode received data.

You can do following in your code to achieve this :

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);

        String urlEncodeddata=URLEncoder.encode(encryptedValue,"UTF-8");
        return urlEncodeddata;
    }

    @SuppressWarnings("restriction")
    public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        String urlDecodedData=URLDecoder.decode(encryptedData, "UTF-8");
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(urlDecodedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }
Sr answered 7/5, 2015 at 5:9 Comment(3)
Hi @sachin I am getting exception at c.doFinal(decodeValue); How can I resolve that ?Joaquin
what is the exception you are getting ?Sr
sorry, this time i am getting exception like Bad padding Exception by removing the URLDecoder.decode() it is working fine. Sending the value as URL encoder String but while I am getting the value from request paramenter those are still special character.Joaquin
A
2

I had same issue in Spring based application and I solved the problem with Base64 Encoding/Decoding process.

Encoding:

String encryptedString = encrypt(stringData);
byte[] encoded = Base64.getEncoder().encode(encryptedString.getBytes(StandardCharsets.UTF_8));
String base64Encoded = new String(encoded);

Decoding:

byte[] decoded = Base64.getDecoder().decode(base64Encoded.getBytes(StandardCharsets.UTF_8));
String encryptedString = new String(decoded);

Than you can successfully decrypt "encryptedString" value on your decrypt method.

String decryptedString = decrypt(encryptedString);

I hope it helps.

Antabuse answered 20/8, 2019 at 9:34 Comment(1)
I agree with this answer. You can encode the encrypted text like "TEj TWBQExpz8/p5SAjIhA==" to base64. Then you just need to decode the base64 string before decrypting your encrypted text.Unimposing
C
0

Use only URLEncode no need to change code.

String encodedStr = URLEncoder.encode(encrypt("XYZ"), "UTF-8");

And there is no need to use URLDecode for decoding url as you can use normal decrypt(encodedStr);

Coverture answered 8/11, 2017 at 11:12 Comment(0)
P
0

You have to use this in C# Application to encode the encrypted value, before sending it through URL. Decryption side, you have to use UrlDecode first to decode QueryString data.

 Server.UrlEncode("");
 Server.UrlDecode("");
Primavera answered 13/3, 2019 at 8:29 Comment(0)
T
0

You can use Base64.encodeBase64URLSafeString.

Example:

  private static final String ALGORITHM = "AES";
  private static final String TRANSFORMATION = "AES/CBC/PKCS5PADDING";
  private static final String ENCODING = StandardCharsets.UTF_8.toString();

  @Value("${vector}")
  private String vector;

  @Value("${key}")
  private String key;

  public String encrypt(String value) {
    try {
      Cipher cipher = initCipher(ENCRYPT_MODE);
      byte[] encrypted = cipher.doFinal(value.getBytes());
      return Base64.encodeBase64URLSafeString(encrypted);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public String decrypt(String encrypted) {
    try {
      Cipher cipher = initCipher(DECRYPT_MODE);
      byte[] originalText = cipher.doFinal(Base64.decodeBase64(encrypted));
      return new String(originalText);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private Cipher initCipher(int mode) throws Exception {
    IvParameterSpec iv = new IvParameterSpec(vector.getBytes(ENCODING));
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM);
    Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    cipher.init(mode, skeySpec, iv);
    return cipher;
  }
Troche answered 5/2, 2023 at 19:27 Comment(1)
Kindly edit your answer and append the ENCODING to "cipher.doFinal(value.getBytes()" and "return new String(originalText);" as you already did for IV and KEY conversion, thanks.Daile

© 2022 - 2024 — McMap. All rights reserved.