Cifrado 3DES en Android

3DES es un algoritmo de cifrado de datos triple, que equivale a aplicar el algoritmo de cifrado DES 3 veces a cada bloque de datos. Debido a que la longitud de la clave del algoritmo DES original es demasiado corta, es fácil que se descifre mediante la fuerza bruta, por lo que el algoritmo 3DES evita que se descifren los datos cifrados aumentando la longitud de la clave.

Este algoritmo es un algoritmo reversible como RSA, que admite el descifrado de cadenas cifradas, siempre que la clave debe ser la misma que el cifrado durante el descifrado.

Del mismo modo, nuestra clase de herramienta de cifrado debería estar en la biblioteca java

Des3Util.java Esta clase está en la biblioteca java
public class Des3Util {
    //定义加密算法DESede,即3DES
    private static final String Algorithm = "DESede";

    /**
     * 加密函数,key为密钥
     * @param key
     * @param raw
     * @return
     */
    public static String encrypt(String key, String raw) {
        try {
            byte[] enBytes = encryptMode(key, raw.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(enBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return raw;
        }
    }

    /**
     * 解密函数,key值必须和加密时的key一致
     * @param key
     * @param enc
     * @return
     */
    public static String decrypt(String key,String enc){
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] enBytes = decoder.decodeBuffer(enc);
            byte[] deBytes = decryptMode(key,enBytes);
            return new String(deBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return enc;
        }
    }

    private static byte[] encryptMode(String key, byte[] src) {
        try {
            SecretKey deskey = new SecretKeySpec(build3Deskey(key), Algorithm);
            Cipher cipher = Cipher.getInstance(Algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, deskey);
            return cipher.doFinal(src);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            return null;
        } catch (BadPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static byte[] decryptMode(String key,byte[] src){
        try {
            SecretKey deskey = new SecretKeySpec(build3Deskey(key),Algorithm);
            Cipher cipher = Cipher.getInstance(Algorithm);
            cipher.init(Cipher.DECRYPT_MODE,deskey);
            return cipher.doFinal(src);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            return null;
        } catch (BadPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据字符串生成密钥24位的字节数组
     *
     * @param keyStr
     * @return
     */
    private static byte[] build3Deskey(String keyStr) {
        try {
            byte[] key = new byte[24];
            byte[] temp = keyStr.getBytes("UTF-8");
            if (key.length > temp.length) {
                System.arraycopy(temp, 0, key, 0, temp.length);
            } else {
                System.arraycopy(temp, 0, key, 0, key.length);
            }
            return key;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp">
    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入文字"/>
    <Button
        android:id="@+id/bt_jiam"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加密"/>
    <Button
        android:id="@+id/bt_jiem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="解密"/>

    <Button
        android:id="@+id/bt_scmyd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="生成密钥对"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private EditText et;
    private Button bt_jiam;
    private Button bt_jiem;
    private Button bt_scmyd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = findViewById(R.id.et);
        bt_jiam = findViewById(R.id.bt_jiam);
        bt_jiem = findViewById(R.id.bt_jiem);
        bt_scmyd = findViewById(R.id.bt_scmyd);
        bt_jiam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //加密
                String keyWord = Des3Util.encrypt("hzh", et.getText().toString());
                et.setText(keyWord);
            }
        });
        bt_jiem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //解密
                try {
                    String content = Des3Util.decrypt("hzh", et.getText().toString().trim());
                    et.setText(content);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        bt_scmyd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }
}

 

Supongo que te gusta

Origin blog.csdn.net/weixin_38322371/article/details/115076446
Recomendado
Clasificación