Skip to content Skip to sidebar Skip to footer

Encrypt/decrypt String In Android And Java Different Values

I´m using this code to Encrypt and Decrypt in Java and Android some Strings and in each system I get a different value. The code I'm using comes from http://www.androidsnippets.co

Solution 1:

This is just my guess, but I think the reason is your key derivation. I'm not really a Java developer though, so I might not be understanding the code correctly.

This code always calls getRawKey() when you encrypt and decrypt. getRawKey() looks like it takes something they call a seed, or your shared secret, and uses it to compute a new random key to do the actual encryption/decryption.

SecureRandomsr= SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    kgen.init(128, sr); // 192 and 256 bits may not be availableSecretKeyskey= kgen.generateKey();

According to Java docs found here, setSeed() "Reseeds this random object. The given seed supplements, rather than replaces, the existing seed."

My guess is that the initial state of the RNG is different on each system/platform, and thus it's giving you different results. You should fix the key derivation to something more standard and consistent, or use an already established crypto system, like PGP in the Bouncy Castle libraries.

Solution 2:

This example will demonstrate to how to encrypt a sting and decrypt, for that purpose we need a shif key which will shift the one character to another character, for exaple if you have 'b' and using shift key=2 then it will becom 98+2=100 which ='d' and again 100-2=98 which is 'b', so this will perform in this way.

Make your String encrypt here !

finalintshift_key=4; //it is the shift key to move charcter, like if i have 'a' then a=97+4=101 which =e and thus it changesStringplainText="piran jhandukhel"; 
    char character; 
     char ch[]=newchar[plainText.length()];//for storing encrypt charfor (intiteration=0; iteration < plainText.length(); iteration++)
            {
                    character = plainText.charAt(iteration); //get characters
                    character = (char) (character + shift_key); //perform shift
              }     ch[iteration]=character;//assign char to char arrayStringencryptstr= String.valueOf(ch);//converting char array to string
     Toast.makeText(this, "Encrypt string is "+ encryptstr Toast.LENGTH_LONG).show();

Make Your String Decrypt here !

for(int i=0;i<encryptstr.length();i++)
     {
        character=str.charAt(i);
        character = (char) (character -shift_key); //perform shift
            ch[i]=character;
     }
 Stirngdecryptstr= String.valueOf(ch);
     Toast.makeText(this, "Decrypted String is "+decryptstr, Toast.LENGTH_LONG).show();

Solution 3:

Looks like it will have different output every time you encrypt it. This is normal.

Post a Comment for "Encrypt/decrypt String In Android And Java Different Values"