Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8633419
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T09:29:16+00:00 2026-06-12T09:29:16+00:00

I’m using this simple class from a tutorial to encrypt a String in my

  • 0

I’m using this simple class from a tutorial to encrypt a String in my Android app and decrypt it on a Java REST backend:

package classes;


import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class MCrypt {

        private String iv = "fedcba9876543210"; 
        private IvParameterSpec ivspec;
        private SecretKeySpec keyspec;
        private Cipher cipher;

        private String SecretKey = "0123456789abcdef";

        public MCrypt()
        {
                ivspec = new IvParameterSpec(iv.getBytes());

                keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

                try {
                    cipher = Cipher.getInstance("AES/CBC/NoPadding");
                } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                        e.printStackTrace();
                }
        }

        public String encrypt(String text) throws Exception
        {
                if(text == null || text.length() == 0)
                        throw new Exception("Empty string");

                byte[] encrypted = null;

                try {
                        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

                        encrypted = cipher.doFinal(padString(text).getBytes());
                } catch (Exception e)
                {                       
                        throw new Exception("[encrypt] " + e.getMessage());
                }

                return bytesToHex(encrypted);
        }

        public String decrypt(String code) throws Exception
        {
                if(code == null || code.length() == 0)
                        throw new Exception("Empty string");

                byte[] decrypted = null;

                try {
                        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

                        decrypted = cipher.doFinal(hexToBytes(code));

                } catch (Exception e)
                {
                       System.out.println(e.toString());
                }

                return new String(decrypted);
        }



        public static String bytesToHex(byte[] data)
        {
                if (data==null)
                {
                        return null;
                }

                int len = data.length;
                String str = "";
                for (int i=0; i<len; i++) {
                        if ((data[i]&0xFF)<16)
                                str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
                        else
                                str = str + java.lang.Integer.toHexString(data[i]&0xFF);
                }
                return str;
        }


        public static byte[] hexToBytes(String str) {
                if (str==null) {
                        return null;
                } else if (str.length() < 2) {
                        return null;
                } else {
                        int len = str.length() / 2;
                        byte[] buffer = new byte[len];
                        for (int i=0; i<len; i++) {
                                buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
                        }
                        return buffer;
                }
        }



        private static String padString(String source)
        {
          char paddingChar = ' ';
          int size = 16;
          int x = source.length() % size;
          int padLength = size - x;

          for (int i = 0; i < padLength; i++)
          {
                  source += paddingChar;
          }

          return source;
        }
}

Its decrypting my String fine. When I send an encrypted String that i tampered with (replaced a character within the encrypted String, the one that goes in the decrypt method as ‘String code’), I get an exception (NumberFormatException) when I try to convert the byte[] to a String.

I’m totally new to cryptography and know I need to study the basics.

What I’m wondering is: is this the usual way to check if the encrypted String is valid? Isn’t there a boolean method that can check beforehand? If I keep it like this, will the throwing of exceptions have a negative effect on the performance of my backend service?

EDIT: Heres the stacktrace:

java.lang.NumberFormatException: For input string: "zf"
java.lang.NullPointerException
    at java.lang.String.<init>(String.java:601)
    at classes.MCrypt.decrypt(MCrypt.java:71)
    at service.Service.cryptotest(Service.java:340)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at us.antera.t5restfulws.services.impl.RestfulWSDispatcher.invokeMethod(RestfulWSDispatcher.java:133)
    at us.antera.t5restfulws.services.impl.RestfulWSDispatcher.service(RestfulWSDispatcher.java:76)
    at $RequestHandler_15b88bc6f1e4.service(Unknown Source)
    at $RequestHandler_15b88bc6f1d7.service(Unknown Source)
    at org.apache.tapestry5.services.TapestryModule$HttpServletRequestHandlerTerminator.service(TapestryModule.java:253)
    at org.apache.tapestry5.internal.gzip.GZipFilter.service(GZipFilter.java:53)
    at $HttpServletRequestHandler_15b88bc6f1d9.service(Unknown Source)
    at org.apache.tapestry5.internal.services.IgnoredPathsFilter.service(IgnoredPathsFilter.java:62)
    at $HttpServletRequestFilter_15b88bc6f1d5.service(Unknown Source)
    at $HttpServletRequestHandler_15b88bc6f1d9.service(Unknown Source)
    at org.apache.tapestry5.services.TapestryModule$1.service(TapestryModule.java:852)
    at $HttpServletRequestHandler_15b88bc6f1d9.service(Unknown Source)
    at $HttpServletRequestHandler_15b88bc6f1d4.service(Unknown Source)
    at org.apache.tapestry5.TapestryFilter.doFilter(TapestryFilter.java:171)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:399)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

EDIT: Okay, clearly I made some rookie mistakes on my “test scenario” ;). I tried the same call with a valid 16bit hex string and the output of decrypt was some weird looking String, which was what I expected.
So, I will first check if the incoming encrypted String is a valid hex at all, then send it to the decrypt method, then check if the decrypted String contains what I expect it to contain.
Thanks a lot all of you 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T09:29:16+00:00Added an answer on June 12, 2026 at 9:29 am

    So, generally speaking, encryption/decryption doesn’t care about the underlying data – that is to say, that any data can be encrypted, and any data can be decrypted.

    That said, it looks like you have a confusion about the output format. It isn’t a String as such, but binary data encoded into ascii as hex. If you tamper with it without understanding it, you will just end up with an encoding that doesn’t make sense. In this case, the tampered hex-string is no longer a hex-string and cannot be decoded back into a byte stream for decryption. A valid hex-string can only contain the characters [0-9a-f]

    Edit:

    You mention that you are trying to prevent against request forgery. It sounds like you’re going about it in a fairly long-winded way, I might be wrong, but if you could explain your scenario and what you’re trying to achieve, we might be able to come up with a simpler solution.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
Does anyone know how can I replace this 2 symbol below from the string
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have thousands of HTML files to process using Groovy/Java and I need to
I am using Paperclip to handle profile photo uploads in my app. They upload
I'm making a simple page using Google Maps API 3. My first. One marker
I'm new to using the Perl treebuilder module for HTML parsing and can't figure

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.