Проблема расшифровки с использованием AES / CBC в Android - PullRequest
0 голосов
/ 26 декабря 2018

Я работаю над созданием простого приложения, которое шифрует и дешифрует строку с использованием алгоритма AES с CBC, шифрование работает, в то время как дешифрование не работает вообще и дает нулевой результат, когда я использовал для установки текста для текста редактированияв XML, так может кто-нибудь помочь мне, пожалуйста?ниже мой код:

public class MainActivity extends AppCompatActivity {

EditText ptext,ctext,dtext;
Button eButton,dButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     ptext =(EditText)findViewById(R.id.editText);
     ctext =(EditText)findViewById(R.id.editText2);
     dtext =(EditText)findViewById(R.id.editText3);

     eButton = (Button)findViewById(R.id.button);
     dButton = (Button)findViewById(R.id.button2);


    KeyGenerator keyGenerator = null;
    try {
        keyGenerator = KeyGenerator.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    keyGenerator.init(128);

    // Generate Key
     final SecretKey key = keyGenerator.generateKey();

    // Generating IV.
    final byte[] IV = new byte[16];
    SecureRandom random = new SecureRandom();
    random.nextBytes(IV);

     eButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
           String plaintext = ptext.getText().toString();
             byte[] cipherText = new byte[0];

                 cipherText = encrypt(plaintext.getBytes(),key, IV);


                 ctext.setText(Base64.getEncoder().encodeToString(cipherText));



         }
     });

     dButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {

             String ciphertext=ctext.getText().toString();


             byte[]    cipher = ciphertext.getBytes();



               String  decryptedText = decrypt(cipher,key, IV);

               dtext.setText(decryptedText);



         }
     });
}

public static byte[] encrypt (byte[] plaintext,SecretKey key,byte[] IV )
{
    try {
        //Get Cipher Instance
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        //Create SecretKeySpec
        SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

        //Create IvParameterSpec
        IvParameterSpec ivSpec = new IvParameterSpec(IV);

        //Initialize Cipher for ENCRYPT_MODE
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

        //Perform Encryption
        byte[] cipherText = cipher.doFinal(plaintext);


        return cipherText;
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}

public static String decrypt (byte[] cipherText, SecretKey key,byte[] IV)
{
    //Get Cipher Instance
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");


    //Create SecretKeySpec
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    //Create IvParameterSpec
    IvParameterSpec ivSpec = new IvParameterSpec(IV);

    //Initialize Cipher for DECRYPT_MODE
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

    //Perform Decryption
    byte[] decryptedText = cipher.doFinal(cipherText);



    return new String(decryptedText);
    } catch (Exception e) {
        e.printStackTrace();

    }
    return null;
}

}

Ответы [ 2 ]

0 голосов
/ 27 декабря 2018

Вы использовали

Base64.getEncoder().encodeToString(cipherText));

после процесса шифрования, но забудьте расшифровать его перед расшифровкой.

Base64.getDecoder().decode( )

Помните, всегда, что вы сделали, переверните его.

0 голосов
/ 26 декабря 2018

Линия

byte[] cipher = ciphertext.getBytes();

является проблемой.Вы должны использовать Base64.decodeBase64 (encryptedValue) при расшифровке, так как вы используете Base64.getEncoder (). EncodeToString при шифровании.Вы должны сделать это до попытки расшифровки.Вы должны отменить операции в обратном порядке метода шифрования.

...