Giter VIP home page Giter VIP logo

cross-platform-aes's Introduction

Cross platform 256bit AES encryption / decryption

This project contains the implementation of (iOS Objective C, iOS Swift, Android, Java, Javascript, NodeJS)

Platforms supported

  1. iOS
  2. Android
  3. NodeJS
  4. PHP

Features:

  1. Cross platform support. Encryption-Decryption works across iOS, Android and Node.js.

  2. Automatically RandomIV is added while encryption and remove first randomized blocks while decryption.

  3. Support for Random IV (initialization vector) for encryption and decryption. Randomization is crucial for encryption schemes to achieve semantic security, a property whereby repeated usage of the scheme under the same key does not allow an attacker to infer relationships between segments of the encrypted message.

  4. Support for SHA-256 for hashing the key. Never use plain text as encryption key. Always hash the plain text key and then use for encryption. AES permits the use of 256-bit keys. Breaking a symmetric 256-bit key by brute force requires 2^128 times more computational power than a 128-bit key. A device that could check a billion billion (10^18) AES keys per second would in theory require about 3×10^51 years to exhaust the 256-bit key space.

One of the key objective is to make AES work on all the platforms with simple implementation.

Complex logics such as generating IV and sha256 the key are done within the library.

Simple Approach

All Platforms

Pass in the plainText as String, Pass in the key as String. Both the encrypted and decrypted data are also String. key is converted to 256-bit within the library for Android, iOS and NodeJS

iOS / Swift 3, 4

Add a bridging header. Apple documentation

#import "CryptLib.h"
let plainText = "this is my plain text"
let key = "your key"

let cryptLib = CryptLib()

let cipherText = cryptLib.encryptPlainTextRandomIV(withPlainText: plainText, key: key)
print("cipherText \(cipherText! as String)")

let decryptedString = cryptLib.decryptCipherTextRandomIV(withCipherText: cipherText, key: key)
print("decryptedString \(decryptedString! as String)")

Android

val plainText = "this is my plain text"
val key = "your key"

val cryptLib = CryptLib()

val cipherText = cryptLib.encryptPlainTextWithRandomIV(plainText, key)
println("cipherText $cipherText")

val decryptedString = cryptLib.decryptCipherTextWithRandomIV(cipherText, key)
println("decryptedString $decryptedString")

Javascript / NodeJS / Web

Download the library

npm install @skavinvarnan/cryptlib --save
const plainText = "this is my plain text";
const key = "your key";

const cryptLib = require('@skavinvarnan/cryptlib');

const cipherText = cryptLib.encryptPlainTextWithRandomIV(plainText, key);
console.log('cipherText %s', cipherText);

const decryptedString = cryptLib.decryptCipherTextWithRandomIV(cipherText, key);
console.log('decryptedString %s', decryptedString);

PHP

Download the package

composer require ahsankhatri/cryptolib-php
$string     = 'this is my plain text';
$secretyKey = 'BlVssQKxzAHFAUNZbqvwS+yKw/m';

$encryption = new \MrShan0\CryptoLib\CryptoLib();

$cipher  = $encryption->encryptPlainTextWithRandomIV($string, $secretyKey);
echo 'encryptedString: ' . $cipher . PHP_EOL;

$plainText = $encryption->decryptCipherTextWithRandomIV($cipher, $secretyKey);
echo 'decryptedString: ' . $plainText . PHP_EOL;

Output

encryptedString ___Cipher Text will be generated here___
decryptedString this is my plain text

Few Tests

Here are few cipher texts. Try decrypting with iOS or Android or NodeJS.

Basic Example:

Cipher Text: "GfTE0IK4zk039+042LwPvsTjr0A8LqBDcxDWAc41YmwxNjZVJ3CcuDxWXsulbUjE"
Cipher Text: "53zydKWD3CJCoSm9YBYaV+pwwGtSP/f36nIfUnRV3GwTFsQXgX84nh0Tu6JpsHkf"
Cipher Text: "h0PMUJhigwVnJZD43i9q98b/AG7GUg8T2BdsQ4Yun2dQHPqSE5QF0RSiHUW0wguc"
Cipher Text: "EhYJzR5oaziXCSJ2ha63Oun6HXLkCILWuJWVUAl64JpU3OdvKNyoA3rKuOj+qfEO"

key: "your key"

Output Plain Text: "this is my plain text"

Example special characters:

Cipher Text: "71g9R98ALCvYD0AVCtNJhEik/00jvon+ductEBlt601Er6tqFrtH0kIB+62O2DPiEsKcSilUez2MXsyGzA2Z9KM8h/tiLmM6psaSLaFELXw="
Cipher Text: "f9ofx42+h5SzJI5sXa+NExyCpxXRdhLcYcuvAsX6qCkxEw10GMzYCnSslV5Ku3v5w96QlHVceLn6yBcUBeZHlpbcnKv38ZKCGxTTv95gIN0="
Cipher Text: "CvG+gJuY5mrcjQa5OfGSA39tQtgEK1fj/OMR8Jaw2XmBOGLWJvII6nNfSvhhGLYG31X65wSLTy6Naz/OTrkEA7KOlpM5PYPpjbY06JA7zHg="
Cipher Text: "C7Bc+bSC1cri0DJ6nLoGoslfMPb4nVea0xHla8nQaOilPTpAx5N8ziLZC7UhpdiSnzYqRmh0WiH5u0wJmAn0JEEFqsxhW6z0biFmT6p8x1s="

key: "%^^&&@(*&@##)@)@``~~"

Output Plain Text: "This is a my #&^&*#&^@@# PLAIN (.)(.) TEXT (@*&#(*^---"

Advance Approach

Refer the source code

Thanks to Cross-platform-AES-encryption

cross-platform-aes's People

Contributors

ahsankhatri avatar skavinvarnan 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

cross-platform-aes's Issues

new line char

I am noticing that each encryption ends with a newline char. Is this expected behavior?
Example: "bV4PAwa7zwiLTTsbPH2zHQ==\n"

is Cross-Plafform-AES using CryptoJS?

I would want to know is Cross-PLatffrom-AES is using CryptoJS.
Do you have the library with pure javascript?

Do you have the implementation in a stored procedure for some database?

Velnerabilities: Memory Exposure

This library contained a vulnerability issue when audited by NPM.

Here the details:
Moderate Memory Exposure
Package bl
Patched in >=0.9.5 <1.0.0 || >=1.0.1
Dependency of @skavinvarnan/cryptlib
Path @skavinvarnan/cryptlib > bl
More info https://nodesecurity.io/advisories/596

Please update the dependencies to fix this issue.

DO NOT SUPPORT SMILIES

I'm facing a smiley issue on enc dec. I use it in node js with MySQL. Table schema was BLOB type.

Some chars missing while decrypting in Android side!

While decrypting cypher text in Android using 'decryptCipherTextWithRandomIV', which was received from Php side, shows only a part of actual data or some character is missing. After a few tries randomly get the exact plain text as desired!
The code is mentioned below :

String cipherText = "WelKD2g4ThgJPeRiVz5FCcMoZG9pGCGgSjDlkD2hq3ee1SRPovlia0o9dEBwpLjg";
String key = "1122334455667788";

String decryptedString = cryptLib.decryptCipherTextWithRandomIV(cipherText, key);

Which may produce the plain text with some letters missing sometimes!!!.. Please help out.

Encryption failing for cross-platform use.

I've created a sample project for testing. I encrypt a string with Obj-c and attempt to decrypt it on using Android. I'm able to Decrypt the string on iOS but not Android. Any help would be greatly appreciated... Many thanks I receive a 'bad padding exception'

Obj-C Code:

    NSString *plainText = @"this is my plain text";
    NSString *keyy = @"simplekey";
    NSString *iiv = @"1234123412341234";
   
    NSString *encryptedString = [[CryptLib alloc] encryptPlainText:plainText key:keyy iv:iiv];

Decryption is not working properly

I am using encryptPlainText/decryptCipherText functions for encryption/decryption. Encryption is working fine but decryption gives wrong result.

"#"S7\u{1F}\u{0B}03vB!'+c\n]"Message":"","ErrorNumber":0,"UserInfo":{"UserDetails":[]}"

But I expect a correct JSON.

I tried tried tried many things and at last I figure out the issue. The issue is in your objective c file. In decryptCipherText method we pass iv in argument but you generate random iv.

- (NSString *) decryptCipherText:(NSString *)ciperText key:(NSString *)key iv:(NSString *)iv { return [[NSString alloc] initWithData:[[CryptLib alloc] decrypt:[[NSData alloc] initWithBase64EncodedString:ciperText options:NSDataBase64DecodingIgnoreUnknownCharacters] key:[[CryptLib alloc] sha256:key length:32] iv:[[CryptLib alloc] generateRandomIV16]] encoding:NSUTF8StringEncoding]; }

Please replace the above method with following

- (NSString *) decryptCipherText:(NSString *)ciperText key:(NSString *)key iv:(NSString *)iv { return [[NSString alloc] initWithData:[[CryptLib alloc] decrypt:[[NSData alloc] initWithBase64EncodedString:ciperText options:NSDataBase64DecodingIgnoreUnknownCharacters] key:[[CryptLib alloc] sha256:key length:32] iv:iv] encoding:NSUTF8StringEncoding]; }

IOS Failes to decrypt VB.net String

Dear
first i would like to than you about your great cryptlib

But i'm using it in android and swift

in android i managed to decrypt the string returned from the server successfully
but in IOS it keeps giving me errors or strange output data like :

ÄľIßþÑÔ×Q0•‹z•lz·'ù\u{0E} ¤*]9\u{15}ï!�EF\nëåt<NxýaI\u{1D}‘\u{03}� N3\u{07}½lô·÷=\u{1D}?ì\u{05}ÂòÅ·#Ñèâ\u{05}’=0Ñ<‰á\u{1D}\t\u{1E}!»>k/t\rÄ\u{07}K{-êg&ZÓ?\0o�¸\u{06}ˆ)ŸÝSX7ÜF\u{0F}]€[ïÎX-‰TÌœâ]¿ü.‚\nS\u{19}ÂN3!\u{15}\u{10}К¥ÍQUö„›'Ï~N\u{0E}€‚F;»ª:sÿÒZ°óD:¿\u{19}\u{1A}†ŽvL

here is an example to try to decrypt

IV = 509+QAilldg3dj3p
key string "sha256" = 2c8bc04829771e56a064e192425f0f98
Encrypted text =
LbA/hK1DfsyqvwPKuyvKH90cFh6u6WfUBvFgv7XLtjNB4s++iJFSdLbAAIYLsFwh4HpZLzWMA5VCZTNwPUztvflIdTfyZ99y9B6Il+KHUKWNsgSlw6WgPw9ZGy+3zpZkaYmI8KkJj9hudeiCODxknXIJ26hkfjbAl9BRJg2GHyNKN1or+DR82Gxtfx6srbHS1jV/vItcZEOKRdaWzdRhGZ1HwYOD5cVg6xdt8Gts3dU=

Can you please help me because i'm frustrated and i failed to decode it using all samples in we

this string is returned from VB.net service
Regards

How do I handle the error in node js?

Specially when I decrypt the data if i dont send the encrypted data instead send the plain text, the node js app crashes, how do I prevent it from crashing and send error response? I'm thinking what if the hacker sends plain text and the app crashes and uses this to crash the app again and again, help me with this as I am new to node js

Decryption not working properly for DATA

Hi I have used the following method to encrypt

  • (NSData *)encrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv {
    char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053
    ivPointer[kCCBlockSizeAES128+2];
    BOOL patchNeeded;
    bzero(keyPointer, sizeof(keyPointer)); // fill with zeroes for padding

    patchNeeded= ([key length] > kCCKeySizeAES256+1);
    if(patchNeeded)
    {
    NSLog(@"Key length is longer %lu", (unsigned long)[[self md5:key] length]);
    key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256)
    }

    //NSLog(@"md5 :%@", key);
    [key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];
    [iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];

    if (patchNeeded) {
    keyPointer[0] = '\0'; // Previous iOS version than iOS7 set the first char to '\0' if the key was longer than kCCKeySizeAES256
    }

    NSUInteger dataLength = [plainText length];

    //see https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CCryptorCreateFromData.3cc.html
    // For block ciphers, the output size will always be less than or equal to the input size plus the size of one block.
    size_t buffSize = dataLength + kCCBlockSizeAES128;
    void *buff = malloc(buffSize);

    size_t numBytesEncrypted = 0;
    //refer to http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-36064/CommonCrypto/CommonCryptor.h
    //for details on this function
    //Stateless, one-shot encrypt or decrypt operation.
    CCCryptorStatus status = CCCrypt(kCCEncrypt, /* kCCEncrypt, etc. /
    kCCAlgorithmAES128, /
    kCCAlgorithmAES128, etc. /
    kCCOptionPKCS7Padding, /
    kCCOptionPKCS7Padding, etc. /
    keyPointer, kCCKeySizeAES256, /
    key and its length /
    ivPointer, /
    initialization vector - use random IV everytime /
    [plainText bytes], [plainText length], /
    input /
    buff, buffSize,/
    data RETURNED here */
    &numBytesEncrypted);
    if (status == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];
    }

    free(buff);
    return nil;
    }

And Decrypt it using the following method,

char keyPointer[kCCKeySizeAES256+2],
ivPointer[kCCBlockSizeAES128+2];
BOOL patchNeeded;

patchNeeded = ([key length] > kCCKeySizeAES256+1);
if(patchNeeded)
{
    NSLog(@"Key length is longer %lu", (unsigned long)[[[StringEncryption alloc] md5:key] length]);
    key = [key substringToIndex:kCCKeySizeAES256];
}

[key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];
[iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];

if (patchNeeded) {
    keyPointer[0] = '\0';
}

NSUInteger dataLength = [encryptedText length];

size_t buffSize = dataLength + kCCBlockSizeAES128;

void *buff = malloc(buffSize);

size_t numBytesEncrypted = 0;

CCCryptorStatus status = CCCrypt(kCCDecrypt,
                                 kCCAlgorithmAES128,
                                 kCCOptionPKCS7Padding,
                                 keyPointer, kCCKeySizeAES256,
                                 ivPointer,
                                 [encryptedText bytes], [encryptedText length], //input
                                 buff, buffSize,//output
                                 &numBytesEncrypted);
if (status == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];
}

free(buff);
return nil;

But the decryption is not working. Please help me resolve this issue.

iOS 13 Decryption failure

On iOS 13 devices, Handling decryption with the library's encrypted strings has consistently failed

Key stored in app is not secured

I know its not an issue, but I just wanted to know how can i store the key in android app, if someone tries to reverse engineer the app, they can get the key and easily decrypt the data.

CC_MD5 is deprecated

'CC_MD5' is deprecated: first deprecated in iOS 13.0 - This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).

Need this as a Plugin for flutter

Its a powerful encryption seen to be working working perfectly fine on the Native Application of Android and iOS both ..
Moving to other, we need this for the Flutter too.

Sha256 with 24 length key SWIFT

Hi, I have this snippet of code working with a sha256 with 32 length key

let plainText :String = "this is my plain text"
let key :String = "your key"
let cryptLib = CryptLib()
let iv = "5/LRE3jKOTCav8VB"
let size = 32
let sha = cryptLib.sha256(key, length: size)
let cipherText = cryptLib.encrypt(plainText.data(using: String.Encoding.utf8), key: sha, iv: iv)
print(cipherText!.base64EncodedString())
let elem = cryptLib.decrypt(cipherText, key: sha, iv: iv)
let salida = String.init(data: elem!, encoding: String.Encoding.utf8)
print(salida!)

But when i change size = 24, it fails the decrypt, is there any way to make the decryption it work ?, i am in a proyect that needs a 24 length key.

encryptPlainTextWithRandomIV in Android and decryptCipherTextWithRandomIV in php don't work

Hello, I trying to encrypt test in Android Java and decrypt in php using encryptPlainTextWithRandomIV in Android and decryptCipherTextWithRandomIV in php. But php can't decrypt the crypted text from android. I use the same Key both.

--------------Android code--------------
String AES_CRYPT_KEY = "Awpj5scJh9gdeKBdnpl5df5d8sqPlfNe"; AESEncryption aesEncryption= new AESEncryption(); String text="2019/01/18 20:04:55#QNd7OpVZ4w56Z8VZ8j5HcHk7UdxinD#U_4752256_nsia#1234567890"; Log.d("AES crypt", aesEncryption.encryptPlainTextWithRandomIV(AES_CRYPT_KEY, text));

Android encryption result: jiAfm/9C+whU/EOG4MW52LNnBNQflM5Ajx2qSdncaL++tF2mpLl/oiPTuBwFCceftUAj9UoaEbE9HqYXVgh/ug==
-------------PHP code -----------------

<?php 
 require '../libs/vendor/autoload.php';
$secretyKey = "Awpj5scJh9gdeKBdnpl5df5d8sqPlfNe";
$encryption = new \MrShan0\CryptoLib\CryptoLib();
$crypted="jiAfm/9C+whU/EOG4MW52LNnBNQflM5Ajx2qSdncaL++tF2mpLl/oiPTuBwFCceftUAj9UoaEbE9HqYXVgh/ug==";
$plainText = $encryption->decryptCipherTextWithRandomIV($crypted, $secretyKey);
echo 'Decrypted: ' . $plainText . PHP_EOL;

?>

// OUTPUT is Empty...........
Decrypted:

Help please

Xcode 8.3.2 Swift 3.x, unexpectedly found nil while unwrapping an Optional value

Hi
I tried your code in Xcode 8.3.2 Swift 3.x, It crashes in the line print decryptedString. Please help.

screen shot 2017-05-23 at 9 37 47 am

let plainText = "this is my plain text"
       let key = "simplekey"
       let iv = "1234123412341234"
       
       let cryptoLib = CryptLib();
       
       let encryptedString = cryptoLib.encryptPlainText(with: plainText, key: key, iv: iv)
       print("encryptedString \(encryptedString! as String)")
       
       let decryptedString = cryptoLib.decryptCipherText(with: encryptedString, key: key, iv: iv)
       print("decryptedString \(decryptedString! as String)")

Arabic or Pesrian characters

HI
When I use Arabic or persian letters in encryption، I can not decode ios side
I'm sure the problem is from Arabic or Persian words
Is there a solution to this problem?

thanks so mutch

Cryptlib not working for flutter IOS

Hi
I am getting below error while I am trying to run app on iOS device.
It's working for android properly.

Undefined symbols for architecture x86_64:
"OBJC_CLASS$_CryptlibPlugin", referenced from:
objc-class-ref in GeneratedPluginRegistrant.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

BadPaddingException

Hi!
The problem arises when I try to decrypt a string from the server (using the same library) with a custom iv and key.

Android [Kotlin]

`val cryptLib = CryptLib()
val iv = "iv"
val key = "key"
val cipherText = "7ESDDdYDbnUh2hqGhAKGbEZKpwa14mEiT553b3etgjc="

val resultText = cryptLib.decryptCipherText(cipherText, key, iv)`

The app crash and return this:
javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT

Caused by: javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:602)
at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:365)
at javax.crypto.Cipher.doFinal(Cipher.java:2055)

Thanks for the help.

Decryption is not working with swift IOS

Could you please check the IOS Decryption and Encryption it not working Properly. when I'am trying to decrypt a string which was encrypted on Android platform.
(or could be please remove CrossPlatform from the title..its misleading) Sorry for my Langauge.

String encrypted in iOS does not decrypt in Android

Hey!!
I have used the header as bridging header in iOS, encryption and decryption works fine in ios as well as android. But when I try to encrypt in iOS and Decrypt in Android or vice versa I do not get result.. Any solution ?

Crypt in Objective-c and decrypt in node.js

Hi,
when I try to decrypt in node.js I have this error:
digital envelope routine: EVP_DecryptFinal_ex:wrong final block length.

I'm using the code example.
Regards,
Michele

C# solution also required

This solution is working fine in iOS & Android, but we also need C#.Net, so can anyone provide same with this.

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.