Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I encrypte my password - Android Studio

does someone know how to encrypte the password which the user add`s into the password field?

I tried this tutorial but I didn't get it work.

https://gist.github.com/aogilvie/6267013#file-string_encrypt_decrypt-md

I hope someone can help me :(

like image 494
Shalomi90 Avatar asked Dec 19 '16 13:12

Shalomi90


3 Answers

Quote this post Difference between Hashing a Password and Encrypting it I would recommend you to use hashing (no encrypting) to store passwords. You can use i.e. md5 (not reccomend), sha1, sha2...

Exampled implementation of SHA1: How to SHA1 hash a string in Android?

like image 52
Leśniakiewicz Avatar answered Oct 17 '22 01:10

Leśniakiewicz


public class AESCrypt
{
    private static final String ALGORITHM = "AES";
    private static final String KEY = "1Hbfh667adfDEJ78";

    public static String encrypt(String value) throws Exception
    {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(AESCrypt.ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte [] encryptedByteValue = cipher.doFinal(value.getBytes("utf-8"));
        String encryptedValue64 = Base64.encodeToString(encryptedByteValue, Base64.DEFAULT);
        return encryptedValue64;

    }

    public static String decrypt(String value) throws Exception
    {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(AESCrypt.ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedValue64 = Base64.decode(value, Base64.DEFAULT);
        byte [] decryptedByteValue = cipher.doFinal(decryptedValue64);
        String decryptedValue = new String(decryptedByteValue,"utf-8");
        return decryptedValue;

    }

    private static Key generateKey() throws Exception
    {
        Key key = new SecretKeySpec(AESCrypt.KEY.getBytes(),AESCrypt.ALGORITHM);
        return key;
    }
}

Use this will solve your problem.

like image 28
Rishabh Mahatha Avatar answered Oct 17 '22 01:10

Rishabh Mahatha


This is the easiest solution ever existed for normal encryption. First, add this in your build gradle file:

    implementation 'com.scottyab:aescrypt:0.0.1'

Then use the bellow code for encryption and decryption:

// To Encrypt
String password = "password";
String message = "hello world";	
try {
    String encryptedMsg = AESCrypt.encrypt(password, message);
}catch (GeneralSecurityException e){
    //handle error
}

// To Decrypt
String password = "password";
String encryptedMsg = "2B22cS3UC5s35WBihLBo8w==";
try {
    String messageAfterDecrypt = AESCrypt.decrypt(password, encryptedMsg);
}catch (GeneralSecurityException e){
     //handle error - could be due to incorrect password or tampered encryptedMsg
}
like image 2
Zia Avatar answered Oct 17 '22 02:10

Zia