常见编码加密解密Base64,URL ,GZIP,DES,RSA等

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/muziby/article/details/79650440

常见编码加密解密的基础用法

  • Base64编码
  • URL编码
  • GZIP
  • AES加密
  • DES加密
  • RSA加密

    public class MainActivity extends AppCompatActivity {
    
    private EditText mTextContent;
    private TextView mTxtResult;
    private TextView mTxtPass;
    private byte [] mDecode;
    private byte [] mPriDecode;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextContent = (EditText) findViewById (R.id.txt_content);
        mTxtResult = (TextView) findViewById (R.id.txt_result);
        mTxtPass = (TextView) findViewById (R.id.txt_password);
    } 
    

    编码

        public void btnBase64Encode(View view) {
            String str = mTextContent.getText().toString().trim();
            // Base64编码 no_wrap 代表编码的结果没有任何换行
            String encoded = Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
            mTxtResult.setText(encoded);
    
            //Base64 解码,
            byte[] decode = Base64.decode(encoded, Base64.NO_WRAP);
            String ss = new String(decode);
            Log.d("Base64 ", "ss = " + ss);
        }
    
        public void btnURLEncode(View view) {
            String str = "%E5%8F%98%E5%BD%A2%E9%87%91%E5%88%9A";
            try {
                String decode = URLDecoder.decode(str, "utf-8");
                Log.d("UE", "URLENCODING: " + decode);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
    
            //URLEncoder
            try {
                String encode = URLEncoder.encode("BY帅", "utf-8");
                Log.d("UE", "URLENCODING: edncode: " + encode);
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * GZIP压缩,解压缩
         *
         * @param view
         */
        public void btnGzipTest(View view) {
            String str = mTextContent.getText().toString().trim();
            // 1.压缩GZIP,GZIPOutPutStream
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            try {
                GZIPOutputStream gzipout = new GZIPOutputStream(bout);
                gzipout.write(str.getBytes());//利用GZIPOutPutStream压缩,并输出结果
                gzipout.finish();//必须调用生成实际的压缩数据
                gzipout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            byte[] bytes = bout.toByteArray();
            mTxtResult.setText("内容长度:" + str.length() + "\n压缩大小:" + bytes.length);
    
            String s = Arrays.toString(bytes);
            Log.d("GZIP", s);
    
            //解压缩 GZIPInputStream
            ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
            try {
                GZIPInputStream gzipIn = new GZIPInputStream(bin);
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                byte[] buf = new byte[128];
                int len;
                while (true) {
                    len = gzipIn.read(buf);
                    if (len == -1) {
                        break;
                    }
    
                    bo.write(buf, 0, len);
                }
                byte[] bytes1 = bo.toByteArray();
                String s1 = new String(bytes1);
                Log.d("GZIP", s1);
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        public void btnDesTest(View view) {
            //DES TEST
            String str = mTextContent.getText().toString().trim();
            String pwd = mTxtPass.getText().toString().trim();
    
    //        byte[] encrypt = CryptUtil.desEncrypt(str.getBytes(), pwd.getBytes());
            byte[] iv = {23, 12, 3, 2, 4, 5, 7, 3, 4, 3, 34, 66, 6, 7, 93, 12};
            byte[] encrypt = CryptUtil.aesEncryptWithIv(str.getBytes(), pwd.getBytes(), iv);
    
    
            String s = Base64.encodeToString(encrypt, Base64.NO_WRAP);
            mTxtResult.setText(s);
    
            //解密,把Base64还原,并且解密
            byte[] ed = Base64.decode(s, Base64.NO_WRAP);
            byte[] data = CryptUtil.aesDecryptWithIv(ed, pwd.getBytes(), iv);
            String ss = new String(data);
            Log.d("DES", "btnDesTest : " + ss);
    
        }
    
        public void btnRsaTest(View view) {
            String state = Environment.getExternalStorageState();
            File dir = getFilesDir();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                dir = Environment.getExternalStorageDirectory();
            }
    
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Log.d("KEY", "dir : " + dir.getAbsolutePath());
            File target = new File(dir, "secret.txt");
    
            try {
                if (!target.exists()) {
                    // 1.加载或者生成密钥对
                    KeyPair keyPair = CryptUtil.generateRsaKey(1024);
                    // 私钥
                    PrivateKey aPrivate = keyPair.getPrivate();
                    // 公钥
                    PublicKey aPublic = keyPair.getPublic();
    
    
                    // 私钥的数据格式
                    byte[] privEncoded = aPrivate.getEncoded();
                    byte[] pubEncoded = aPublic.getEncoded();
    
    //        String publicstr = aPublic.toString();
    
                    String pubkeyEncode = Base64.encodeToString(pubEncoded, Base64.NO_WRAP);
                    String priKeyEncode = Base64.encodeToString(privEncoded, Base64.NO_WRAP);
    //        Log.d("Key", publicstr);
    
                    //TODO:把公钥,私钥使用BASE64编码,保存到文件中,下一次启动时,需要先加载,没有才创建
    
                    target.createNewFile();
                    BufferedWriter bw = new BufferedWriter(new FileWriter(target, true));
    
                    bw.write(pubkeyEncode);
                    bw.newLine();
                    bw.write(priKeyEncode);
    
                    bw.close();
                    BufferedReader bufferedReader = new BufferedReader(new FileReader(target));
                    String Pub = bufferedReader.readLine();
                    mDecode = Base64.decode(Pub, Base64.NO_WRAP);
                    String Pri = bufferedReader.readLine();
                    mPriDecode = Base64.decode(Pri, Base64.NO_WRAP);
                    bufferedReader.close();
    
    //                FileOutputStream fos = new FileOutputStream(target);
    //                fos.write(pubencode);
    //                fos.close();
                }else if (target.exists()){
                    BufferedReader bufferedReader = new BufferedReader(new FileReader(target));
                    String Pub = bufferedReader.readLine();
                    mDecode = Base64.decode(Pub, Base64.NO_WRAP);
                    String Pri = bufferedReader.readLine();
                    mPriDecode = Base64.decode(Pri, Base64.NO_WRAP);
                    Log.d("key","public: " + Pub);
                    Log.d("key","private: " + Pri);
                    bufferedReader.close();
    
    
                }
            } catch (IOException e) {
                e.printStackTrace();
    
            }
    
    
    
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(mDecode);
            PKCS8EncodedKeySpec pkeySpec = new PKCS8EncodedKeySpec(mPriDecode);
            RSAPrivateKey privateKey = null;
            RSAPublicKey rsap = null;
            KeyFactory keyFactory;
            try {
                keyFactory = KeyFactory.getInstance("RSA");
    
                rsap = (RSAPublicKey) keyFactory.generatePublic(keySpec);
                privateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkeySpec);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeySpecException e) {
                e.printStackTrace();
            }
    
    
            String str = mTextContent.getText().toString().trim();
            byte[] encrypt = CryptUtil.rsaEncrypt(str.getBytes(), rsap);
    
    
            String es = Base64.encodeToString(encrypt, Base64.NO_WRAP);
            mTxtResult.setText(es);
    
            byte[] dd = Base64.decode(es, Base64.NO_WRAP);
            byte[] data = CryptUtil.rsaDecrypt(dd, privateKey);
            String s1 = new String(data);
            Log.d("RSA", "RSACry : " + s1);
    
        }
    }
    

加密工具类

    public class CryptUtil {
        private CryptUtil() {

        }

        /**
         * DES 加密算法
         *
         * @param data 原始数据
         * @param key  密码,必须是8个字节
         * @return byte[] 经过加密之后的内容
         */
        public static byte[] desEncrypt(byte[] data, byte[] key) {
            byte[] ret = null;
            if (data != null && key != null) {
                if (data.length > 0 && key.length == 8) {
                    // 1.使用 Cipher引擎,来初始化加密,并且设置密码
                    try {
                        Cipher cipher = Cipher.getInstance("DES");
                        // 1.1 DESKEYSPEC用于描述 的事的密码
                        DESKeySpec spec = new DESKeySpec(key);
                        // 1.2使用SecretKeyFactory生成Key对象
                        SecretKeyFactory des = SecretKeyFactory.getInstance("DES");
                        SecretKey sk = des.generateSecret(spec);

                        // 1.3初始化Cipper 为加密I操作,并且制定密钥
                        cipher.init(Cipher.ENCRYPT_MODE, sk);

                        // 2.加密数据
                        ret = cipher.doFinal(data);

                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (NoSuchPaddingException e) {
                        e.printStackTrace();
                    } catch (InvalidKeyException e) {
                        e.printStackTrace();
                    } catch (InvalidKeySpecException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    }
                }

            }
            return ret;
        }

        /**
         * DES 解密算法
         *
         * @param data 原始数据
         * @param key  密码,必须是8个字节
         * @return byte[] 经过解密之后的内容
         */
        public static byte[] desDecrypt(byte[] data, byte[] key) {
            byte[] ret = null;
            if (data != null && key != null) {
                if (data.length > 0 && key.length == 8) {
                    // 1.使用 Cipher引擎,来初始化解密,并且设置密码
                    try {
                        Cipher cipher = Cipher.getInstance("DES");
                        // 1.1 DESKEYSPEC用于描述 的事的密码
                        DESKeySpec spec = new DESKeySpec(key);
                        // 1.2使用SecretKeyFactory生成Key对象
                        SecretKeyFactory des = SecretKeyFactory.getInstance("DES");
                        SecretKey sk = des.generateSecret(spec);

                        // 1.3初始化Cipper 为解密操作,并且制定密钥
                        cipher.init(Cipher.DECRYPT_MODE, sk);

                        // 2.解密数据
                        ret = cipher.doFinal(data);

                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (NoSuchPaddingException e) {
                        e.printStackTrace();
                    } catch (InvalidKeyException e) {
                        e.printStackTrace();
                    } catch (InvalidKeySpecException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    }
                }

            }
            return ret;
        }


        ///////////////////////////////////////////////////////////////////////////
        // AES方式
        ///////////////////////////////////////////////////////////////////////////

        public static byte[] aesEncrySimple(byte[] data, byte[] key) {
            byte[] ret = null;
            if (data != null && key != null) {
                if (data.length > 0 && key.length == 16) {
                    // AES 128bit = 16nytes
                    try {
                        Cipher cipher = Cipher.getInstance("AES");
                        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
                        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
                        ret = cipher.doFinal(data);
                    } 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 ret;
        }

        public static byte[] aesDecrySimple(byte[] data, byte[] key) {
            byte[] ret = null;
            if (data != null && key != null) {
                if (data.length > 0 && key.length == 16) {
                    // AES 128bit = 16nytes
                    try {
                        Cipher cipher = Cipher.getInstance("AES");
                        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
                        cipher.init(Cipher.DECRYPT_MODE, keySpec);
                        ret = cipher.doFinal(data);
                    } 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 ret;
        }

        ///////////////////////////////////////////////////////////////////////////
        // AES 方式2 使用两套密码
        ///////////////////////////////////////////////////////////////////////////

        /**
         * 使用两套密码的加密,强度更高
         *
         * @param data   数据
         * @param key    第一个密码
         * @param ivData 第二个密码
         * @return
         */
        public static byte[] aesEncryptWithIv(byte[] data, byte[] key, byte[] ivData) {
            byte[] ret = null;
            if (data != null && key != null && ivData != null) {
                if (data.length > 0 && key.length == 16 && ivData.length == 16) {
                    //使用两套密码的,算法需要写成AES/算法模式/填充模式
                    try {
                        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                        //准备第一套
                        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
                        //准备第二套密码
                        IvParameterSpec iv = new IvParameterSpec(ivData);

                        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
    //                    ret = cipher.doFinal(data);
                        cipher.update(data);
                        ret = cipher.doFinal();

                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (NoSuchPaddingException e) {
                        e.printStackTrace();
                    } catch (InvalidAlgorithmParameterException e) {
                        e.printStackTrace();
                    } catch (InvalidKeyException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    }
                }
            }
            return ret;
        }


        public static byte[] aesDecryptWithIv(byte[] data, byte[] key, byte[] ivData) {
            byte[] ret = null;
            if (data != null && key != null && ivData != null) {
                if (data.length > 0 && key.length == 16 && ivData.length == 16) {
                    //使用两套密码的,算法需要写成AES/算法模式/填充模式
                    try {
                        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                        //准备第一套
                        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
                        //准备第二套密码
                        IvParameterSpec iv = new IvParameterSpec(ivData);

                        cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
    //                    ret = cipher.doFinal(data);
                        cipher.update(data);
                        ret = cipher.doFinal();

                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (NoSuchPaddingException e) {
                        e.printStackTrace();
                    } catch (InvalidAlgorithmParameterException e) {
                        e.printStackTrace();
                    } catch (InvalidKeyException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    }
                }
            }
            return ret;
        }

        ///////////////////////////////////////////////////////////////////////////
        // RSA
        ///////////////////////////////////////////////////////////////////////////

        // 1.生成密钥对, 公钥和私钥

        /**
         * bits  位数必须在 1024 和 2048 之间
         *
         * @param bits
         * @return
         */
        public static KeyPair generateRsaKey(int bits) {
            KeyPair ret = null;
            try {
                KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
                kpg.initialize(bits);
                ret = kpg.generateKeyPair();

            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return ret;
        }


        /**
         *  RSA 加密,使用公钥加密,那么必须使用私钥解密
         *          使用私钥加密,必须使用公钥解密
         *
         * @param data
         * @param key
         * @return
         */
        public static byte[] rsaEncrypt(byte[] data, Key key) {
            byte[] ret = null;
            if (data != null && data.length > 0 && key != null) {
                try {
                    Cipher cipher = Cipher.getInstance("RSA");
                    cipher.init(Cipher.ENCRYPT_MODE, key);
                    ret = cipher.doFinal(data);
                } 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 ret;
        }


        //解密
        public static byte[] rsaDecrypt(byte[] data, Key key) {
            byte[] ret = null;
            if (data != null && data.length > 0 && key != null) {
                try {
                    Cipher cipher = Cipher.getInstance("RSA");
                    cipher.init(Cipher.DECRYPT_MODE, key);
                    ret = cipher.doFinal(data);
                } 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 ret;
        }
    }

猜你喜欢

转载自blog.csdn.net/muziby/article/details/79650440
今日推荐