Easy way to Encrypt/Decrypt string in Android

后端 未结 5 1127
旧时难觅i
旧时难觅i 2020-12-04 10:50

My question is how to encrypt a String:

String AndroidId;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(save         


        
5条回答
  •  余生分开走
    2020-12-04 10:52

    Try with below code it`s working for me.

    AES Encryption

    public static String getEncryptedString(String value) {
            try {
              byte[] key = your Key in byte array;
              byte[] input = sault in byte array
    
                return Base64.encodeToString(encrypt(value.getBytes("UTF-8"), key, input), Base64.DEFAULT);
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        }
    
    
     public static byte[] encrypt(byte[] data, byte[] key, byte[] ivs) {
            try {
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
                byte[] finalIvs = new byte[16];
                int len = ivs.length > 16 ? 16 : ivs.length;
                System.arraycopy(ivs, 0, finalIvs, 0, len);
                IvParameterSpec ivps = new IvParameterSpec(finalIvs);
                cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivps);
                return cipher.doFinal(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    

提交回复
热议问题