0

I am using a microcontroller with NFC so I need to send encrypted data that why I am using AES/CBC/NoPadding while I am working on the android app I am having an issue with encryption and decryption this is the code I am working on

    String message="(*my_Log*y7VRMh5Wau80bRebLh/JaHMru/0Sj05E+lKUvT6d8Rw=*1604137444*19)111111111112";
    textView.setText("before encp:- "+message);
    try {
        String data=encrypt(message,"Thats my Kung Fu");
        Log.d("data after encode:-",data);
        textView.append("\n after encode:- \n"+data);
        String data2=decrypt(data,"Thats my Kung Fu");
        Log.d("data after decode:-",data2);
        textView.append("\n after decode:- \n"+data2);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

@RequiresApi(api = Build.VERSION_CODES.O)
private String decrypt(String data, String key) throws Exception {
    SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher=null;
    byte[] ivBytes = new byte[16];
    cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
    cipher.init(Cipher.DECRYPT_MODE,skey,new IvParameterSpec(ivBytes));
    byte[] decodeval=Base64.getDecoder().decode(data);
    byte[] decval= cipher.doFinal(decodeval);
    return new String(decval);

}

@RequiresApi(api = Build.VERSION_CODES.O)
private String encrypt(String message, String key) throws Exception{
    byte[] encval=null;
    SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE,skey);
    encval=cipher.doFinal(message.getBytes());
    String encryptedValue = Base64.getEncoder().encodeToString(encval);
    return encryptedValue;

}

and this is my log:- D/data after encode:-: zJSEw6H+abZFkwNA/pqpdZUMNFhY0KmZ2lXF23tdAVIm1C5L5oIMagWXG6NRt0UDcIy/xeAeHkEtf32+5WVQ420/TSljaxER7ynJ5+hgFMMo1qJHrWb8tZYUzMIvokUG

D/data after decode:-: �5ts�����U0³u%Wau80bRebLh/JaHMru/0Sj05E+lKUvT6d8Rw=160413744419)111111111112

not complete decode also before encoding string size is 80 after encoding string size is 128 and after decade it's agin 80

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0
@RequiresApi(api = Build.VERSION_CODES.O)
private String encrypt(String message, String key) throws Exception{
    byte[] encval=null;
    SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    byte[] ivBytes = new byte[16];
    cipher.init(Cipher.ENCRYPT_MODE,skey,new IvParameterSpec(ivBytes));   //iv here
    encval=cipher.doFinal(message.getBytes());
    String encryptedValue = Base64.getEncoder().encodeToString(encval);
    return encryptedValue;

}

you have to provide iv in encrypt too