Encrypt-Decrypt String


Encrypt/Decrypt string in Android (using your own secret key)


// create secrete key of sting token/key    
    String keystr = "hkjhgsdghhg";
    byte[] bytearr = new Base32().decode(keystr);
    SecretKey secret = new SecretKeySpec(bytearr, 0, bytearr.length, "AES");

    String password = "123456";
    //Encrept    byte[] cipherText = encryptMsg(password, secret))
    

    public static byte[] encryptMsg(String message, SecretKey secret)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
    {
        /* Encrypt the message. */        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
        return cipherText;
    }

    //Decrept
    password =  decryptMsg(cipherText, secret))

    public static String decryptMsg(byte[] cipherText, SecretKey secret)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException
    {
        /* Decrypt the message, given derived encContentValues and initialization vector. */        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret);
        String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
        return decryptString;
    }

No comments:

Post a Comment

Run/install/debug Android applications over Wi-Fi ?

Open Teminal/cmd --------------- Below steps is for Android 10 or lower Step 1 - Connect the device via USB and make sure debugging is work...