GithubHelp home page GithubHelp logo

simbiose / encryption Goto Github PK

View Code? Open in Web Editor NEW
354.0 25.0 79.0 320 KB

Encryption is a simple way to encrypt and decrypt strings on Android and Java project.

License: MIT License

Java 100.00%
java encryption android decrypt-strings kotlin kotlin-android

encryption's Introduction

Encryption

Encryption is a simple way to encrypt and decrypt strings on Android and Java project.

Android Arsenal Build Status Build Status

How to use

1º Add JitPack to your build file

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
  }
}

2º Add the gradle dependency

compile 'com.github.simbiose:Encryption:2.0.1'

3º Get an Encryption instance

String key = "YourKey";
String salt = "YourSalt";
byte[] iv = new byte[16];
Encryption encryption = Encryption.getDefault(key, salt, iv);

4º Encrypt your text

String encrypted = encryption.encryptOrNull("Text to be encrypt");

5º Decrypt your text

String decrypted = encryption.decryptOrNull(encrypted);

Custom usage

You can use you own builder

Encryption encryption = new Encryption.Builder()
                .setKeyLength(128)
                .setKey("YourKey")
                .setSalt("YourSalt")
                .setIv(yourByteIvArray)
                .setCharsetName("UTF8")
                .setIterationCount(1)
                .setDigestAlgorithm("SHA1")
                .setBase64Mode(Base64.DEFAULT)
                .setAlgorithm("AES/CBC/PKCS5Padding")
                .setSecureRandomAlgorithm("SHA1PRNG")
                .setSecretKeyType("PBKDF2WithHmacSHA1")
                .build();

See more on Examples folder, there is an Android, a Java and a Kotlin project.

FAQ

  • What is Encryption library?
    • Encryption library is an Open Source library to help encryption routines in Android and Java applications, our target is to be simple and secure.
  • What is the "IV", what should be my yourByteIvArray
    • Encryption 1.2+ uses by default the AES algorithm in CBC mode, so to encrypt and decrypt works you should have the same key and the same IV byte array to encrypt and to decrypt. An example of IV is byte[] iv = {-89, -19, 17, -83, 86, 106, -31, 30, -5, -111, 61, -75, -84, 95, 120, -53}; like you can see, 16 bytes in a byte array. So if you want to use this library I recommend you create you own IV and save it 💾.
  • I Don't like null returns when errors occurs, what to do to handle errors?
    • You have the power to handle the exceptions, instead of uses encryptOrNull method just uses the encrypt method. The same for the decryptOrNull, just uses the decrypt method.
  • I'm getting problems with main thread, what to do?
    • Encrypt routines can take time, so you can uses the encryptAsync with a Encryption.Callbackto avoid ANR'S. The same for decryptAsync
  • I'm an older user, version 1.4 or less, what to do to update Encrypt to version 2.+?
    • The library has changed the default iteration count from 65536 to 1, it improve the performance, if you have a code using the old version or if you prefer to use a big iteration count you just need to use a custom builder instead of get the default builder and set the iteration count you want
    • As far as the library uses 1 as default iteration count we do not need anymore the getLowIteration and it was removed from project, if you use it you can just change to getDefault
    • MIT is the project license so feel free to use it 🎉
  • I'm a very older user, version 1.1 or less, what to do to update Encrypt to version 1.2+?
    • The library has several changes in his structure in version 1.2, both in algorithm and in code usage, so if you are an older user you need migrate the encrypted stuff or configure the Builder manually to the same parameters used in version 1.1 and olds.

Want to contribute?

Fell free to contribute, We really like pull requests :octocat:

Third part

  • Copyright (C) 2010 The Android Open Source Project, applied to:
    • Base64 (third.part.android.util.Base64) original comes from here

encryption's People

Contributors

ademar111190 avatar brianplummer avatar walmyrcarvalho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

encryption's Issues

Android P

Starting in Android P, Crypto JCA provider has been removed. Calls to SecureRandom.getInstance("SHA1PRNG", "Crypto") will throw NoSuchProviderException.

Proguard settings

Please mention the proguard settings to be used with this library.

With minifyEnabled I am getting this exception

java.lang.IncompatibleClassChangeError: Expected 'byte[] third.part.android.util.c.a' to be a instance field rather than a static field (declaration of 'third.part.android.util.c' appears in /base.apk)
`at third.part.android.util.c.(Unknown Source)

                                                   at third.part.android.util.Base64.d(Unknown Source)

                                                   at third.part.android.util.Base64.c(Unknown Source)

                                                   at third.part.android.util.Base64.encodeToString(Unknown Source)

                                                   at se.simbio.encryption.Encryption.b(Unknown Source)

                                                   at se.simbio.encryption.Encryption.decrypt(Unknown Source)`

How to avoid IllegalBlockSizeException?

Hello,
I still obtaining following Exception randomly during the sync (encrypt/decrypt) of the values.
I have no idea how to avoid the following Exception, what I'm doing wrong? Encryption/Decryption is processed in async services. Many thanks for any hint.

03-05 10:29:28.624 2633-2835/? W/System.err: javax.crypto.IllegalBlockSizeException: error:1e00007b:Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_LENGTH
03-05 10:29:28.624 2633-2835/? W/System.err: at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
03-05 10:29:28.624 2633-2835/? W/System.err: at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:570)
03-05 10:29:28.624 2633-2835/? W/System.err: at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:351)
03-05 10:29:28.624 2633-2835/? W/System.err: at javax.crypto.Cipher.doFinal(Cipher.java:1736)
03-05 10:29:28.624 2633-2835/? W/System.err: at se.simbio.encryption.Encryption.decrypt(Encryption.java:179)
03-05 10:29:28.624 2633-2835/? W/System.err: at com.mypackage.security.Security.decryptString(Security.java:127)
03-05 10:29:28.624 2633-2835/? W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
03-05 10:29:28.624 2633-2835/? W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
03-05 10:29:28.624 2633-2835/? W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
03-05 10:29:28.624 2633-2835/? W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
03-05 10:29:28.624 2633-2835/? W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
03-05 10:29:28.624 2633-2835/? W/System.err: at java.lang.Thread.run(Thread.java:764)

My Encrypt, Decrypt methods are following:

public String decryptString(final String string, Context context) {
        String decryptedString;
        if (Constants.Global.ENCRYPTION_ENABLED) {
            //Logger.d("decrypting " + string);
            if (string != null) {
                try {
                    decryptedString = encryptionInstance.decrypt(string);
                } catch (Exception e) {
                    decryptedString = "";
                    e.printStackTrace();
                }
            } else {
                decryptedString = "";
            }
        } else {
            decryptedString = string;
        }
        return decryptedString;
    }

public String encryptString(final String string, Context context) {
        String encryptedString;
        if(Constants.Global.ENCRYPTION_ENABLED) {
            //Logger.d("encrypting " + string);
            if(string != null) {
                try {
                    encryptedString = encryptionInstance.encrypt(string);
                } catch (Exception e) {
                    encryptedString = "";
                    e.printStackTrace();
                }
            } else {
                encryptedString = "";
            }
        } else {
            encryptedString  = string;
        }
        return encryptedString;
    }

Decryption taking too much time .

Hi i am using this library to store values in shared pref , currently i'm using version 1.2.0 .
in my onCreate Method i'm getting values from sharedpref and after decryption i'm storing in variables . Now my problem is that Its taking too much time and also when i generate Signed APK with release build type , its returns Null in decyryptornull method .
Please help

AES in ECB mode is Insecure

It's my understanding that the default cipher mode for AES with javax.crypto.cipher is ECB. You aren't specifying anything else, so it looks like that's what your utility uses. AES used in ECB mode is insecure. Duplicate plaintext blocks will result in the same ciphertext every time.

This can be mitigated by using AES in CBC mode with random IVs from a cryptographically secure pseudo-random number generator (CSPRNG). I'm not very familiar with Java, but I think that SecureRandom is considered secure as long as you do not seed it manually.

Suboptimal key derivation

There are several points making the key derivation weaker than it could be, the main problem being SHA1 which caps the entropy at 160 bit. Also there already are known SHA1-collision making SHA1 a broken hash function. While the impact on key derivation is limited, you better are safe-than-sorry when it comes to encryption.

  1. The hashing before using PBKDF2 is kinda useless as PBKDF2 also hashes the incoming password. Also the usually used SHA1 limits the maximum security of the current scheme to 160 bits as mentioned above. Removing the hash-step would also speed up encryption a little bit.
  2. The usually used "PBKDF2WithHmacSHA1" also used SHA1 which, as mentioned above, rather should not be used. AFAIK you can just use "PBKDF2WithHmacSHA256" or "PBKDF2WithHmacSHA512", so you could change the default value to switch to more secure hash methods.
  3. The default iteration count of 1 is very low and thus kind of makes the usage of PBKDF2 unnecessary as it is supposed to be a slower key-derivation function to make brute-forcing passwords harder. I know that there were performance complaints but you can use a compromise like 4096 which is used in WPA2 according to Wikipedia. This would still make brute-forcing the password roughly 4000 times more time consuming that the iteration count of 1 but should still be reasonably fast even on mobile devices.

Equivalent default build encryption in OpenSSL

Hi, I tried to use the openssl tool for encrypt according to the standard build of this library, but I was not successful, could you help me?
Maybe I'm not going wrong IV, because in the library it only accepts 16 bytes after converting to byteArray

I try: openssl aes-128-cbc -e -pbkdf2 -salt -S "----------------" -iv "--------------------------------" -iter 1 -in ./tls_key_original.key -out tls_openssl.key -pass pass:"----------------" -base64

EditText text not being recognized as String

I'm trying to encrypt text from an EditText field, which is input by the user assigned an equated variable which goes through the encryption process. It does not recognize [EditText].text as a string but an editable. Is there any way to use user's input instead of hardcoding a string?

cant import this project in eclipse

dear developer ,
you work is good. but i cant import this project in my eclipse .and also tell me how to encrypt my string url in android project.

Jar in Maven repo

Hi @ademar111190

I can see that you published aar into Maven repo. However it looks like there are no something special for Android in your lib. It will be better to publish it as usual jar. Also it will be cool to remove android package dependencies.

Currently I cannot use your library in simple Java or Gradle/Groovy.

Callback

Hi, how would I use the encrypt/decrypt async in Activity? I already implemented the Encryption.Callback. What should I do next? Thanks!

JS Port

How about making a javascript port ?

Attempting to decrypt data with invalid key may return non-null

I expect to get null any time when decryption failed while using decryptOrNull, but sometimes it returns junk when decrypting with invalid key.

Here is a test:

public class EncryptUnitTest {

    private final static String SALT = "1EykVsCVKk1pkZq08PDGTg";
    private final static byte[] IV = new byte[] {
            55, -115, 76, -14, 79, -107, -115, 35,
            -122, -24, -76, -82, 39, -92, 104, 41
    };

    @Test
    public void encrypt_isWorking() throws Exception {
        String validPin = "0000";
        String invalidPin = "2222"; // "5555" works as well
        String password = "Terminator_2";

        Encryption enc = Encryption.getDefault(validPin, SALT, IV);
        String encryptedPassword = enc.encryptOrNull(password);
        assertNotNull(encryptedPassword); // encrypted password, ok


        // decrypt using invalid key
        Encryption dec = Encryption.getDefault(invalidPin, SALT, IV);
        String decryptedPassword = dec.decryptOrNull(encryptedPassword);
        assertNull(decryptedPassword); // FAILED: must be null, but it's junk
    }
}

This test fails on assertNull with message:
java.lang.AssertionError: expected null, but was:<�f �����S��!Q��>

I suspect the padding block is OK in this case and library threats this situation as successful decryption.

How decrypt in php?

I have saved password in database mysql and now i want login via web browser.. how to decrypt?

maven can't download this source

I want to use this into my project ,I use maven , so I add encrytion's dependecy ,but maven can't download source . Do you know how to solve this problem?

last block incomplete in decryption

Hi,

I'm using this as a class (seen it in stackOverFlow), but it's not working for me.

I have an application that makes a xml file and then sends it to another device. I encrypted the file in the first one, then the second one has to decrypt it and read it and then open another application which has to decrypt it one more time. This another app is the one that encrypted the file in the first device.

I have tried to use just one device (I create the file, then move it manually to a directory and read it from the application) and it works ok, but when i send the file from one device to another I get a "last block incomplete in decryption" exception. Why is this? how do I solve it?

thanks in advance

Encrypted data is not authenticated / potential padding oracles

The encrypted data is not authenticated, thus allowing easy manipulation of the ciphertext with predictable changes to the plaintext. This is especially bad as unauthenticated AES-CBC often leads to padding oracle attacks which allow the recovery of the plaintext by an active adversary.

How to fix:

  1. Apply a secure message-authentication-code (MAC) like HMAC-SHA256 on the ciphertext and the IV. Always check the MAC BEFORE decrypting the ciphertext.

  2. Alternatively, use an AAD-Scheme like AES-GCM or ChaCha20-Ploy1305.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.