0

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!)
Goran
  • 7
  • 4
  • Under what circumstances is this going to be used? If this ties down user data, this is potentially a bad idea as users may receive a replacement SIM from their network operator or move to a different network. This would lead to their previous secret key becoming invalid. – Michael Dodd Jan 17 '17 at 17:38
  • The app decryption should only be used with this simcard. If the user logs in via the app the simcard serial number is sent to the database that is already finished. I need only the secret key as a simcard serial number – Goran Jan 17 '17 at 17:43
  • 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. BUT you dont inherit form Context so it won't work. see my updated answer. – Jon Goodwin Jan 20 '17 at 13:29

2 Answers2

0

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));
Jon Goodwin
  • 9,053
  • 5
  • 35
  • 54
  • not work problem is `getSystemService` its marked reed – Goran Jan 20 '17 at 09:27
  • "it does not work" is not useful, post the compile time error. It WILL work, when you get ride of the bugs. Are you calling "new MCrypt(this); " from your Activity ? – Jon Goodwin Jan 20 '17 at 18:05
  • If I try private String deviceid = "894310210159403811111456457657845786485458"; then Encoder works Simcard Serial is 8943102101594038 and i can read the encoded data – Goran Jan 20 '17 at 21:28
  • no Jon i use `MCrypt mcrypt = new MCrypt();` and ` `String timedate = new String( mcrypt.decrypt(job.getString("timedate") ));` – Goran Jan 20 '17 at 21:34
  • I told you to RE USE THE CONSTRUCTOR NOT ADD ANOTHER ONE. Why would I tell you to do change thing and then you dont' use it? – Jon Goodwin Jan 20 '17 at 23:14
0

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;
    }
}
Goran
  • 7
  • 4
  • "Read the Simcard serial number Not work" is not useful to anyone. What is the error ? Show the logcat (error log). I tested my code, it works fine. – Jon Goodwin Jan 20 '17 at 03:49