您的位置:首页 > 编程语言 > Java开发

Java(JDK)的加密技术

2015-10-06 00:01 801 查看
Java常规的加密方式无非:非对称加密和对称加密

非对称加密

MD5,SHA,RSA等加密方式


对称加密

DES,DES3等加密方式


文件加密

Hash散列值


其它加密方式:例如 DSA(公钥-私钥-验证型加密技术),较为复杂。不在叙述。

MD5加密

package util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5_Encrypt_Util {

/**
* MD5单向加密(非对称加密).
*  作用:让大容量信息在用数字签名软件签署私人密钥前被"压缩"成一种保密的格式
* (就是把一个任意长度的字节串变换成一定长的十六进制数字串)。
* @author 张相逢的博客
* */
public byte[] eccrypt(String info) throws NoSuchAlgorithmException{
/**
* MessageDigest类用于为应用程序提供信息摘要算法的功能,
* 如 MD5 或 SHA 算法。简单点说就是用于生成散列码。
* 信息摘要是安全的单向哈希函数,它接收任意大小的数据,输出固定长度的哈希值
* 根据MD5算法生成MessageDigest对象
*
* @author 张相逢的博客
* */
MessageDigest md5 = MessageDigest.getInstance("MD5");
//将需要加密的字符串更换成数组形式
byte[] srcBytes = info.getBytes();
//使用srcBytes更新摘要
md5.update(srcBytes);
//完成哈希计算,得到result加密后的对象
byte[] resultBytes = md5.digest();
return resultBytes;
}

/**
* 测试
* @author 张相逢的博客
* */
public static void main(String args[]) throws NoSuchAlgorithmException{
String msg = "张相逢的博客";
MD5_Encrypt_Util md5 = new MD5_Encrypt_Util();
byte[] resultBytes = md5.eccrypt(msg);
System.out.println("密文是:" + new String(resultBytes));
System.out.println("明文是:" + msg);
}

}


SHA加密

package util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* 非对称加密 ---单向加密
* SHA 是一种数据加密算法,该算法经过加密专家多年来的发展和改进已日益完善,
* 现在已成为公认的最安全的散列算法之一,并被广泛使用。该算法的思想是接收一段明文,
* 然后以一种不可逆的方式将它转换成一段(通常更小)密文,
* 也可以简单的理解为取一串输入码(称为预映射或信息),并把它们转化为长度较短、
* 位数固定的输出序列即散列值(也称为信息摘要或信息认证代码)的过程。
* 散列函数值可以说时对明文的一种“指纹”或是“摘要”
* 所以对散列值的数字签名就可以视为对此明文的数字签名
*
* @author 张相逢
* */
public class SHA_Encrypt_Util {

/**
* @param info  要加密的字符串
* */
public byte[] eccrypt(String info) throws NoSuchAlgorithmException{
MessageDigest md5 = MessageDigest.getInstance("SHA");
byte[] srcBytes = info.getBytes();
//使用srcBytes更新摘要
md5.update(srcBytes);
//完成哈希计算,得到result
byte[] resultBytes = md5.digest();
return resultBytes;
}

/**
* 测试
*/
public static void main(String[] args) throws NoSuchAlgorithmException {
String msg = "张相逢的博客";
SHA_Encrypt_Util sha = new SHA_Encrypt_Util();
byte[] resultBytes = sha.eccrypt(msg);
System.out.println("明文是:" + msg);
System.out.println("密文是:" + new String(resultBytes));
}

}


RSA加密

package util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;

/**
* 非对称加密
*
* RSA 公钥加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的。
* RSA取名来自开发他们三者的名字。RSA是目前最有影响力的公钥加密算法,
* 它能够抵抗到目前为止已知的所有密码攻击,已被ISO推荐为公钥数据加密标准。
* RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困难,
* 因此可以将乘积公开作为加密密钥。
*
* 其原理就是:用公钥加密 用私钥加密
* @author 张相逢的博客
* */
public class RSA_Encrypt_Util {
//Cipher负责完成加密或解密工作,基于RSA
private Cipher cipher;
//KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
private KeyPairGenerator keyPairGen;
//生成一个密钥对,保存在keyPair中
private KeyPair keyPair;
//得到私钥
private RSAPrivateKey privateKey ;
//得到公钥
private RSAPublicKey publicKey ;

public RSA_Encrypt_Util() throws Exception{
cipher= cipher = Cipher.getInstance("RSA");
//创建密钥生成器
keyPairGen = KeyPairGenerator.getInstance("RSA");
//初始化密钥对生成器,密钥大小为1024位
keyPairGen.initialize(1024);
keyPair=keyPairGen.generateKeyPair();
privateKey=(RSAPrivateKey)keyPair.getPrivate();
publicKey = (RSAPublicKey)keyPair.getPublic();
}

/**
* 加密
* @param srcBytes  需要加密的字符串
*/
protected byte[] encrypt(byte[] srcBytes) throws Exception{
//根据公钥,对Cipher对象进行初始化
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] resultBytes = cipher.doFinal(srcBytes);
return resultBytes;
}

/**
* 解密
* @param privateKey  需要加密的字符串
*/
protected byte[] decrypt(byte[] srcBytes) throws Exception{
if(privateKey!=null){
//Cipher负责完成加密或解密工作,基于RSA
Cipher cipher = Cipher.getInstance("RSA");
//根据公钥,对Cipher对象进行初始化
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] resultBytes = cipher.doFinal(srcBytes);
return resultBytes;
}
return null;
}

/**
* 测试
*/
public static void main(String[] args) throws Exception{
RSA_Encrypt_Util rsa = new RSA_Encrypt_Util();
String msg = "张相逢的博客";
//用公钥加密
byte[] srcBytes = msg.getBytes();
byte[] resultBytes = rsa.encrypt(srcBytes);
//用私钥解密
byte[] decBytes = rsa.decrypt(resultBytes);
System.out.println("明文是:" + msg);
System.out.println("加密后是:" + new String(resultBytes));
System.out.println("解密后是:" + new String(decBytes));
}

}


DES加密(对称加密)

package util;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

/**
* 对称加密DES
*
* DES算法为密码体制中的对称密码体制,又被成为美国数据加密标准,
* 是1972年美国IBM公司研制的对称密码体制加密算法。
*  明文按64位进行分组, 密钥长64位,
*  密钥事实上是56位参与DES运算(第8、16、24、32、40、48、56、64位是校验位,
*   使得每个密钥都有奇数个1)分组后的明文组和56位的密钥按位替代或交换的方法形成密文组的加密方法。
*
*   @author 张相逢的博客
* */

public class DES_Encrypt_Util {

//KeyGenerator 提供对称密钥生成器的功能,支持各种算法
private KeyGenerator keygen;
//SecretKey 负责保存对称密钥
private SecretKey deskey;
//Cipher负责完成加密或解密工作
private Cipher c;
//该字节数组负责保存加密的结果
private byte[] cipherByte;

public DES_Encrypt_Util() throws NoSuchAlgorithmException, NoSuchPaddingException{
Security.addProvider(new com.sun.crypto.provider.SunJCE());
//实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
keygen = KeyGenerator.getInstance("DES");
//生成密钥
deskey = keygen.generateKey();
//生成Cipher对象,指定其支持的DES算法
c = Cipher.getInstance("DES");
}

/**
* 对字符串加密
* @param str 需要加密的字符串
*/
public byte[] Encrytor(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
c.init(Cipher.ENCRYPT_MODE, deskey);
byte[] src = str.getBytes();
// 加密,结果保存进cipherByte
cipherByte = c.doFinal(src);
return cipherByte;
}

/**
* 对字符串解密
*
* @param buff 需要加密的字符串
*/
public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示解密模式
c.init(Cipher.DECRYPT_MODE, deskey);
cipherByte = c.doFinal(buff);
return cipherByte;
}

/**
* 测试
*/
public static void main(String[] args) throws Exception {
DES_Encrypt_Util DES = new DES_Encrypt_Util();
String msg ="张相逢的博客";
byte[] encontent = DES.Encrytor(msg);//加密
byte[] decontent = DES.Decryptor(encontent);//解密
System.out.println("明文是:" + msg);
System.out.println("加密后:【" + new String(encontent)+"】");
System.out.println("解密后:" + new String(decontent));
}

}


DES3加密(对称加密)

package util;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

/**
* 对称加密
*
* 3DES又称Triple DES,是DES加密算法的一种模式,它使用3条56位的密钥对3DES
* 数据进行三次加密。数据加密标准(DES)是美国的一种由来已久的加密标准,它使用对称密钥加密法,
*  并于1981年被ANSI组织规范为ANSI X.3.92。DES使用56位密钥和密码块的方法,而在密码块的方法中,
*  文本被分成64位大小的文本块然后再进行加密。比起最初的DES,3DES更为安全。
*
*   其具体实现如下:
*   设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的密钥,P代表明文,C代表密文,
*  这样,   
*  3DES加密过程为:C=Ek3(Dk2(Ek1(P)))
*  3DES解密过程为:P=Dk1((EK2(Dk3(C)))
*
* @author 张相逢的博客
* */
public class DES3_Encrypt_Util {

// KeyGenerator 提供对称密钥生成器的功能,支持各种算法
private KeyGenerator keygen;
// SecretKey 负责保存对称密钥
private SecretKey deskey;
// Cipher负责完成加密或解密工作
private Cipher c;
// 该字节数组负责保存加密的结果
private byte[] cipherByte;

public DES3_Encrypt_Util() throws NoSuchAlgorithmException, NoSuchPaddingException {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// 实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
keygen = KeyGenerator.getInstance("DESede");
// 生成密钥
deskey = keygen.generateKey();
// 生成Cipher对象,指定其支持的DES算法
c = Cipher.getInstance("DESede");
}

/**
* 对字符串加密
*
* @param str 需要加密的字符串
*/
public byte[] Encrytor(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
c.init(Cipher.ENCRYPT_MODE, deskey);
byte[] src = str.getBytes();
// 加密,结果保存进cipherByte
cipherByte = c.doFinal(src);
return cipherByte;
}

/**
* 对字符串解密
* @param buff 需要解密的字符串
*/
public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式
c.init(Cipher.DECRYPT_MODE, deskey);
cipherByte = c.doFinal(buff);
return cipherByte;
}

/**
* 测试
*/
public static void main(String[] args) throws Exception {
DES3_Encrypt_Util des = new DES3_Encrypt_Util();
String msg ="张相逢的博客";
byte[] encontent = des.Encrytor(msg);
byte[] decontent = des.Decryptor(encontent);
System.out.println("明文是:" + msg);
System.out.println("加密后:" + new String(encontent));
System.out.println("解密后:" + new String(decontent));

}

}


hash文件散列值加密

作用:可用于识别文件是否重复上传(同一个文件的hash散列值是相同的,不会因为修改了名字散列值而变化。)。我测试的文件,前两个文件内容一样,文件名字以及拓展名都不一样,最后一个文件和前两个文件内容一样。用于观察变化!!!


package util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

/**
* 非对称加密
*
* 对于文件的哈希算法加密
*
* 作用:可用此检测两个文件是否是同一个文件
* 对现有文件加密访问,可检测文件是否重复上传
* @author 张相逢的博客
* */
public class HashFile_Encrypt_Util {

public static final char[] hexChar = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static final String[] hashTypes = new String[] { "MD2", "MD5", "SHA1", "SHA-256", "SHA-384", "SHA-512" };

public void MD5File(String fileName) throws Exception{
//String fileName = args[0];
System.out.println("需要获取hash的文件为: " + fileName);
List<MessageDigest> mds = new ArrayList<MessageDigest>();
for (String hashType : hashTypes) {
MessageDigest md = MessageDigest.getInstance(hashType);
mds.add(md);
}
InputStream fis = null;
try {
fis = new FileInputStream(fileName);
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
for (MessageDigest md : mds) {
md.update(buffer, 0, numRead);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
for (MessageDigest md : mds) {
System.out.println(md.getAlgorithm() + " == " + toHexString(md.digest()));
}
}

public static void main(String[] args) throws Exception {
String[] fileName = new String[] {"E:/test1.exe","E:/test2.ini","E:/test3.ini"};
HashFile_Encrypt_Util files  = new HashFile_Encrypt_Util();
for(int i=0;i<fileName.length;i++){
files.MD5File(fileName[i]);
}

}

public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
sb.append(hexChar[b[i] & 0x0f]);
}
return sb.toString();
}

}


给大家分享下我的测试类吧以及coder的jar包。点击下载即可

我的测试类以及jar文件 密码【pec9】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: