博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
几种加密算法
阅读量:7291 次
发布时间:2019-06-30

本文共 9758 字,大约阅读时间需要 32 分钟。

Base64加密:

1.org.apache.commons.codec,加密后没有换行

package util;import java.io.UnsupportedEncodingException;import org.apache.commons.codec.binary.Base64;/** * @todo Apache的 commons-codec.jar得到的编码字符串是不带换行符的 * @author zhangyanan * @date 2018年8月7日 */public class CommonsCodecEncodeDecode {    /**     * 加密str     *      * @param str     * @return     */    public static String getBase64(String str) {        byte[] b = null;        String s = null;        try {            b = str.getBytes("utf-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        if (b != null) {            s=Base64.encodeBase64String(b);        }        return s;    }        /**     * 解密s     *      * @param str     * @return     */    public static String getFromBase64(String s) {        byte[] b = null;        String result = null;        if (s != null) {            try {                b = Base64.decodeBase64(s);                result = new String(b, "utf-8");            } catch (Exception e) {                e.printStackTrace();            }        }        return result;    }}
View Code

2.sun.misc.BASE64,不推荐使用,加密后有换行回车

package util;import java.io.FileOutputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;/** * @todo BASE64加密解密类 * @author zhangyanan * @date 2018年8月6日 */@SuppressWarnings("restriction")public class EncodeAndDecode {    public static void main(String[] args) {        String base64 = getBase64("http:www.baidu.comasdfsdfcaewfsdcsdfqweafd输入1230.,。");        String fromBase64 = getFromBase64(base64);        System.out.println(base64);        System.out.println();        System.out.println(fromBase64);            }    /**     * 加密str     *      * @param str     * @return     */    public static String getBase64(String str) {        byte[] b = null;        String s = null;        try {            b = str.getBytes("utf-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        if (b != null) {            s = new BASE64Encoder().encode(b);        }        return s;    }        /**     * 解密s     *      * @param str     * @return     */    public static String getFromBase64(String s) {        byte[] b = null;        String result = null;        if (s != null) {            BASE64Decoder decoder = new BASE64Decoder();            try {                b = decoder.decodeBuffer(s);                result = new String(b, "utf-8");            } catch (Exception e) {                e.printStackTrace();            }        }        return result;    }    public static boolean GenerateImage(String base64str, String savepath) { // 对字节数组字符串进行Base64解码并生成图片        if (base64str == null) // 图像数据为空            return false;        // System.out.println("开始解码");        BASE64Decoder decoder = new BASE64Decoder();        try {            // Base64解码            byte[] b = decoder.decodeBuffer(base64str);            // System.out.println("解码完成");            for (int i = 0; i < b.length; ++i) {                if (b[i] < 0) {
// 调整异常数据 b[i] += 256; } } // System.out.println("开始生成图片"); // 生成jpeg图片 OutputStream out = new FileOutputStream(savepath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }}
View Code

3.javax.xml.bind.DatatypeConverter 推荐使用 简洁速度快,没有换行,java1.6开始内置

package util;import javax.xml.bind.DatatypeConverter;/** * @todo * @author zhangyanan * @date 2018年8月7日 */public class DatatypeConverterTest {    public static void main(String[] args){        String s="www.bai注释";        String printBase64Binary = DatatypeConverter.printBase64Binary(s.getBytes());        System.out.println(printBase64Binary);        byte[] parseBase64Binary = DatatypeConverter.parseBase64Binary(printBase64Binary);        System.out.println(new String(parseBase64Binary));        System.out.println("----------");    }}
View Code

4.java.util.Base64 推荐使用,速度最快、简洁,没有换行,但要java1.8环境()

import java.io.UnsupportedEncodingException;import java.util.Base64;/** * @todo java8 java.util.Base64测试 * @author zhangyanan * @date 2018年8月7日 */public class TestBase64 {    public static void main(String[] args) throws UnsupportedEncodingException {        // 编码        String asB64 = Base64.getEncoder().encodeToString("聊聊ss33!%".getBytes("utf-8"));        System.out.println(asB64);// 输出为: c29tZSBzdHJpbmc=        // 解码        byte[] asBytes = Base64.getDecoder().decode(asB64);        System.out.println(new String(asBytes, "utf-8"));// 输出为: some string    }    }
View Code

 

 

20180813:des加密解密

des加密解密算法

import java.security.*;  import javax.crypto.*;    /**  * DES加解密算法  */  public class DES {        private static String strDefaultKey = "abcDEF123";      private Cipher encryptCipher = null;      private Cipher decryptCipher = null;          /**      * 默认构造方法,使用默认密钥      * @throws Exception      */      public DES() throws Exception {          this(strDefaultKey);      }          /**      * 指定密钥构造方法      * @param strKey 指定的密钥      * @throws Exception      */      public DES(String strKey) throws Exception {          Security.addProvider(new com.sun.crypto.provider.SunJCE());          Key key = getKey(strKey.getBytes());          encryptCipher = Cipher.getInstance("DES");          encryptCipher.init(Cipher.ENCRYPT_MODE, key);          decryptCipher = Cipher.getInstance("DES");          decryptCipher.init(Cipher.DECRYPT_MODE, key);      }          /**      * 加密字符串      * @param strIn 需加密的字符串      * @return 加密后的字符串      * @throws Exception      */      public String encrypt(String strIn) throws Exception {          return byteArr2HexStr(encrypt(strIn.getBytes()));      }                  /**      * 加密字节数组      * @param arrB 需加密的字节数组      * @return 加密后的字节数组      * @throws Exception      */      public byte[] encrypt(byte[] arrB) throws Exception {          return encryptCipher.doFinal(arrB);      }                    /**      * 解密字符串      * @param strIn 需解密的字符串      * @return 解密后的字符串      * @throws Exception      */      public String decrypt(String strIn) throws Exception {          return new String(decrypt(hexStr2ByteArr(strIn)));      }                  /**      * 解密字节数组      * @param arrB 需解密的字节数组      * @return 解密后的字节数组      * @throws Exception      */      public byte[] decrypt(byte[] arrB) throws Exception {          return decryptCipher.doFinal(arrB);      }                /**      * 从指定字符串生成密钥,密钥所需的字节数组长度为8位      * 不足8位时后面补0,超出8位只取前8位      * @param arrBTmp 构成该字符串的字节数组      * @return 生成的密钥      * @throws java.lang.Exception      */      private Key getKey(byte[] arrBTmp) throws Exception {          byte[] arrB = new byte[8];          for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {              arrB[i] = arrBTmp[i];          }          Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");          return key;      }                    /**      * 将byte数组转换为表示16进制值的字符串,      * 如:byte[]{8,18}转换为:0813,      * 和public static byte[] hexStr2ByteArr(String strIn)      * 互为可逆的转换过程      * @param arrB 需要转换的byte数组      * @return 转换后的字符串      * @throws Exception 本方法不处理任何异常,所有异常全部抛出      */      public static String byteArr2HexStr(byte[] arrB) throws Exception {          int iLen = arrB.length;          StringBuffer sb = new StringBuffer(iLen * 2);          for (int i = 0; i < iLen; i++) {              int intTmp = arrB[i];              while (intTmp < 0) {                  intTmp = intTmp + 256;              }              if (intTmp < 16) {                  sb.append("0");              }              sb.append(Integer.toString(intTmp, 16));          }          return sb.toString();      }                /**      * 将表示16进制值的字符串转换为byte数组,      * 和public static String byteArr2HexStr(byte[] arrB)      * 互为可逆的转换过程      * @param strIn 需要转换的字符串      * @return 转换后的byte数组      * @throws Exception 本方法不处理任何异常,所有异常全部抛出      */      public static byte[] hexStr2ByteArr(String strIn) throws Exception {          byte[] arrB = strIn.getBytes();          int iLen = arrB.length;          byte[] arrOut = new byte[iLen / 2];          for (int i = 0; i < iLen; i = i + 2) {              String strTmp = new String(arrB, i, 2);              arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);          }          return arrOut;      }      }
View Code

加密解密工具类

/** * 加密解密工具类 */public class EncryUtil {        /**     * 使用默认密钥进行DES加密     */    public static String encrypt(String plainText) {        try {            return new DES().encrypt(plainText);        } catch (Exception e) {            return null;        }    }        /**     * 使用指定密钥进行DES解密     */    public static String encrypt(String plainText, String key) {        try {            return new DES(key).encrypt(plainText);        } catch (Exception e) {            return null;        }    }        /**     * 使用默认密钥进行DES解密     */    public static String decrypt(String plainText) {        try {            return new DES().decrypt(plainText);        } catch (Exception e) {            return null;        }    }        /**     * 使用指定密钥进行DES解密     */    public static String decrypt(String plainText, String key) {        try {            return new DES(key).decrypt(plainText);        } catch (Exception e) {            return null;        }    }        public static void main(String[] args) {        String key="3123_";        String encrypt = encrypt("12345624389pq234@Q*&*(",key);        System.out.println("加密的:"+encrypt);        System.out.println("解密的:"+decrypt(encrypt,key));    }}
View Code

 

转载于:https://www.cnblogs.com/yanan7890/p/9439989.html

你可能感兴趣的文章
Tslib步骤以及出现问题的解决方案【转】
查看>>
angularjs 标签指令
查看>>
给出一个数组A,找出一对 (i, j)使得A[i] <= A[j] (i < j)并且j-i最大
查看>>
曾今的代码系列——获取当天最大流水号存储过程
查看>>
EhCache 分布式缓存/缓存集群
查看>>
Asp.Net MVC 必备插件MVC Route Visualizer(Visual Studio 2012 版)
查看>>
js39---组合模式,查找遍历树
查看>>
Lucene(.net)学习
查看>>
这是传说,必须迷恋它:观察者模式
查看>>
linux自动定时备份web程序和mysql数据库
查看>>
架设Discuz Net版 dnt_3.5.2_sqlserver的经验
查看>>
shell 字符串操作
查看>>
python _、__和__xx__的区别
查看>>
八伟大的工具,Windows用户永远都不想错过
查看>>
《IT项目管理》读书笔记(2)——项目管理的环境和过程
查看>>
全排列算法原理和实现
查看>>
C#开发微信公众平台-就这么简单(附Demo)
查看>>
TCP/IP TCP 传输控制协议
查看>>
JS:2.2,循环控制(JavaScript,for,while,do while,break,continue)高级
查看>>
《CCNP TSHOOT 300-135认证考试指南》——2.5节在传输过程中收集信息
查看>>