java文件加密解密
packagecom.palic.pss.afcs.worldthrough.common.util;
importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;
importrepack.com.thoughtworks.xstream.core.util.Base64Encoder;
/**
*AES加密解密
*@authorEX-CHENQI004
*
*/
publicclassAesUtils{
publicstaticfinalStringcKey="assistant7654321";
/**
*加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringencrypt(StringsSrc,StringsKey)throwsException{
if(sKey==null){
("ArgumentsKeyisnull.");
}
if(sKey.length()!=16){
(
"ArgumentsKey'lengthisnot16.");
}
byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");
Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
byte[]encrypted=cipher.doFinal(sSrc.getBytes("UTF-8"));
StringtempStr=parseByte2HexStr(encrypted);
Base64Encoderencoder=newBase64Encoder();
returnencoder.encode(tempStr.getBytes("UTF-8"));
}
/**
*解密--先进行base64解码,在进行16进制转为2进制然后再解码
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringdecrypt(StringsSrc,StringsKey)throwsException{
if(sKey==null){
("499");
}
if(sKey.length()!=16){
("498");
}
byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");
Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);
Base64Encoderencoder=newBase64Encoder();
byte[]encrypted1=encoder.decode(sSrc);
StringtempStr=newString(encrypted1,"utf-8");
encrypted1=parseHexStr2Byte(tempStr);
byte[]original=cipher.doFinal(encrypted1);
StringoriginalString=newString(original,"utf-8");
returnoriginalString;
}
/**
*将二进制转换成16进制
*
*@parambuf
*@return
*/
(bytebuf[]){
StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
returnsb.toString();
}
/**
*将16进制转换为二进制
*
*@paramhexStr
*@return
*/
publicstaticbyte[]parseHexStr2Byte(StringhexStr){
if(hexStr.length()<1)
returnnull;
byte[]result=newbyte[hexStr.length()/2];
for(inti=0;i<hexStr.length()/2;i++){
inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);
intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),
16);
result[i]=(byte)(high*16+low);
}
returnresult;
}
publicstaticvoidmain(String[]args)throwsException{
/*
*加密用的Key可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定
*/
StringcKey="assistant7654321";
//需要加密的字串
StringcSrc="123456";
//加密
longlStart=System.currentTimeMillis();
StringenString=encrypt(cSrc,cKey);
System.out.println("加密后的字串是:"+enString);
longlUseTime=System.currentTimeMillis()-lStart;
System.out.println("加密耗时:"+lUseTime+"毫秒");
//解密
lStart=System.currentTimeMillis();
StringDeString=decrypt(enString,cKey);
System.out.println("解密后的字串是:"+DeString);
lUseTime=System.currentTimeMillis()-lStart;
System.out.println("解密耗时:"+lUseTime+"毫秒");
}
}
Ⅱ 如何利用JAVA对文档进行加密和解密处理,完整的java类
我以前上密码学课写过一个DES加解密的程序,是自己实现的,不是通过调用java库函数,代码有点长,带有用户界面。需要的话联系我
Ⅲ JAVA使用什么加密算法和解密算法好
简单的Java加密算法有:
第一种. BASE
Base是网络上最常见的用于传输Bit字节代码的编码方式之一,大家可以查看RFC~RFC,上面有MIME的详细规范。Base编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base来将一个较长的唯一标识符(一般为-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base编码具有不可读性,即所编码的数据不会被人用肉眼所直接看到。
第二种. MD
MD即Message-Digest Algorithm (信息-摘要算法),用于确保信息传输完整一致。是计算机广泛使用的杂凑算法之一(又译摘要算法、哈希算法),主流编程语言普遍已有MD实现。将数据(如汉字)运算为另一固定长度值,是杂凑算法的基础原理,MD的前身有MD、MD和MD。广泛用于加密和解密技术,常用于文件校验。校验?不管文件多大,经过MD后都能生成唯一的MD值。好比现在的ISO校验,都是MD校验。怎么用?当然是把ISO经过MD后产生MD的值。一般下载linux-ISO的朋友都见过下载链接旁边放着MD的串。就是用来验证文件是否一致的。
MD算法具有以下特点:
压缩性:任意长度的数据,算出的MD值长度都是固定的。
容易计算:从原数据计算出MD值很容易。
抗修改性:对原数据进行任何改动,哪怕只修改个字节,所得到的MD值都有很大区别。
弱抗碰撞:已知原数据和其MD值,想找到一个具有相同MD值的数据(即伪造数据)是非常困难的。
强抗碰撞:想找到两个不同的数据,使它们具有相同的MD值,是非常困难的。
MD的作用是让大容量信息在用数字签名软件签署私人密钥前被”压缩”成一种保密的格式(就是把一个任意长度的字节串变换成一定长的十六进制数字串)。除了MD以外,其中比较有名的还有sha-、RIPEMD以及Haval等。
第三种.SHA
安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准(Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于^位的消息,SHA会产生一个位的消息摘要。该算法经过加密专家多年来的发展和改进已日益完善,并被广泛使用。该算法的思想是接收一段明文,然后以一种不可逆的方式将它转换成一段(通常更小)密文,也可以简单的理解为取一串输入码(称为预映射或信息),并把它们转化为长度较短、位数固定的输出序列即散列值(也称为信息摘要或信息认证代码)的过程。散列函数值可以说是对明文的一种“指纹”或是“摘要”所以对散列值的数字签名就可以视为对此明文的数字签名。
SHA-与MD的比较
因为二者均由MD导出,SHA-和MD彼此很相似。相应的,他们的强度和其他特性也是相似,但还有以下几点不同:
对强行攻击的安全性:最显着和最重要的区别是SHA-摘要比MD摘要长 位。使用强行技术,产生任何一个报文使其摘要等于给定报摘要的难度对MD是^数量级的操作,而对SHA-则是^数量级的操作。这样,SHA-对强行攻击有更大的强度。
对密码分析的安全性:由于MD的设计,易受密码分析的攻击,SHA-显得不易受这样的攻击。
速度:在相同的硬件上,SHA-的运行速度比MD慢。
第四种.HMAC
HMAC(Hash Message Authentication Code,散列消息鉴别码,基于密钥的Hash算法的认证协议。消息鉴别码实现鉴别的原理是,用公开函数和密钥产生一个固定长度的值作为认证标识,用这个标识鉴别消息的完整性。使用一个密钥生成一个固定大小的小数据块,即MAC,并将其加入到消息中,然后传输。接收方利用与发送方共享的密钥进行鉴别认证等。
Ⅳ Java文件加解密
做网站有时会处理一些上传下载的文件 可能会用到加解密功能 以下是一个加解密方法
Java代码
import java io File;
import java io FileInputStream;
import java io FileOutputStream;
import java io IOException;
import nf Conf;
import mon time TimeHandler;
/**
* 加解密单元
* @author lupingui
* : :
*/
public class EncryptDecrypt {
//加解密KEY 这个不能变动 这里可以由任意的字符组成 尽量用特殊字符
static final byte[] KEYVALUE = getBytes();
//读取字节的长度
static final int BUFFERLEN = ;
//加密临时存储目录
static final String TRANSIT_DIR_ENC = ;
//解密临时存储目录
static final String TRANSIT_DIR_DEC = ;
/**
* 文件加密
* @param oldFile 待加密文件
* @param saveFileName 加密后文件保存路径
* @return
* @throws IOException
*/
public static boolean encryptFile(File oldFile String saveFileName) throws IOException{
//如果传入的文件不存在或者不是文件则直接返回
if (!oldFile exists() || !oldFile isFile()){
return false;
}
FileInputStream in = new FileInputStream(oldFile);
//加密后存储的文件
File file = new File(saveFileName);
if (!file exists()){
return false;
}
//读取待加密文件加密后写入加密存储文件中
FileOutputStream out = new FileOutputStream(file);
int c pos keylen;
pos = ;
keylen = KEYVALUE length;
byte buffer[] = new byte[BUFFERLEN];
while ((c = in read(buffer)) != ) {
for (int i = ; i < c; i++) {
buffer[i] ^= KEYVALUE[pos];
out write(buffer[i]);
pos++;
if (pos == keylen){
pos = ;
}
}
}
in close();
out close();
return true;
}
/**
* 文件加密
* @param oldFile:待加密文件
* @param saveFile 加密后的文件
* @return
* @throws IOException
*/
public static boolean encryptFile(File oldFile File saveFile) throws IOException{
//如果传入的文件不存在或者不是文件则直接返回
if (!oldFile exists() || !oldFile isFile() || !saveFile exists() || !saveFile isFile()){
return false;
}
FileInputStream in = new FileInputStream(oldFile);
//读取待加密文件加密后写入加密存储文件中
FileOutputStream out = new FileOutputStream(saveFile);
int c pos keylen;
pos = ;
keylen = KEYVALUE length;
byte buffer[] = new byte[BUFFERLEN];
while ((c = in read(buffer)) != ) {
for (int i = ; i < c; i++) {
buffer[i] ^= KEYVALUE[pos];
out write(buffer[i]);
pos++;
if (pos == keylen){
pos = ;
}
}
}
in close();
out close();
return true;
}
/**
* 文件加密
* @param oldFile 待加密文件
* @return
* @throws IOException
*/
public static File encryptFile(File oldFile) throws IOException{
//如果传入的文件不存在或者不是文件则直接返回
if (!oldFile exists() || !oldFile isFile()){
return null;
}
FileInputStream in = new FileInputStream(oldFile);
//临时加密文件存储目录
File dirFile = new File(TRANSIT_DIR_ENC);
//如果临时存储目录不存在或不是目录则直接返回
if (!dirFile exists() || !dirFile isDirectory()){
return null;
}
//加密后存储的文件
File file = new File(dirFile enc_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName());
if (!file exists()){
file createNewFile();
}
//读取待加密文件加密后写入加密存储文件中
FileOutputStream out = new FileOutputStream(file);
int c pos keylen;
pos = ;
keylen = KEYVALUE length;
byte buffer[] = new byte[BUFFERLEN];
while ((c = in read(buffer)) != ) {
for (int i = ; i < c; i++) {
buffer[i] ^= KEYVALUE[pos];
out write(buffer[i]);
pos++;
if (pos == keylen){
pos = ;
}
}
}
in close();
out close();
//返回加密后的文件
return file;
}
/**
* 文件加密
* @param oldFileName 待加密文件路径
* @return
* @throws IOException
* @throws Exception
*/
public static File encryptFile(String oldFileName) throws IOException {
//如果待加密文件路径不正确则直接返回
if (oldFileName == null || oldFileName trim() equals( )){
return null;
}
//待加密文件
File oldFile = new File(oldFileName);
//如果传入的文件不存在或者不是文件则直接返回
if (!oldFile exists() || !oldFile isFile()){
return null;
}
//调用文件加密方法并返回结果
return encryptFile(oldFile);
}
/**
* 文件解密
* @param oldFile 待解密文件
* @return
* @throws IOException
*/
public static File decryptFile(File oldFile) throws IOException{
//如果待解密文件不存在或者不是文件则直接返回
if (!oldFile exists() || !oldFile isFile()){
return null;
}
FileInputStream in = new FileInputStream(oldFile);
//临时解密文件存储目录
File dirFile = new File(TRANSIT_DIR_DEC);
//如果临时解密文件存储目录不存在或不是目录则返回
if (!dirFile exists() || !dirFile isDirectory()){
return null;
}
//解密存储文件
File file = new File(dirFile dec_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName() substring(oldFile getName() lastIndexOf( )));
if (!file exists()){
file createNewFile();
}
//读取待解密文件并进行解密存储
FileOutputStream out = new FileOutputStream(file);
int c pos keylen;
pos = ;
keylen = KEYVALUE length;
byte buffer[] = new byte[BUFFERLEN];
while ((c = in read(buffer)) != ) {
for (int i = ; i < c; i++) {
buffer[i] ^= KEYVALUE[pos];
out write(buffer[i]);
pos++;
if (pos == keylen){
pos = ;
}
}
}
in close();
out close();
//返回解密结果文件
return file;
}
/**
* 文件解密
* @param oldFileName 待解密文件路径
* @return
* @throws Exception
*/
public static File decryptFile(String oldFileName) throws Exception {
//如果待解密文件路径不正确则直接返回
if (oldFileName == null || oldFileName trim() equals( )){
return null;
}
//待解密文件
File oldFile = new File(oldFileName);
//如果待解密文件不存在或不是文件则直接返回
if (!oldFile exists() || !oldFile isFile()){
return null;
}
//调用文件解密方法并返回结果
return decryptFile(oldFile);
}
lishixin/Article/program/Java/hx/201311/26983
Ⅳ java中如何实现对文件和字符串加密. 解密
DES 密钥生成,加解密方法,,你可以看一下
//DES 密钥生成工具
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class GenKey {
private static final String DES = "DES";
public static final String SKEY_NAME = "key.des";
public static void genKey1(String path) {
// 密钥
SecretKey skey = null;
// 密钥随机数生成
SecureRandom sr = new SecureRandom();
//生成密钥文件
File file = genFile(path);
try {
// 获取密钥生成实例
KeyGenerator gen = KeyGenerator.getInstance(DES);
// 初始化密钥生成器
gen.init(sr);
// 生成密钥
skey = gen.generateKey();
// System.out.println(skey);
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param file : 生成密钥的路径
* SecretKeyFactory 方式生成des密钥
* */
public static void genKey2(String path) {
// 密钥随机数生成
SecureRandom sr = new SecureRandom();
// byte[] bytes = {11,12,44,99,76,45,1,8};
byte[] bytes = sr.generateSeed(20);
// 密钥
SecretKey skey = null;
//生成密钥文件路径
File file = genFile(path);
try {
//创建deskeyspec对象
DESKeySpec desKeySpec = new DESKeySpec(bytes,9);
//实例化des密钥工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
//生成密钥对象
skey = keyFactory.generateSecret(desKeySpec);
//写出密钥对象
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static File genFile(String path) {
String temp = null;
File newFile = null;
if (path.endsWith("/") || path.endsWith("\\")) {
temp = path;
} else {
temp = path + "/";
}
File pathFile = new File(temp);
if (!pathFile.exists())
pathFile.mkdirs();
newFile = new File(temp+SKEY_NAME);
return newFile;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
genKey2("E:/a/aa/");
}
}
//DES加解密方法
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*制卡文件加/解密 加密方式DES
*/
public class SecUtil {
public static final Log log = LogFactory.getLog(SecUtil.class);
/**
* 解密
*
* @param keyPath
* 密钥路径
* @param source
* 解密前文件
* @param dest
* 解密后文件
*/
public static void decrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
// 读取加密密钥
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
log.info("Error when read keyFile");
throw new RuntimeException(ey1);
} catch (Exception ey2) {
log.info("error when read the keyFile");
throw new RuntimeException(ey2);
}
// 用key产生Cipher
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception ey3) {
log.info("Error when create the cipher");
throw new RuntimeException(ey3);
}
// 取得要解密的文件并解密
File file = new File(source);
String filename = file.getName();
try {
// 输出流,请注意文件名称的获取
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(dest));
// 输入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(file)), cipher);
int thebyte = 0;
while ((thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
} catch (Exception ey5) {
log.info("Error when encrypt the file");
throw new RuntimeException(ey5);
}
}
/**
* 加密
* @param keyPath 密钥路径
* @param source 加密前文件
* @param dest 加密后文件
*/
public static void encrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
// 读取加密密钥
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
log.info("Error when read keyFile");
throw new RuntimeException(ey1);
} catch (Exception ey2) {
log.info("error when read the keyFile");
throw new RuntimeException(ey2);
}
// 用key产生Cipher
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (Exception ey3) {
log.info("Error when create the cipher");
throw new RuntimeException(ey3);
}
// 取得要解密的文件并解密
File file = new File(source);
String filename = file.getName();
try {
// 输出流,请注意文件名称的获取
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(dest));
// 输入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(file)), cipher);
int thebyte = 0;
while ((thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
} catch (Exception ey5) {
log.info("Error when encrypt the file");
throw new RuntimeException(ey5);
}
}
}
Ⅵ 如何用java实现文件(不只是txt文本)的整体加密解密
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.NoSuchAlgorithmException;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjavax.crypto.Cipher;
/**
*文件加密解密
*加解密需要依靠以下四个属性,
;
staticKeyPairkeyPair;
staticRSAPrivateKeyprivateKey;
staticRSAPublicKeypublicKey;
*@authoryoung
*
*/
publicclassRSAEncrypt{
;
staticKeyPairkeyPair;
staticRSAPrivateKeyprivateKey;
staticRSAPublicKeypublicKey;
static{
try{
//实例类型
keyPairGen=KeyPairGenerator.getInstance("RSA");
//初始化长度
keyPairGen.initialize(512);
//声场KeyPair
keyPair=keyPairGen.generateKeyPair();
//Generatekeys
privateKey=(RSAPrivateKey)keyPair.getPrivate();
publicKey=(RSAPublicKey)keyPair.getPublic();
}catch(NoSuchAlgorithmExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
RSAEncryptencrypt=newRSAEncrypt();
Filefile=newFile(
"C:\DocumentsandSettings\Administrator.DCB5E0D91E0D436\桌面\sdf.txt");
FilenewFile=newFile(
"C:\DocumentsandSettings\Administrator.DCB5E0D91E0D436\桌面\sdf1.txt");
encrypt.encryptFile(encrypt,file,newFile);
Filefile1=newFile(
"C:\DocumentsandSettings\Administrator.DCB5E0D91E0D436\桌面\sdf1.txt");
FilenewFile1=newFile(
"C:\DocumentsandSettings\Administrator.DCB5E0D91E0D436\桌面\sdf2.txt");
encrypt.decryptFile(encrypt,file1,newFile1);
}
/**
*加密文件
*@paramencryptRSAEncrypt对象
*@paramfile源文件
*@paramnewFile目标文件
*/
publicvoidencryptFile(RSAEncryptencrypt,Filefile,FilenewFile){
try{
InputStreamis=newFileInputStream(file);
OutputStreamos=newFileOutputStream(newFile);
byte[]bytes=newbyte[53];
while(is.read(bytes)>0){
byte[]e=encrypt.encrypt(RSAEncrypt.publicKey,bytes);
bytes=newbyte[53];
os.write(e,0,e.length);
}
os.close();
is.close();
System.out.println("writesuccess");
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*解密文件
*@paramencryptRSAEncrypt对象
*@paramfile
*@paramnewFile
*/
publicvoiddecryptFile(RSAEncryptencrypt,Filefile,FilenewFile){
try{
InputStreamis=newFileInputStream(file);
OutputStreamos=newFileOutputStream(newFile);
byte[]bytes1=newbyte[64];
while(is.read(bytes1)>0){
byte[]de=encrypt.decrypt(RSAEncrypt.privateKey,bytes1);
bytes1=newbyte[64];
os.write(de,0,de.length);
}
os.close();
is.close();
System.out.println("writesuccess");
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*加密实现
**EncryptString.*
*
*@returnbyte[]加密后的字节数组
*/
protectedbyte[]encrypt(RSAPublicKeypublicKey,byte[]obj){
if(publicKey!=null){
try{
Ciphercipher=Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
returncipher.doFinal(obj);
}catch(Exceptione){
e.printStackTrace();
}
}
returnnull;
}
/**
*解密实现
**Basicdecryptmethod*
*
*@returnbyte[]解密后的字节数组
*/
protectedbyte[]decrypt(RSAPrivateKeyprivateKey,byte[]obj){
if(privateKey!=null){
try{
Ciphercipher=Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,privateKey);
returncipher.doFinal(obj);
}catch(Exceptione){
e.printStackTrace();
}
}
returnnull;
}
}
Ⅶ 漫谈Java加密技术(二)
接下来我们介绍对称加密算法 最常用的莫过于DES数据加密算法
DES
DES Data Encryption Standard 即数据加密算法 是IBM公司于 年研究成功并公开发表的 DES算法的入口参数有三个 Key Data Mode 其中Key为 个字节共 位 是DES算法的工作密钥 Data也为 个字节 位 是要被加密或被解密的数据 Mode为DES的工作方式 有两种 加密或解密
DES算法把 位的明文输入块变为 位的密文输出块 它所使用的密钥也是 位
通过java代码实现如下
importjava security Key;importjava security SecureRandom;importjavax crypto Cipher;importjavax crypto KeyGenerator;importjavax crypto SecretKey;importjavax crypto SecretKeyFactory;importjavax crypto spec DESKeySpec;/***//***DES安全编码组件authorby;**<pre>*支持DES DESede(TripleDES 就是 DES) AES Blowfish RC RC (ARCFOUR)*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*具体内容需要关注JDKDocument&///docs/technotes/guides/security/l*</pre>**@author梁栋*@version *@since */{/***//***ALGORITHM算法<br>*可替换为以下任意一种算法 同时key值的size相应改变 **<pre>*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*</pre>**在KeytoKey(byte[]key)方法中使用下述代码*<code>SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);</code>替换*<code>*DESKeySpecdks=newDESKeySpec(key);*SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);*SecretKeysecretKey=keyFactory generateSecret(dks);*</code>*/= DES ;/***//***转换密钥<br>**@paramkey*@return*@throwsException*/privatestaticKeytoKey(byte[]key)throwsException{DESKeySpecdks=newDESKeySpec(key);SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);SecretKeysecretKey=keyFactory generateSecret(dks);//当使用其他对称加密算法时 如AES Blowfish等算法时 用下述代码替换上述三行代码//SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);returnsecretKey;}/***//***解密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]decrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher DECRYPT_MODE k);returncipher doFinal(data);}/***//***加密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]encrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher ENCRYPT_MODE k);returncipher doFinal(data);}/***//***生成密钥**@return*@throwsException*/publicstaticStringinitKey()throwsException{returninitKey(null);}/***//***生成密钥**@paramseed*@return*@throwsException*/publicstaticStringinitKey(Stringseed)throwsException{SecureRandomsecureRandom=null;if(seed!=null){secureRandom=newSecureRandom(decryptBASE (seed));}else{secureRandom=newSecureRandom();}KeyGeneratorkg=KeyGenerator getInstance(ALGORITHM);kg init(secureRandom);SecretKeysecretKey=kg generateKey();returnencryptBASE (secretKey getEncoded());}}
延续上一个类的实现 我们通过MD 以及SHA对字符串加密生成密钥 这是比较常见的密钥生成方式
再给出一个测试类
importstatic junit Assert *;import junit Test;/***//****@authorby;;*@version *@since */publicclassDESCoderTest{@Testpublicvoidtest()throwsException{StringinputStr= DES ;Stringkey=DESCoder initKey();System err println( 原文: +inputStr);System err println( 密钥: +key);byte[]inputData=inputStr getBytes();inputData=DESCoder encrypt(inputData key);System err println( 加密后: +DESCoder encryptBASE (inputData));byte[]outputData=DESCoder decrypt(inputData key);StringoutputStr=newString(outputData);System err println( 解密后: +outputStr);assertEquals(inputStr outputStr);}}
得到的输出内容如下
原文 DES
密钥 f wEtRrV q =
加密后 C qe oNIzRY=
解密后 DES
由控制台得到的输出 我们能够比对加密 解密后结果一致 这是一种简单的加密解密方式 只有一个密钥
其实DES有很多同胞兄弟 如DESede(TripleDES) AES Blowfish RC RC (ARCFOUR) 这里就不过多阐述了 大同小异 只要换掉ALGORITHM换成对应的值 同时做一个代码替换SecretKey secretKey = new SecretKeySpec(key ALGORITHM) 就可以了 此外就是密钥长度不同了
/**
lishixin/Article/program/Java/gj/201311/27624