Android cryptography library with SecureRandom patches.

Overview

CircleCI Bintray License GitHub issues

EasyCrypt

Secure and efficient cryptography library for Android. (Auto fix SecureRandom bugs in API 18 and below.)

Note: EasyCrypt uses only secure implementations and all the known Crypto bugs are already dealt with properly. More information here.

Features

  • AES-256 encryption algorithm
  • CBC/CTR mode of operations
  • Block padding with PKCS7 (only with CBC)
  • Computationally secure random salt (of cipher block size)
  • Password stretching with PBKDF2
  • Random IV generated on each encryption (16 bytes)
  • Supports MD5, SHA1, and SHA2 hash functions
  • Generate secure keys with SecureRandom or random.org
  • Asymmetric encryption with RSA
  • Auto handle large data by using hybrid asymmetric encryption
  • Asymmetric RSA signing and verification
  • Supported RSA key sizes are 2048 bits and 4096 bits
  • Password analysis for strength, crack times, weakness, etc using nulab's zxcvbn4j library

Sample app

Download the sample app from play store.

Install

Add in your app's build.gradle

dependencies {
    ..
    implementation "com.pvryan.easycrypt:easycrypt:1.3.3"
}

Usage

val eCryptSymmetric = ECSymmetric()
val eCryptAsymmetric = ECAsymmetric()
val eCryptHash = ECHash()
val eCryptPass = ECPasswords()

Symmetric key encryption

Encrypt data

eCryptSymmetric.encrypt (input, password,
    object : ECResultListener {

        // Optional
        override fun onProgress(newBytes: Int, bytesProcessed: Long, totalBytes: Long) {

        }

        override fun <T> onSuccess(result: T) {

        }

        override fun onFailure(message: String, e: Exception) {

        }
    },
    outputFile // Optional
)

Decrypt data

eCryptSymmetric.decrypt(input, password,
        object : ECResultListener {

            // Optional
            override fun onProgress(newBytes: Int, bytesProcessed: Long, totalBytes: Long) {

            }

            override fun <T> onSuccess(result: T) {

            }

            override fun onFailure(message: String, e: Exception) {

            }
        },
        outputFile // Optional
)

Asymmetric key encryption

Encrypt data

eCryptAsymmetric.generateKeyPair(object : ECRSAKeyPairListener {

     override fun onSuccess(keyPair: KeyPair) {
         privateKey = keyPair.private as RSAPrivateKey // Save private key
         eCryptAsymmetric.encrypt(input, keyPair.public as RSAPublicKey,
                 object : ECResultListener {

                     // Optional
                     override fun onProgress(newBytes: Int, bytesProcessed: Long, totalBytes: Long) {

                     }

                     override fun <T> onSuccess(result: T) {

                     }

                     override fun onFailure(message: String, e: Exception) {

                     }
                 },
                 outputFile // Optional
         )
     }

     override fun onFailure(message: String, e: Exception) {
         e.printStackTrace()
     }

 }, keySize = eCryptAsymmetric.KeySizes._4096)

Decrypt data

eCryptAsymmetric.decrypt(input, privateKey,
        object : ECResultListener {

            // Optional
            override fun onProgress(newBytes: Int, bytesProcessed: Long, totalBytes: Long) {

            }

            override fun <T> onSuccess(result: T) {

            }

            override fun onFailure(message: String, e: Exception) {

            }
        },
        outputFile // Optional
)

Sign data

eCryptKeys.genRSAKeyPair(object : ECRSAKeyPairListener {

    override fun onGenerated(keyPair: KeyPair) {

        publicKey = keyPair.public as RSAPublicKey

        eCryptAsymmetric.sign(input,
                keyPair.private as RSAPrivateKey,
                object : ECResultListener {

                    // Optional
                    override fun onProgress(newBytes: Int, bytesProcessed: Long, totalBytes: Long) {

                    }

                    override fun <T> onSuccess(result: T) {

                    }

                    override fun onFailure(message: String, e: Exception) {

                    }
                },
                signatureOutputFile)
    }

    override fun onFailure(message: String, e: Exception) {

    }
})

Verify data

eCryptAsymmetric.verify(input, publicKey, signatureFile,
        object : ECVerifiedListener {
            override fun onSuccess(verified: Boolean) {

            }

            override fun onFailure(message: String, e: Exception) {

            }
        }
)

Hash data

eCryptHash.calculate(input, hashAlgorithm, // from ECHashAlgorithms
        object : ECResultListener {

            // Optional
            override fun onProgress(newBytes: Int, bytesProcessed: Long, totalBytes: Long) {

            }

            override fun <T> onSuccess(result: T) {

            }

            override fun onFailure(message: String, e: Exception) {

            }
        },
        outputFile // Optional
)

Analyze password

val analysis: ECPasswordAnalysis = ECPasswordAnalyzer.analyze("thisismypassword")

Input Output
File outputFile
FileInputStream outputFile
ByteArray String or outputFile (if provided)
ByteArrayInputStream String or outputFile (if provided)
String String or outputFile (if provided)
CharSequence String or outputFile (if provided)
Anything else InvalidParameterException

Generate key with SecureRandom (pseudo-random)

val password = eCryptPass.genSecureRandomPassword(length, charArrayOf(/*symbols to be used in password*/))

Generate key with Random.org (true random)

For sample to work enter your API key in FragmentPasswords

eCryptPass.genRandomOrgPassword(
        length,
        "random-org-api-key", //TODO: Replace with your random.org api key
        new ECPasswordListener() {

            @Override
            public void onFailure(@NonNull String message, @NonNull Exception e) {

            }

            @Override
            public void onSuccess(@NonNull String password) {

            }
        });

License

Copyright 2018 Priyank Vasa
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • Decryption breaks on newer Android versions

    Decryption breaks on newer Android versions

    EDIT: to clarify the problem - encryption and decryption on the same platform works! The problem is when you encrypt information on some platforms and then afterwards, decryption of this data is attempted on others. I've seem compatibility problems between these ranges of API versions:

    • 22 or before,
    • 23 through 25,
    • 26 and after,

    meaning, encryption-decryption between devices in each range works, but between devices in different ranges doesn't.

    ORIGINAL post:

    W/System.err: javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
    W/System.err:     at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
    W/System.err:     at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:570)
    W/System.err:     at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:351)
    W/System.err:     at javax.crypto.Cipher.doFinal(Cipher.java:1736)
    W/System.err:     at com.pvryan.easycrypt.symmetric.performDecrypt.invoke$easycrypt_release(performDecrypt.kt:70)
    W/System.err:     at com.pvryan.easycrypt.symmetric.ECSymmetric$decrypt$1.invoke(ECSymmetric.kt:209)
    W/System.err:     at com.pvryan.easycrypt.symmetric.ECSymmetric$decrypt$1.invoke(ECSymmetric.kt:44)
    W/System.err:     at org.jetbrains.anko.AsyncKt$doAsync$1.invoke(Async.kt:140)
    W/System.err:     at org.jetbrains.anko.AsyncKt$doAsync$1.invoke(Unknown Source:0)
    W/System.err:     at org.jetbrains.anko.AsyncKt$sam$Callable$761a5578.call(Unknown Source:2)
    W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
    W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    W/System.err:     at java.lang.Thread.run(Thread.java:764)
    

    It seems that this library is experiencing the same issue found in this other library below (in an older version, they fixed it by enforcing usage of Bouncy Castle instead of the new default provider on Android 6.0 onwards).

    https://github.com/AArnott/PCLCrypto/issues/61

    Please also make this library enforce usage of Bouncy Castle as well as a workaround at least until a fix is found using the new provider on API 23 onwards. EDIT: As I mention below, apparently just doing this workaround won't be enough :(

    I tested on an emulator with API 26.

    Thank you!

    opened by guilhermesgb 12
  • ECResultListener is not working

    ECResultListener is not working

    I am trying to run a method once the encryption is done with the help of the ECResultListener like below:

    String fileKey = "123456";
                            ECSymmetric ecSymmetric = new ECSymmetric();
                            ecSymmetric.encrypt(orginaFile, fileKey, new ECResultListener() {
                                @Override
                                public void onProgress(int newBytes, long processedBytes, long totalBytes) {
    
                                }
    
                                @Override
                                public <T> void onSuccess(T t) {
                                        Toasty.success(singleChatActivity.this, "ENCRYPTED").show(); // DOESN'T display although there is an encrypted file as an result
                                }
    
                                @Override
                                public void onFailure(String s, Exception e) {
    
                                }
                            }, encryptedFile);
    

    Any help?

    opened by JagarYousef 7
  • E/Cannot write to file.: java.io.IOException: Error while finalizing cipher when decrypting on another device

    E/Cannot write to file.: java.io.IOException: Error while finalizing cipher when decrypting on another device

    I am trying to send encrypted files through Firebase storage, when the same encryption/decryption works pretty fine on the same device where I encrypt the data, it gives the following error after 99% of the decryption on another device:

    E/Cannot write to file.: java.io.IOException: Error while finalizing cipher

    Please note that the encryption string key is the same and also the same function to decrypt the file in both devices. Is there something I am missing here?

    opened by cergo1991 5
  • Question: What data type does verify() expect for the Signature file?

    Question: What data type does verify() expect for the Signature file?

    Thank you for this project. I have a hex signature string, what do I need to convert it to in order to use the eCryptAsymmetric.verify() function? Thank you

    opened by danshev 4
  • Cannot write to file.java.io.IOException: Error while finalizing cipher

    Cannot write to file.java.io.IOException: Error while finalizing cipher

    I am trying to decrypt an image after the downloading from Firebase storage directly (in OnSuccessListener) and the log of the progress of decryption works till it reaches 99% and gives the following error: Cannot write to file.java.io.IOException: Error while finalizing cipher Please note:

    • The premissions are granted.
    • The decryption works in other locations.

    Any recommendations for this?

    opened by JagarYousef 3
  • Jcenter shutdown will make this package unavailable

    Jcenter shutdown will make this package unavailable

    Early 2022 Jcenter will become unavailable. This is currently the only source to obtain this package. Migration to Jitpack or MavenCentral could solve the problem.

    opened by JarmoKukkola 0
  • 1.3.5 Package broken

    1.3.5 Package broken

    Describe the bug Release 1.3.5 build is broken. https://jitpack.io/com/github/pvasa/EasyCrypt/1.3.5/build.log

    To Reproduce Steps to reproduce the behavior: See log: https://jitpack.io/com/github/pvasa/EasyCrypt/1.3.5/build.log

    Expected behavior Library should install correctly when installed using Gradle. Currently only the randomorg package is built inside the library.

    Screenshots If applicable, add screenshots to help explain your problem.

    Smartphone (please complete the following information):

    • Device: [e.g. iPhone6]
    • OS: [e.g. iOS8.1]
    • Version [e.g. 22]

    Additional context Add any other context about the problem here.

    opened by luyzdeleon 0
  • Help with this library please !

    Help with this library please !

    Hi there, please i need help with this question in stackoverflow:

    https://stackoverflow.com/questions/55662883/encrypt-data-with-cryptoswift-coming-from-easycrypt

    The android developer used this library inside one application but when i try to decrypt data from iOS (with CryptoSwift), i don't get the excepted results. Some help please ??

    opened by wonder2011 0
Owner
Priyank Vasa
Priyank Vasa
Minecraft Server Software specially designed for Thicc SMP. Here on GitHub without the private patches, just a normal hybrid JettPack-Pufferfish-Empirecraft fork

AlynaaMC A private, custom server software for Thicc SMP and a fork of Pufferfish. Here on GitHub with patches from JettPack, Airplane and Pufferfish

ThiccMC 14 Dec 31, 2021
[Android Library] A SharedPreferences helper library to save and fetch the values easily.

Preference Helper A SharedPreferences helper library to save and fetch the values easily. Featured in Use in your project Add this to your module's bu

Naveen T P 13 Apr 4, 2020
Oratio Library for Android Studio helps you simplify your Android TTS codes

Oratio Oratio is a library for Android Studio. This library is useful to a number of developers who are currently making apps using android TTS(Text-T

Jacob Lim 1 Oct 28, 2021
Android Ptrace Inject for all ABIs and all APIs. Help you inject Shared Library on Android.

Android Ptrace Inject 中文可以参考我的注释内容进行理解 我写的注释相对来说比较全面了 How to build Make sure you have CMake and Ninja in your PATH Edit CMakeLists.txt. Set ANDROID_ND

SsageParuders 65 Dec 19, 2022
YouTube Player library for Android and Chromecast, stable and customizable.

android-youtube-player android-youtube-player is a stable and customizable open source YouTube player for Android. It provides a simple View that can

Pierfrancesco Soffritti 2.9k Jan 2, 2023
A highly customizable calendar library for Android, powered by RecyclerView.

CalendarView A highly customizable calendar library for Android, powered by RecyclerView. With this library, your calendar will look however you want

Kizito Nwose 3.4k Jan 3, 2023
View "injection" library for Android.

Kotter Knife Deprecated: This was a terrible idea because it allocates an object for every view reference. Do not use, and do not use anything like it

Jake Wharton 2.2k Dec 28, 2022
Android library that creates app shortcuts from annotations

Shortbread Android library that generates app shortcuts for activities and methods annotated with @Shortcut. No need to touch the manifest, create XML

Matthias Robbers 1.8k Dec 30, 2022
Kotlin library for Android

KAndroid Kotlin library for Android providing useful extensions to eliminate boilerplate code in Android SDK and focus on productivity. Download Downl

Paweł Gajda 890 Nov 13, 2022
A Lightweight PDF Viewer Android library which only occupies around 125kb while most of the Pdf viewer occupies up to 16MB space.

Pdf Viewer For Android A Simple PDF Viewer library which only occupies around 125kb while most of the Pdf viewer occupies upto 16MB space. How to inte

Rajat 362 Dec 29, 2022
[Android Library] Get easy access to device information super fast, real quick

DeviceInfo-Sample Simple, single class wrapper to get device information from an android device. This library provides an easy way to access all the d

Anitaa Murthy 193 Nov 20, 2022
Maildroid is a small robust android library for sending emails using SMTP server

Maildroid ?? Maildroid is a small robust android library for sending emails using SMTP server ?? Key Features • Add to your project • Documentation •

Nedim 174 Dec 22, 2022
Android calendar library provides easy to use widget with events

Kotlin-AgendaCalendarView Kotlin-AgendaCalendarView based on AgendaCalendarView Kotlin-AgendaCalendarView is a awesome calendar widget with a list of

Ognev Zair 88 Nov 21, 2022
🔓 Kotlin version of the popular google/easypermissions wrapper library to simplify basic system permissions logic on Android M or higher.

EasyPermissions-ktx Kotlin version of the popular googlesample/easypermissions wrapper library to simplify basic system permissions logic on Android M

Madalin Valceleanu 326 Dec 23, 2022
All in 1 picker library for android.

Lassi Lassi is simplest way to pick media (either image, video, audio or doc) Lassi Media picker Key features Simple implementation Set your own custo

MindInventory 137 Dec 30, 2022
With Viola android face detection library, you can detect faces in a bitmap, crop faces using predefined algorithm and get additional information from the detected faces.

Viola Viola android face detection library detects faces automatically from a bitmap, crop faces using the predefined algorithms, and provides supplem

Darwin Francis 58 Nov 1, 2022
Android Spinner Dialog Library supported on both Java and Kotlin, Use for single or multi selection of choice

SpinnerDialog Android Spinner Dialog Library, Use for single or multi selection of choice Android UI Download To include SpinnerDialog in your project

Hamza Khan 55 Sep 15, 2022
Lightweight data loading and caching library for android

ColdStorage A lightweight data loading and caching library for android Quicklinks Feature requests: Got a new requirement? Request it here and it will

Cryptic Minds 41 Oct 17, 2022