GithubHelp home page GithubHelp logo

android-php-encrypt-decrypt's Introduction

Android-PHP-Encrypt-Decrypt

Encrypt / Decrypt Between Android and PHP and vice-versa

HOW TO USE IT (JAVA)

MCrypt mcrypt = new MCrypt();

/* Encrypt */
String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") );

/* Decrypt */
String decrypted = new String( mcrypt.decrypt( encrypted ) );

HOW TO USE IT (PHP)

$mcrypt = new MCrypt();

/* Encrypt */
$encrypted = $mcrypt->encrypt("Text to encrypt");

/* Decrypt */
$decrypted = $mcrypt->decrypt($encrypted);

android-php-encrypt-decrypt's People

Contributors

poul-kg avatar serpro 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

android-php-encrypt-decrypt's Issues

Read Simcard Serial Number and use it as Secret Key

problem with read on Android device, the Simcard Serial Number and use the first 16 Numbers as Secret Key

` import android.content.Context;
import android.telephony.TelephonyManager;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class MCrypt {

Context mContext;
TelephonyManager mtelemamanger;
static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
public String deviceid = mtelemamanger.getSimSerialNumber();
public String iv = new String (deviceid.substring(0, 16));
private static IvParameterSpec ivspec;
private static SecretKeySpec keyspec;
private static Cipher cipher;
private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!)

public MCrypt ()    {
    ivspec = new IvParameterSpec(iv.getBytes());

    keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

    try {
        cipher = Cipher.getInstance("AES/CBC/NoPadding");
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public MCrypt (Context context)//this is a constructor
{
    mContext = context;
    mtelemamanger = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
}

    public byte[] encrypt(String text) throws Exception
{
    if(text == null || text.length() == 0)
        throw new Exception("Empty string");

    byte[] encrypted = null;

    try {
        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

        encrypted = cipher.doFinal(padString(text).getBytes());
    } catch (Exception e)
    {
        throw new Exception("[encrypt] " + e.getMessage());
    }

    return encrypted;
}

public static byte[] decrypt(String code) throws Exception
{
    if(code == null || code.length() == 0)
        throw new Exception("Empty string");

    byte[] decrypted = null;

    try {
        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

        decrypted = cipher.doFinal(hexToBytes(code));
        //Remove trailing zeroes
        if( decrypted.length > 0)
        {
            int trim = 0;
            for( int i = decrypted.length - 1; i >= 0; i-- ) if( decrypted[i] == 0 ) trim++;

            if( trim > 0 )
            {
                byte[] newArray = new byte[decrypted.length - trim];
                System.arraycopy(decrypted, 0, newArray, 0, decrypted.length - trim);
                decrypted = newArray;
            }
        }
    } catch (Exception e)
    {
        throw new Exception("[decrypt] " + e.getMessage());
    }
    return decrypted;
}


public static String bytesToHex(byte[] buf)
{
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i)
    {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}


public static byte[] hexToBytes(String str) {
    if (str==null) {
        return null;
    } else if (str.length() < 2) {
        return null;
    } else {
        int len = str.length() / 2;
        byte[] buffer = new byte[len];
        for (int i=0; i<len; i++) {
            buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
        }
        return buffer;
    }
}



private static String padString(String source)
{
    char paddingChar = 0;
    int size = 16;
    int x = source.length() % size;
    int padLength = size - x;

    for (int i = 0; i < padLength; i++)
    {
        source += paddingChar;
    }

    return source;
}

} `

Is it really needed to have different IVs?

As far as I know (which is very little), the IV is used as a sort of nuance to generate different outputs despite having same content and same password.
Of course I know the password needs to be the same when encrypting/decrypting, but can't the IV be different? Doesn't the fact that both parties need to know the password AND iv make the IV concept redundant making it a sort of second password? Why not use the very same password for example?

Android and PHP both are getting different Encrypted Value.

String---> "qwertyuiopasdfghjklzxcvbnm qwertyuiopasdfghjklzxcvbnm qwertyuiopasdfghjklzxcvbnm"

Android Encrypted Value---> "b8eccae23aa47f2b60f664df5353f337cb942c70c8d8f14d123f9b04d29f1fc8e4295c42ea767562e28262f5d6d16180db4b8666032c375202deb446b659f081c8c9c7d463a4b36f5a7a5fea87b6bb6d8a1a428995f279ce6309794b3531dc09"

Php Encrypted Value--->"b8eccae23aa47f2b60f664df5353f337cb942c70c8d8f14d123f9b04d29f1fc8e4295c42ea767562e28262f5d6d16180db4b8666032c375202deb446b659f081c8c9c7d463a4b36f5a7a5fea87b6bb6d"

The problem is php is not giving the entire value, Please have a look at dark characters in encrypted value.

Note: if my String is small then it works fine. The problem only happens if String length exceeds 64 characters.

Thanks.

Android Live Stream APP

Hello.thanks for code.can u give me any documentation how to integrate this to my Android Live TV Application.which use API from PHP Server to get the streaming links.
Can we encrypt the links with this.

Decrypt file in Android

In php i'm encrypt file
$mcrypt->encrypt(fread($handle, 4096));

how decrypt it's in android?

Json Decryption

java.lang.Exception: [decrypt] Invalid int: "{ "

i am getting this error how to resolve it ?

Problem integrating it on Android

Hi
When i try to do this:

import com.myproject.MCrypt;

MCrypt mcrypt = new MCrypt();
String decrypting = new String(mcrypt.decrypt(myencryptedtext));

Java ask me to add exception:

        MCrypt mcrypt = new MCrypt();
        try {
            String decrypting = new String(mcrypt.decrypt(myencryptedtext));
            Log.w("decrypting", decrypting );
        } catch (Exception e) {

        }

But nothing returned in the LOGS !

Can you help me please ?

doesn work for Video

Hi, I need to use this API, but before use, I just did plain test, where PHP encryption decryption worked for txt, docx etc but when it comes to video, it fails. I also noticed there initial space was erased, trim removes it.

Strange chars

hi,
i still have strange ?? characters in Java when decrypting.

Error when use php 7

hi
when use php version 7 not work and get error {main} thrown in MCrypt.php on line 11

please check this bug

thanks

Objective C equivalent for this.

I want to use this in my PHP server side API and in Android App and iOS app.
Working fine with the above code in PHP and Android.

Now need full code for the iOS equivalent for this. Can anyone have this.. please

Can not encrypt & decrypt JPG file

I want to encrypt and then decrypt .jpg file

Here is the code snippet I use:

$crypter = new MCrypt();
// encrypt
file_put_contents('dst.ejp', $crypter->encrypt(file_get_contents('src.jpg')));
// decrypt
file_put_contents('dst-decrypted.jpg', $crypter->decrypt(file_get_contents('dst.ejp')));

but the final dst-decrypted.jpg is not a valid image file anymore.

Any suggestions? I'm using PHP 5.4.20

Alternative for Ionic 2 Framework

I implemented this method in Android and PHP. But now after creating the same app in Ionic 2 for iOS need to perform the same process in ionic 2 (typescript). Any help would be wonderful.

UMD Research Study

Hi there,
We are researchers from the University of Maryland conducting a study about software code reuse. If you are interested in helping us in this study​ through ​a short interview about this project, please contact us on ​[email protected]​ for more information​. You will be ​compensated for your time.

Special Characters?

Hi, I'm loosing special characters when I encrypt in Android and decrypt in PHP. For example, encrypting "Agresión Agravada" ends up being "AgresiÃ�³n Agravada" when decrypted in PHP. The PHP function does say:
return utf8_encode(trim($decrypted));
but I don't understand why the "ó" is not being decrypted.

Thanks!

PS. I'm also using ZeroBytePadding instead of NoPadding because NoPadding would give me this error: java.lang.Exception: [encrypt] data not block size aligned

Can't encrypt unicode string - Java

Hi,

I have try to use your code to encrypt utf8 string but got an errr: javax.crypto.IllegalBlockSizeException: data not block size aligned.

Could you help to fix, please?

Android MCrypt decode Invalid int

Currently testing encrypt-decrypt functions for Android side.

Plain text is "You should be able to read this, bro."
iv = 483e705e5a7f270f;
secretKey = 53c7a330f1bf93d6;

encrypt output is "j:�Xg֎� �T;�H��ZA�����7�(�yJ1$(�[d�{�$�����ûD"
decrypt gives out an error: java.lang.Exception: [decrypt] Invalid int: "j:"

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.