Scytale


Source link: https://github.com/yakivmospan/scytale

Scytale

One tool to manage key generation, key storing and encryption on different APIs of Android.

As you may know Android provides API to use keystore that is stored in system only from API 18. They introduced AndroidKeyStore provider that is responsible for managing this.

But as always there are underwater stones. Up to API 23 you are only able to create asymmetric keys using AndroidKeyStore provider. Also algorithms that you can use are limited. And what about devices below API 18?

I've create API that wraps default JCA API and AndroidKeyStore API and makes it easy to create, manage and use your keys on any Android API.

Sample

// Create and save key Store store = new Store(getApplicationContext());
 if (!store.hasKey("test")) {

 SecretKey key = store.generateSymmetricKey("test", null);
 
}
 ...  // Get key SecretKey key = store.getSymmetricKey("test", null);
  // Encrypt/Decrypt data Crypto crypto = new Crypto(Options.TRANSFORMATION_SYMMETRIC);
 String text = "Sample text";  String encryptedData = crypto.encrypt(text, key);
 Log.i("Scytale", "Encrypted data: " + encryptedData);
  String decryptedData = crypto.decrypt(encryptedData, key);
 Log.i("Scytale", "Decrypted data: " + decryptedData);

How it works?

Depending on what key you need and what Android you are using, API will create keystore file in application inner cache or will use AndroidKeyStore to hold keys. Key generation will be also made with different API. The tables below show what will be used in different cases.

In case you want to generate and save Asymmetric key

API Application Keystore AndroidKeyStore
< 18 +
>= 18 +

In case you want to generate and save Symmetric key

API Application Keystore AndroidKeyStore
< 23 +
>= 23 +

After calling one of generateKey methods, key will be automatically stored in keystore.

To store asymmetric PrivateKey we need to provide X509Certificate. And of course there is no default API to do that.

On 18+ devices it's pretty easy, Google did it for us.

For pre 18 there is one 3rd party library that can create self signed X509Certificate. It is called Bouncy Castle and is available on Maven as well. But after some research I found that Google copied this library to their API but made it private. Why? Don't ask me...

So I decided to make it like this:

  • API will try to get Google Bouncy Castle using reflection (I've checked it on few APIs and it seems to work well)
  • If Google version is missing, API will try to get 3rd party Bouncy Castle library. It will use reflection as well. This has two advantages:
  • You can add this API for 18+ devices without any additional libraries.
  • You can run this API on pre 18 devices without any additional libraries as well. And in case some device will miss Google hidden API you will receive an error and then include Bouncy Castle to project. This is pretty cool if you are getting error on 15 API but your min project API is 16, and there is no errors on it.

In general it creates simple interface to work with Keystore using API provided by Java and different versions of Android.

Extended Usage

Instead of using generateAsymmetricKey(@NonNull String alias, char[] password) method you can use generateAsymmetricKey(@NonNull KeyProps keyProps) one, and define key with specific options.

// Create store with specific name and password Store store = new Store(context, STORE_NAME, STORE_PASSWORD);
  final String alias = "alias"; final char[] password = "password".toCharArray();
 final int keysize = 512;  final Calendar start = Calendar.getInstance();
 final Calendar end = Calendar.getInstance();
 end.add(Calendar.YEAR, 1);
  // Create a key store params, some of them are specific per platform // Check KeyProps doc for more info KeyProps keyProps = new KeyProps.Builder()
 .setAlias(alias)
 .setPassword(password)
 .setKeySize(keysize)
 .setKeyType("RSA")
 .setSerialNumber(BigInteger.ONE)
 .setSubject(new X500Principal("CN=" + alias + " CA Certificate"))
 .setStartDate(start.getTime())
 .setEndDate(end.getTime())
 .setBlockModes("ECB")
 .setEncryptionPaddings("PKCS1Padding")
 .setSignatureAlgorithm("SHA256WithRSAEncryption")
 .build();
  // Generate KeyPair depending on KeyProps KeyPair keyPair = store.generateAsymmetricKey(keyProps);
  // Encrypt/Dencrypt data using buffer with or without Initialisation Vectors // This additional level of safety is required on 23 API level for // some algorithms. Specify encryption/decryption block size to use buffer for // large data when using block based algorithms (such as RSA)  final int encryptionBlockSize = keysize / 8 - 11; // as specified for RSA/ECB/PKCS1Padding keys final int decryptionBlockSize = keysize / 8; // as specified for RSA/ECB/PKCS1Padding keys  Crypto crypto = new Crypto("RSA/ECB/PKCS1Padding", encryptionBlockSize, decryptionBlockSize);
  String text = "Sample text"; String encryptedData = crypto.encrypt(text, key, false);
 String decryptedData = crypto.decrypt(encryptedData, key, false);

Download

Add dependency to your app build.gradle file:

compile 'com.yakivmospan:scytale:1.0.1'

Minimum supported API version is 8.

License

Copyright 2016 Yakiv Mospan  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. 

Resources

Android library to crop images by moving & scaling image.

Utility library of concurrent execution strategies for JVM and Android.

  • Inspired by async for JavaScript and Node.js.
  • Execute collection iterators and control flow strategies concurrently in the background.
  • Callbacks are notified when strategies are complete, cancelled, or error out.
  • Android extensions execute final callbacks on the UI thread.

This library extends RecyclerView + Recycler Adapter.

Epoxy is an Android library for building complex screens in a RecyclerView. It abstracts the boilerplate of view holders, item types, item ids, span counts, and more, in order to simplify building screens with multiple view types. Additionally, Epoxy adds support for saving view state and automatic diffing of item changes.

Tiger - the fastest java dependency injection framework.

A SharedPreferences wrapper for Android that encrypts the content with 256 bit AES encryption. The Encryption key is securely stored in device's KeyStore. You can also use the EncryptionManager to encrypt/decrypt data out of the box.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes