MCrypt class use simcard serial number as SecretKey

210 views Asked by At

How can I read the Simcard serial number and use the first 16 numbers as a SecretKey

........
     private String SecretKey = "0123456789abcdef";**//Read the Simcard serial number and use the first 16 numbers as a SecretKey**

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

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

           ................

what I'm doing wrong ??

public class MCrypt {

static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
private String deviceid = telephonyManager.getSimSerialNumber();


//private String deviceid = "894310210159403811111456457657845786485458";
private String serial = new String (deviceid.substring(0, 16));
private String iv = ""+serial;//Dummy iv (CHANGE IT!) 8943102101594038
private static IvParameterSpec ivspec;
private static SecretKeySpec keyspec;
private static Cipher cipher;
private static Context context;
private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!)
2

There are 2 answers

5
Jon Goodwin On BEST ANSWER

O.k. now I see your problem. Activity inherit's from Context - so when you are calling getSystemService in your class MCrypt , you are really wanting to call super.getSystemService.

If you want to have a Context available in another class (like MCrypt), you can pass it in as an argument to a method of that class (the constructor, which you already have), and keep a reference to it, etc.
Add Context argument to your constructor in MCrypt:

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

Add the below permission into your Androidmanifest.xml file.

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Then use this:

TelephonyManager telemamanger = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = telemamanger.getSimSerialNumber();

the getSimSerialNumber() function returns a string which contains provider info etc. If you want to get the pure sim serial number you have to get the last 14 digits.

String SecretKey = deviceid.substring(Math.max(0, deviceid.length() - 14));
1
Goran On

Thats my Worked Code

/**
 * Created by Studio on 02/06/2017.
 */

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 {
    TelephonyManager mtelemamanger;
    private static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    private static IvParameterSpec ivspec;
    private static SecretKeySpec keyspec;
    private static Cipher cipher;
    MCrypt(Context con)
        {
            mtelemamanger = (TelephonyManager) con.getSystemService(Context.TELEPHONY_SERVICE);
            String deviceid = mtelemamanger.getSimSerialNumber();
            String iv = deviceid.substring(0, 16);
            ivspec = new IvParameterSpec(iv.getBytes());
            String secretKey = "0123456789abcdef";
            keyspec = new SecretKeySpec(secretKey.getBytes(), "AES");

        try {
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    public byte[] encrypt(String text) throws Exception
    {
        if(text == null || text.length() == 0)
            throw new Exception("Empty string");

        byte[] encrypted;

        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;
    }

    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);
    }


    private 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;
    }
}