加密解密

 共四种:

1.base64(大小写英文字母、10个基本阿拉伯数字、+、/)

2.MD5(任意长度的数据,算出的MD5值长度都是固定的,哪怕只修改1个字节,所得到的MD5值都有很大区别)

3.对称密钥加密(加密解密的密钥一样)

4.非对称加密(加密解密的密钥不一样,分为公钥和私钥)

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
        final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                switch (item.getItemId()) {
                    case R.id.base64:
//                        fragment = new Base64Fragment();
                        transaction.replace(R.id.content, new Base64Fragment());
                        break;
                    case R.id.md5:
                        transaction.replace(R.id.content, new MD5Fragment());
                        break;
                    case R.id.des:
                        transaction.replace(R.id.content, new DESFragment());
                        break;
                    case R.id.rsa:
                        transaction.replace(R.id.content, new RSAFragment());
                        break;
                }
//                transaction.replace(R.id.content, fragment).commit();
                transaction.commit();
                drawerLayout.closeDrawer(Gravity.LEFT);
                return true;
            }
        });
    }
}

Base64加密解密

public class Base64Fragment extends Fragment {
    @Bind(R.id.encode_et)
    EditText encodeEt;
    @Bind(R.id.decode_et)
    EditText decodeEt;
    @Bind(R.id.result)
    TextView result;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.base64_layout,null);
        ButterKnife.bind(this, view);
        return view;
    }

    @OnClick(R.id.encode)
    public void encode() {
        String srcStr = encodeEt.getText().toString();
        //编码
        String s = Base64.encodeToString(srcStr.getBytes(), Base64.DEFAULT);
        decodeEt.setText(s);
    }

    @OnClick(R.id.decode)
    public void decode() {
        String srcStr = decodeEt.getText().toString();
        byte[] decode = Base64.decode(srcStr.getBytes(), Base64.DEFAULT);
        String s = new String(decode, 0, decode.length);
        result.setText(s);
    }
}

MD5加密解密

public class MD5Fragment extends Fragment {
    @Bind(R.id.encode_et)
    EditText encodeEt;
    @Bind(R.id.result)
    TextView result;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.md5_layout, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @OnClick(R.id.encode)
    public void encode() {
        try {
            //获取一个消息摘要生成实例
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] digest = messageDigest.digest(encodeEt.getText().toString().getBytes());
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : digest) {
                //使用十六进制输出消息摘要,不足两位的用0补齐
                stringBuffer.append(String.format("%02x", b));
            }
            result.setText(stringBuffer.toString());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}

对称密钥加密

public class DESFragment extends Fragment {
    @Bind(R.id.encode_et)
    EditText encodeEt;
    @Bind(R.id.decode_et)
    EditText decodeEt;
    @Bind(R.id.encode_et2)
    EditText encodeEt2;
    @Bind(R.id.decode_et2)
    EditText decodeEt2;
    @Bind(R.id.encode_et3)
    EditText encodeEt3;
    @Bind(R.id.decode_et3)
    EditText decodeEt3;
    @Bind(R.id.result)
    TextView result;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.des_layout, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @OnClick(R.id.encode)
    public void encode() {
        String des = EncryptionHelper.des(encodeEt.getText().toString(), "789", EncryptionHelper.ENCODE);
        decodeEt.setText(des);
    }

    @OnClick(R.id.decode)
    public void decode() {
        String des = EncryptionHelper.des(decodeEt.getText().toString(), "789", EncryptionHelper.DECODE);
        result.setText(des);
    }

    @OnClick(R.id.encode2)
    public void encode2() {
        String s = EncryptionHelper.des3(encodeEt2.getText().toString(), "123", EncryptionHelper.ENCODE);
        decodeEt2.setText(s);
    }

    @OnClick(R.id.decode2)
    public void decode2() {
        String s = EncryptionHelper.des3(decodeEt2.getText().toString(), "123", EncryptionHelper.DECODE);
        result.setText(s);
    }

    @OnClick(R.id.encode3)
    public void encode3() {
        String s = EncryptionHelper.aes(encodeEt3.getText().toString(), "abcd", EncryptionHelper.ENCODE);
        decodeEt3.setText(s);
    }

    @OnClick(R.id.decode3)
    public void decode3() {
        String abcd = EncryptionHelper.aes(decodeEt3.getText().toString(), "abcd", EncryptionHelper.DECODE);
        result.setText(abcd);
    }
}
public class EncryptionHelper {
    public static final int ENCODE = 0;
    public static final int DECODE = 1;

    /**
     * 使用DES算法进行对称加/解密
     *
     * @param srcStr 明文
     * @param key    密钥
     * @param mode   模式(加密/解密)
     * @return
     */
    public static String des(String srcStr, String key, int mode) {
        String charsetName = "UTF-8";
        try {
            //获得key的byte数组
            byte[] keyBytes = key.getBytes(charsetName);
            //des算法中key的长度为8
            byte[] temp = new byte[8];
            //数组拷贝
            //1.源数组
            //2.开始复制的位置
            //3.目标数组
            //4.目标数组的位置
            //5.复制的长度
            System.arraycopy(keyBytes, 0, temp, 0, Math.min(keyBytes.length, temp.length));
            //生成密钥
            //1.密钥数组
            //2.生成密钥的算法名称
            SecretKey secretKey = new SecretKeySpec(temp, "des");
            //获取一个密文生成器
            Cipher cipher = Cipher.getInstance("des");
            //如果要进行加密
            if (mode == ENCODE) {
                //初始化密文生成器
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                //执行加密
                byte[] bytes = cipher.doFinal(srcStr.getBytes(charsetName));
                //使用Base64对加密结果进行编码
                String s = Base64.encodeToString(bytes, Base64.DEFAULT);
                return s;
                //如果要解密
            } else {
                //初始化密文生成器
                cipher.init(Cipher.DECRYPT_MODE, secretKey);
                //由于传进来的srcStr是对密文进行加密后的字符串,所以在解密之前先要解码
                byte[] bytes = cipher.doFinal(Base64.decode(srcStr, Base64.DEFAULT));
                //返回明文
                return new String(bytes, 0, bytes.length);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String des3(String srcStr, String key, int mode) {
        String charsetName = "UTF-8";
        try {
            byte[] keyBytes = key.getBytes(charsetName);
            //注意和des算法key的长度不同
            byte[] temp = new byte[24];
            System.arraycopy(keyBytes, 0, temp, 0, Math.min(keyBytes.length, temp.length));
            SecretKey secretKey = new SecretKeySpec(temp, "desede");
            Cipher cipher = Cipher.getInstance("desede");
            if (mode == ENCODE) {
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                byte[] bytes = cipher.doFinal(srcStr.getBytes(charsetName));
                return Base64.encodeToString(bytes, Base64.DEFAULT);
            } else {
                cipher.init(Cipher.DECRYPT_MODE, secretKey);
                byte[] bytes = cipher.doFinal(Base64.decode(srcStr, Base64.DEFAULT));
                return new String(bytes, 0, bytes.length);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String aes(String srcStr, String key, int mode) {
        String charsetName = "UTF-8";
        try {
            byte[] keyBytes = key.getBytes(charsetName);
            byte[] temp = new byte[32];
            System.arraycopy(keyBytes, 0, temp, 0, Math.min(keyBytes.length, temp.length));
            SecretKey secretKey = new SecretKeySpec(temp, "aes");
            Cipher cipher = Cipher.getInstance("aes");
            if (mode == ENCODE) {
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                byte[] bytes = cipher.doFinal(srcStr.getBytes(charsetName));
                return Base64.encodeToString(bytes, Base64.DEFAULT);
            } else {
                cipher.init(Cipher.DECRYPT_MODE, secretKey);
                byte[] bytes = cipher.doFinal(Base64.decode(srcStr, Base64.DEFAULT));
                return new String(bytes, 0, bytes.length);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }
}

非对称密钥加密

public class RSAFragment extends Fragment {
    //两个大素数的乘积
    private static final String MODULUS = "100631058000714094813874361191853577129731636346684218206605779824931626830750623070803100189781211343851763275329364056640619755337779928985272486091431384128027213365372009648233171894708338213168824861061809490615593530405056055952622249066180336803996949444124622212096805545953751253607916170340397933039";
    //公钥
    private static final String PUB_KEY = "65537";
    //私钥
    private static final String PRI_KEY = "26900155715313643087786516528374548998821559381075740707715132776187148793016466508650068087107695523642202737697714709374658856733792614490943874205956727606674634563665154616758939576547663715234643273055658829482813503959459653708062875625210008961239643775661357655599312857249418610810177817213648575161";

    @Bind(R.id.encode_et)
    EditText encodeEt;
    @Bind(R.id.decode_et)
    EditText decodeEt;
    @Bind(R.id.result)
    TextView result;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.rsa_layout, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @OnClick(R.id.encode)
    public void encode() {
        String srcStr = encodeEt.getText().toString();
        try {
            //获取一个公钥/私钥生成工厂
            KeyFactory keyFactory = KeyFactory.getInstance("rsa");
            //1.大素数的乘积
            //2.公钥
            RSAPublicKeySpec rsaPublicKey = new RSAPublicKeySpec(new BigInteger(MODULUS), new BigInteger(PUB_KEY));
            //生成公钥
            PublicKey publicKey = keyFactory.generatePublic(rsaPublicKey);
            //获取一个密码生成器
            Cipher cipher = Cipher.getInstance("rsa");
            //初始化密码生成器
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            //加密
            byte[] bytes = cipher.doFinal(srcStr.getBytes("UTF-8"));
            String s = Base64.encodeToString(bytes, Base64.DEFAULT);
            decodeEt.setText(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.decode)
    public void decode() {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("rsa");
            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(new BigInteger(MODULUS), new BigInteger(PRI_KEY));
            PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);
            Cipher cipher = Cipher.getInstance("rsa");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] bytes = cipher.doFinal(Base64.decode(decodeEt.getText().toString(), Base64.DEFAULT));
            String s = new String(bytes, 0, bytes.length);
            result.setText(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
    }
}

 

原文地址:https://www.cnblogs.com/anni-qianqian/p/5484624.html