http://www.cnblogs.com/vwpolo/archive/2012/07/18/2597232.html

Java加密解密字符串

 

旧文重发:http://www.blogjava.net/vwpolo/archive/2009/12/05/304874.html#383365

import java.security.Key;
import java.security.Security; import javax.crypto.Cipher; /**
* DES加密和解密工具,可以对字符串进行加密和解密操作 。
* @author 刘尧兴
* <p>2009-12-5</p>
*/
public class DesUtils { /** 字符串默认键值 */
private static String strDefaultKey = "national"; /** 加密工具 */
private Cipher encryptCipher = null; /** 解密工具 */
private Cipher decryptCipher = null; /**
* 将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;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// 把负数转换为正数
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// 小于0F的数需要在前面补0
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
* 本方法不处理任何异常,所有异常全部抛出
* @author <a href="mailto:leo841001@163.com">LiGuoQing</a>
*/
public static byte[] hexStr2ByteArr(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length; // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
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;
} /**
* 默认构造方法,使用默认密钥
*
* @throws Exception
*/
public DesUtils() throws Exception {
this(strDefaultKey);
} /**
* 指定密钥构造方法
*
* @param strKey
* 指定的密钥
* @throws Exception
*/
public DesUtils(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 arrB
* 需加密的字节数组
* @return 加密后的字节数组
* @throws Exception
*/
public byte[] encrypt(byte[] arrB) throws Exception {
return encryptCipher.doFinal(arrB);
} /**
* 加密字符串
*
* @param strIn
* 需加密的字符串
* @return 加密后的字符串
* @throws Exception
*/
public String encrypt(String strIn) throws Exception {
return byteArr2HexStr(encrypt(strIn.getBytes()));
} /**
* 解密字节数组
*
* @param arrB
* 需解密的字节数组
* @return 解密后的字节数组
* @throws Exception
*/
public byte[] decrypt(byte[] arrB) throws Exception {
return decryptCipher.doFinal(arrB);
} /**
* 解密字符串
*
* @param strIn
* 需解密的字符串
* @return 解密后的字符串
* @throws Exception
*/
public String decrypt(String strIn) throws Exception {
return new String(decrypt(hexStr2ByteArr(strIn)));
} /**
* 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位
*
* @param arrBTmp
* 构成该字符串的字节数组
* @return 生成的密钥
* @throws java.lang.Exception
*/
private Key getKey(byte[] arrBTmp) throws Exception {
// 创建一个空的8位字节数组(默认值为0)
byte[] arrB = new byte[8]; // 将原始字节数组转换为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;
} /**
* main方法 。
* @author 刘尧兴
* @param args
*/
public static void main(String[] args) {
try {
String test = "123456789";
DesUtils des = new DesUtils("leemenz");//自定义密钥
System.out.println("加密前的字符:" + test);
System.out.println("加密后的字符:" + des.encrypt(test));
System.out.println("解密后的字符:" + des.decrypt(des.encrypt(test))); System.out.println("解密后的字符:" + des.decrypt("202cb962ac59075b964b07152d234b70"));
}
catch (Exception e) {
e.printStackTrace();
}
}
}

Java加密解密字符串的更多相关文章

  1. java加密解密

    java加密解密 public class MD5Util { /** * @param args */ public static void main(String[] args) { System ...

  2. password学4——Java 加密解密之消息摘要算法(MD5 SHA MAC)

    Java 加密解密之消息摘要算法(MD5 SHA MAC) 消息摘要 消息摘要(Message Digest)又称为数字摘要(Digital Digest). 它是一个唯一相应一个消息或文本的固定长度 ...

  3. Java加密解密大全

    ChinaSEI系列讲义(By 郭克华)   Java加密解密方法大全                     如果有文字等小错,请多包涵.在不盈利的情况下,欢迎免费传播. 版权所有.郭克华 本讲义经 ...

  4. java加密解密算法位运算

    一.实例说明 本实例通过位运算的异或运算符 “ ^ ” 把字符串与一个指定的值进行异或运算,从而改变每个字符串中字符的值,这样就可以得到一个加密后的字符串.当把加密后的字符串作为程序输入内容,异或运算 ...

  5. ◆JAVA加密解密-3DES

    从数据安全谈起       当你使用网银时,是否担心你的银行卡会被盗用?     当你和朋友用QQ进行聊天时,是否担心你的隐私会被泄露?     作为开发者,编写安全的代码比编写优雅的代码更重要,因为 ...

  6. java加密解密的学习

    注:此文章只是对如何学习java加密解密技术做一个讲解.并不涉及具体的知识介绍,如果有需要请留言,有时间我补冲长.个人觉着学习一个学习方法比学习一个知识点更有价值的多. 首先,对于加密解密知识体系没有 ...

  7. PHP的加密解密字符串函数

    程序中经常使用的PHP加密解密字符串函数 代码如下: /********************************************************************* 函数 ...

  8. php 加密解密字符串

    /********************************************************************* 函数名称:encrypt 函数作用:加密解密字符串 使用方 ...

  9. django删除表重建&修改用户密码&base64加密解密字符串&ps aux参数说明&各种Error例子

    1.django的queryset不支持负索引 AssertionError: Negative indexing is not supported. 2.django向前端JavaScript传递列 ...

随机推荐

  1. Sql Server异常捕获 try catch

    declare @num int begin try end try begin catch select ERROR_LINE() as 错误行数, ERROR_MESSAGE() as 错误消息 ...

  2. Anton and Chess

    Anton and Chess time limit per test 4 seconds memory limit per test 256 megabytes input standard inp ...

  3. Spring Boot 系列教程6-全局异常处理

    @ControllerAdvice源码 package org.springframework.web.bind.annotation; import java.lang.annotation.Ann ...

  4. Swift & OC 混编 浅析

    转载自:http://www.infoq.com/cn/articles/wangyi-cartoon-swift-mixed-practice?utm_campaign=rightbar_v2&am ...

  5. PAT (天梯)L2-004. 这是二叉搜索树吗?

    L2-004. 这是二叉搜索树吗? 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 一棵二叉搜索树可被递归地定义为具有下列性质的 ...

  6. HDU - 2502 Subway

    题目链接:http://poj.org/problem?id=2502 分析: 告诉一些地铁线路,从起点到终点,中途可以步行,可以坐地铁,找一条最短的路 主要是把图建立好,然后直接dijkstra或者 ...

  7. PAT (Advanced Level) 1097. Deduplication on a Linked List (25)

    简单题. #include<cstdio> #include<cstring> #include<cmath> #include<vector> #in ...

  8. ViewPager滑动标签-PagerSlidingTabStrip的使用

    有篇博客写的已经非常详细,所以不再写了.主要在于导入这个Library,导入Library看自己的笔记 博客地址:http://doc.okbase.net/HarryWeasley/archive/ ...

  9. Oracle数据库设计小细节

    1. 如果使用PowerDesigner此类工具,注意将工具的导出的SQL语句中对于表的双引号去掉. 2. 建表和建字段的时候,不同单词之间使用下划线分隔,比如 REC_ID 3. Oracle中数值 ...

  10. h5移动端设计页面

    @京东设计中心 :去年JDC出了不少优秀的武媚娘…不,H5呢,大家都很拼,同时当然也积累了一些经验和教训,今天结合咱们的实战案例,从字体,排版,动效,音效,适配性,想法这几个方面好好聊一聊关于H5的设 ...