java 3DES 加密

Wesley13
• 阅读 470

public class DESCode {
private String algorithm = "DESede/CBC/PKCS7Padding";//加密方法/运算模式/填充模式
private String charset = "UTF-8";//编码
private Cipher encCipher;//加密cipher
private Cipher decCipher;//解密cipher
private String encStrKey =null;//密钥
private String encSourceSpliter="$";
private String hashSourceSpliter="_";
private MessageDigest digest;//计算摘要对象
private KeyGenerator keyGene;
public String getKey()
{
return this.keyGene.getKey();
}
public DESCode(KeyGenerator keyGene)throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, DecoderException {
    Security
    .addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//添加jce支持(sun有其默认实现)

    this.keyGene = keyGene;
  
    digest=MessageDigest.getInstance("MD5");
    this.encStrKey = keyGene.getEncKeyStr();
    init();
}
private void init() throws NoSuchAlgorithmException,
     NoSuchPaddingException, InvalidKeyException,
     InvalidAlgorithmParameterException, DecoderException {
    encCipherInit();
    decCipherInit();
}

private void encCipherInit() throws NoSuchAlgorithmException,
     NoSuchPaddingException, InvalidKeyException,
     InvalidAlgorithmParameterException, DecoderException {
    DESedeKeySpec encKey = new DESedeKeySpec(Hex.decodeHex(this.encStrKey
      .toCharArray()));
    SecretKey secrekey = new SecretKeySpec(encKey.getKey(), algorithm);
    this.encCipher = Cipher.getInstance(this.algorithm);
    IvParameterSpec iv = new IvParameterSpec(new byte[] { 1, 2, 3, 4, 5, 6,
      7, 8 });//iv向量(加密解密双方要一致)
    encCipher.init(Cipher.ENCRYPT_MODE, secrekey, iv);//初始化cipher对象
}

private void decCipherInit() throws InvalidKeyException, DecoderException,
     NoSuchAlgorithmException, NoSuchPaddingException,
     InvalidAlgorithmParameterException {
    DESedeKeySpec encKey = new DESedeKeySpec(Hex.decodeHex(this.encStrKey
      .toCharArray()));
    SecretKey secrekey = new SecretKeySpec(encKey.getKey(), algorithm);
    this.decCipher = Cipher.getInstance(this.algorithm);
    IvParameterSpec iv = new IvParameterSpec(new byte[] { 1, 2, 3, 4, 5, 6,
      7, 8 });
    decCipher.init(Cipher.DECRYPT_MODE, secrekey, iv);//初始化cipher对象

}

public String encrypt(String sourceMsg)//加密数据
     throws UnsupportedEncodingException, IllegalBlockSizeException,
     BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, DecoderException {
    if(!this.encStrKey.equals(this.keyGene.getEncKeyStr()))
    {
     this.encStrKey = keyGene.getEncKeyStr();
     init();
    }
    byte[] msg = sourceMsg.getBytes(this.charset);
    byte[] value = this.encCipher.doFinal(msg);
    return new String(Base64.encodeBase64(value));

}

public String decrypt(String msgStr) throws IllegalBlockSizeException,
     BadPaddingException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, DecoderException {//解密数据
    if(!this.encStrKey.equals(this.keyGene.getEncKeyStr()))
    {
     this.encStrKey = keyGene.getEncKeyStr();
     init();
    }
    byte[] temp = Base64.decodeBase64(msgStr);
    byte[] value = this.decCipher.doFinal(temp);
    String result = new String(value, this.charset);
    return URLDecoder.decode(result, this.charset);
}
public String md5EnCode(String src,boolean replace)
{
if(replace)
{
    src=src.replace(this.encSourceSpliter, this.hashSourceSpliter);
}
return Hex.encodeHexString(digest.digest(src.getBytes()));

}
public String urlEncode(String... str) throws UnsupportedEncodingException {
    StringBuilder sb = new StringBuilder();
    for (String s : str) {
     sb.append(URLEncoder.encode(s, this.charset));
     sb.append(this.encSourceSpliter);

    }
    int len = sb.length();
    if (len > 0) {

     sb.delete(len-1, len );
    }
    return sb.toString();

}

public static void main(String[] args) throws Exception {
    DESCode descode = new DESCode(new KeyGenerator());
    MessageDigest dig = MessageDigest.getInstance("MD5");
    String msg1 = "ybcola$"
      + Hex.encodeHexString(dig.digest("pppppppp".getBytes()))
      + "$www.yltch.net";
    String msg2 = descode.urlEncode("ybcola", Hex.encodeHexString(dig
      .digest("pppppppp".getBytes())), "www.yltch.net");
    String msg3 = descode.urlEncode("弟弟", "1000", "7", "根据推广逻辑,增加的奖励",
      "dz_02156356548", "www.yltch.net");
    System.out.println(msg1);
    System.out.println(msg2);
    System.out.println(msg3);
    System.out.println("-------encode------");
    msg1= descode.encrypt(msg1);
    msg2= descode.encrypt(msg2);
    msg3= descode.encrypt(msg3);

    System.out.println(msg1);
    System.out.println(msg2);
    System.out.println(msg3);
    System.out.println("------decode--------");
    // String msg4 =
    // "hOWzn/a38v2idQegaPnBUqJL3jsF9uh8OBSQ+LKoCeXGNkXX2ceCIn14g6FbFF4StrBoOfBH6UPRoHvO/Ftwp3qL4FHf/1+3aCU3K0esqqQ=";
    System.out.println(descode.decrypt(msg1));
    System.out.println(descode.decrypt(msg2));
    System.out.println(descode.decrypt(msg3));
}
}

public class KeyGenerator {
private String key="hongsoft";
private String encKeyStr="9F8C243AEE347183B39DD81B20941E86BC11529B034C8842";
public String getEncKeyStr() {
    return encKeyStr;
}
public void setEncKeyStr(String encKeyStr) {
    this.encKeyStr = encKeyStr;
}
public String getKey() {
    return key;
}
public void setKey(String key) {
    this.key = key;
}

}

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java日期时间API系列31
  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这