Here is the class of encryption and decryption key

public class SecurityClass { private static Cipher serCretss(String mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { SecretKeySpec sks = null; SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed("any data used as random seed".getBytes()); KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128, sr); sks = new SecretKeySpec((kg.generateKey()).getEncoded(), "AES"); Cipher c = Cipher.getInstance("AES"); if (mode.equals("d")){ c.init(Cipher.DECRYPT_MODE, sks); }else { c.init(Cipher.ENCRYPT_MODE, sks); } return c; } public static byte[] doCript(String myText) { byte[] encodedBytes = null; try { encodedBytes = serCretss("e").doFinal(myText.getBytes()); } catch (Exception e) { Log.e("Crypto", "AES encryption error"); } return encodedBytes; } public static byte[] decodeCript(byte[] convertbyte) { byte[] decodedBytes = null; try { decodedBytes = serCretss("d").doFinal(convertbyte); } catch (Exception e) { Log.e("Crypto", "AES decryption error"); } return decodedBytes; } } 

so do encrypt

 SecurityClass.doCript(a) 

so do decipher

  SecurityClass.decodeCript(a) 

encrypts but when decrypted gives null

    1 answer 1

    When encrypting and decrypting, you use different keys.

    The serCretss() method each time re-generates a new key KeyGenerator.init() - which uses a random generator supplied to it.

    • Thank you very much! Yes, I completely misunderstood the essence of encryption. Corrected, thank you. - elik