java加密解密工具
移动端越来越火了,我们在开发过程中,总会碰到要和移动端打交道的场景,比如.NET和android或者iOS的打交道。为了让数据交互更安全,我们需要对数据进行加密传输。今天研究了一下,把几种语言的加密都实践了一遍,实现了.NET,java(android),iOS都同一套的加密算法,下面就分享给大家。
AES加密有多种算法模式,下面提供两套模式的可用源码。
加密方式:
先将文本AES加密
返回Base64转码
解密方式:
将数据进行Base64解码
进行AES解密
一、CBC(Cipher Block Chaining,加密块链)模式
是一种循环模式,前一个分组的密文和当前分组的明文异或操作后再加密,这样做的目的是增强破解难度.
密钥
密钥偏移量
java/adroid加密AESOperator类:
package com.bci.wx.base.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* AES 是一种可逆加密算法,对用户的敏感信息加密处理 对原始数据进行AES加密后,在进行Base64编码转化;
*/
public class AESOperator {
/*
* 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式,key需要为16位。
*/
private String sKey = "smkldospdosldaaa";//key,可自行修改
private String ivParameter = "0392039203920300";//偏移量,可自行修改
private static AESOperator instance = null;
private AESOperator() {
}
public static AESOperator getInstance() {
if (instance == null)
instance = new AESOperator();
return instance;
}
public static String Encrypt(String encData ,String secretKey,String vector) throws Exception {
if(secretKey == null) {
return null;
}
if(secretKey.length() != 16) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = secretKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。
}
// 加密
public String encrypt(String sSrc) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。
}
// 解密
public String decrypt(String sSrc) throws Exception {
try {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception ex) {
return null;
}
}
public String decrypt(String sSrc,String key,String ivs) throws Exception {
try {
byte[] raw = key.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception ex) {
return null;
}
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
B. 如何利用JAVA对文档进行加密和解密处理,完整的java类
我以前上密码学课写过一个DES加解密的程序,是自己实现的,不是通过调用java库函数,代码有点长,带有用户界面。需要的话联系我
C. 用Java实现IDEA数据加密解密
随着Internet的迅速发展,电子商务的浪潮势不可挡,日常工作和数据传输都放在Internet网上进行传输,大大提高了效率,降低了成本,创造了良好的效益。但是,由于Internet网络协议本身存在着重要的安全问题(IP包本身并不继承任何安全特性,很容易伪造出IP包的地址、修改其内容、重播以前的包以及在传输途中拦截并查看包的内容),使网上的信息传输存在巨大的安全风险电子商务的安全问题也越来越突出。加密是电子商务中最主要的安全技术,加密方法的选取直接影响电子商务活动中信息的安全程度,在电子商务系统中,主要的安全问题都可以通过加密来解决。数据的保密性可通过不同的加密算法对数据加密来实现。
对我国来讲,虽然可以引进很多的外国设备,但加密设备不能依靠引进,因为它涉及到网络安全、国家机密信息的安全,所以必须自己研制。当前国际上有许多加密算法,其中DES(Data Encryption Standard)是发明最早的用得最广泛的分组对称加密算法,DES用56位蜜钥加密64位明文,输出64位密文,DES的56位密钥共有256 种可能的密钥,但历史上曾利用穷举攻击破解过DES密钥,1998年电子边境基金会(EFF)用25万美元制造的专用计算机,用56小时破解了DES的密钥,1999年,EFF用22小时完成了破解工作,使DES算法受到了严重打击,使它的安全性受到严重威胁。因为JAVA语言的安全性和网络处理能力较强,本文主要介绍使用IDEA(Internation Data Encryption Algorithm )数据加密算法在Java环境下实现数据的安全传输。
一、IDEA数据加密算法
IDEA数据加密算法是由中国学者来学嘉博士和着名的密码专家 James L. Massey 于1990年联合提出的。它的明文和密文都是64比特,但密钥长为128比特。IDEA 是作为迭代的分组密码实现的,使用 128 位的密钥和 8 个循环。这比 DES 提供了更多的 安全性,但是在选择用于 IDEA 的密钥时,应该排除那些称为“弱密钥”的密钥。DES 只有四个弱密钥和 12 个次弱密钥,而 IDEA 中的弱密钥数相当可观,有 2 的 51 次方个。但是,如果密钥的总数非常大,达到 2 的 128 次方个,那么仍有 2 的 77 次歼则方个密钥可供选择。IDEA 被认为是极为安全的。使用 128 位的密钥,蛮力攻击中需要进行的测试次数与 DES 相比会明显增大,甚至允许对弱密钥测试。而且,它本身 也显示了它尤其能抵抗专业形式的分析性攻击。
二、Java密码体系和Java密码扩展
Java是Sun公司开发的一种面向对象的编程语言,并且由于它的平台无关性被大量应用于Internet的开发。Java密码体系(JCA)和Java密码扩展(JCE)的设计目的是为Java提供与实现无关的加密函数API。它们都用factory方法来创建类的例程,然后把实际的加密函数委托给提供者指定的底层引擎,引擎中为类提供了服务提供者接口在Java中实现数据的加密/解密,是使用其内置的JCE(Java加密扩展)来实现的。Java开发工具集1.1为实现包括数字签名和信息摘要在内的加密功能,推出了一种基于供应商的新型灵活应用编程接口。Java密码体系结构支持供应商的互操作,同时支持硬件和软件实现。Java密码学结构设计遵循两个原则:(1)算法的独立性和可靠性。(2)实现的独立性和相互作用性。算法的独立性是通过定义密码服务类和改模来获得。用户只需了解密码算法的概念,而不用去关心如何实现这些概念。实现的独立性和相互作用性通过密码服务提供器来实现。密码服务提供器是实现一个或多个密码服务的一个或多个程序包。软件开发商根据一定接口,将各种算法实现后,打包成一个提供器,用户可以安装不同的提供器。安装和配置提供器,可将包含提供器的ZIP和JAR文件放在CLASSPATH下,再编辑Java安全属性文件唤缓来设置定义一个提供器。Java运行环境Sun版本时,提供一个缺省的提供器Sun。
三、Java环境下的实现
1.加密过程的实现
void idea_enc( int data11[], /*待加密的64位数据首地址*/ int key1[]){
int i ;
int tmp,x;
int zz[]=new int[6];
for ( i = 0 ; i < 48 ; i += 6) { /*进行8轮循环*/
for(int j=0,box=i;j<6;j++,box++){
zz[j]=key1[box];
}
x = handle_data(data11,zz);
tmp = data11[1]; /*交换中间两个*/
data11[1] = data11[2];
data11[2] = tmp;
}
tmp = data11[1]; /*最后一轮不交换*/
data11[1] = data11[2];
data11[2] = tmp;
data11[0] = MUL(data11[0],key1[48]);
data11[1] =(char)((data11[1] + key1[49])%0x10000);
data11[2] =(char)((data11[2] + key1[50])%0x10000);
data11[3] = MUL(data11[3],key1[51]);
}
2.解密过程的实现
void key_decryExp(int outkey[])/*解密密钥的变逆处理*/
{ int tmpkey[] = new int[52] ;
int i;
for ( i = 0 ; i < 52 ; i++) {
tmpkey[i] = outkey[ wz_spkey[i] ] ;/*换位*/
}
for ( i = 0 ; i < 52 ; i++) {
outkey[i] = tmpkey[i];
}
for ( i = 0 ; i < 18 ; i++) {
outkey[wz_spaddrever[i]] = (char)(65536-outkey[wz_spaddrever[i]]) ;/*替换成加法逆*/
}
for ( i = 0 ; i < 18 ; i++){
outkey[wz_spmulrevr[i]] =(char)(mulInv(outkey[wz_spmulrevr[i]] ));/*替换成乘法逆*/
}
}
四、总结
在实际应用中,我们可以使用Java开发工具包(JDK)中内置的对Socket通信的支持,通过JCE中的Java流和链表,加密基于Socket的网络通信.我们知道,加密/解密是数据传输中保证数据完整性的常用方法,Java语言因其平台无关性,在Internet上的应用非常之广泛.使用Java实现基于IDEA的数据加密传输可以在不同的平台上实现并具有实现简洁、安全性强等优点。
D. 如何使用JAVA实现对字符串的DES加密和解密
java加密字符串可以使用des加密算法,实例如下:
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 加密解密
*
* @author shy.qiu
* @since http://blog.csdn.net/qiushyfm
*/
public class CryptTest {
/**
* 进行MD5加密
*
* @param info
* 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToMD5(String info) {
byte[] digesta = null;
try {
// 得到一个md5的消息摘要
MessageDigest alga = MessageDigest.getInstance("MD5");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}
/**
* 进行SHA加密
*
* @param info
* 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToSHA(String info) {
byte[] digesta = null;
try {
// 得到一个SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}
// //////////////////////////////////////////////////////////////////////////
/**
* 创建密匙
*
* @param algorithm
* 加密算法,可用 DES,DESede,Blowfish
* @return SecretKey 秘密(对称)密钥
*/
public SecretKey createSecretKey(String algorithm) {
// 声明KeyGenerator对象
KeyGenerator keygen;
// 声明 密钥对象
SecretKey deskey = null;
try {
// 返回生成指定算法的秘密密钥的 KeyGenerator 对象
keygen = KeyGenerator.getInstance(algorithm);
// 生成一个密钥
deskey = keygen.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 返回密匙
return deskey;
}
/**
* 根据密匙进行DES加密
*
* @param key
* 密匙
* @param info
* 要加密的信息
* @return String 加密后的信息
*/
public String encryptToDES(SecretKey key, String info) {
// 定义 加密算法,可用 DES,DESede,Blowfish
String Algorithm = "DES";
// 加密随机数生成器 (RNG),(可以不写)
SecureRandom sr = new SecureRandom();
// 定义要生成的密文
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
// 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
c1.init(Cipher.ENCRYPT_MODE, key, sr);
// 对要加密的内容进行编码处理,
cipherByte = c1.doFinal(info.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
// 返回密文的十六进制形式
return byte2hex(cipherByte);
}
/**
* 根据密匙进行DES解密
*
* @param key
* 密匙
* @param sInfo
* 要解密的密文
* @return String 返回解密后信息
*/
public String decryptByDES(SecretKey key, String sInfo) {
// 定义 加密算法,
String Algorithm = "DES";
// 加密随机数生成器 (RNG)
SecureRandom sr = new SecureRandom();
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
c1.init(Cipher.DECRYPT_MODE, key, sr);
// 对要解密的内容进行编码处理
cipherByte = c1.doFinal(hex2byte(sInfo));
} catch (Exception e) {
e.printStackTrace();
}
// return byte2hex(cipherByte);
return new String(cipherByte);
}
// /////////////////////////////////////////////////////////////////////////////
/**
* 创建密匙组,并将公匙,私匙放入到指定文件中
*
* 默认放入mykeys.bat文件中
*/
public void createPairKey() {
try {
// 根据特定的算法一个密钥对生成器
KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
// 加密随机数生成器 (RNG)
SecureRandom random = new SecureRandom();
// 重新设置此随机对象的种子
random.setSeed(1000);
// 使用给定的随机源(和默认的参数集合)初始化确定密钥大小的密钥对生成器
keygen.initialize(512, random);// keygen.initialize(512);
// 生成密钥组
KeyPair keys = keygen.generateKeyPair();
// 得到公匙
PublicKey pubkey = keys.getPublic();
// 得到私匙
PrivateKey prikey = keys.getPrivate();
// 将公匙私匙写入到文件当中
doObjToFile("mykeys.bat", new Object[] { prikey, pubkey });
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中
*
* @param info
* 要签名的信息
* @param signfile
* 存入的文件
*/
public void signToInfo(String info, String signfile) {
// 从文件当中读取私匙
PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
// 从文件中读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
try {
// Signature 对象可用来生成和验证数字签名
Signature signet = Signature.getInstance("DSA");
// 初始化签署签名的私钥
signet.initSign(myprikey);
// 更新要由字节签名或验证的数据
signet.update(info.getBytes());
// 签署或验证所有更新字节的签名,返回签名
byte[] signed = signet.sign();
// 将数字签名,公匙,信息放入文件中
doObjToFile(signfile, new Object[] { signed, mypubkey, info });
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取数字签名文件 根据公匙,签名,信息验证信息的合法性
*
* @return true 验证成功 false 验证失败
*/
public boolean validateSign(String signfile) {
// 读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
// 读取签名
byte[] signed = (byte[]) getObjFromFile(signfile, 1);
// 读取信息
String info = (String) getObjFromFile(signfile, 3);
try {
// 初始一个Signature对象,并用公钥和签名进行验证
Signature signetcheck = Signature.getInstance("DSA");
// 初始化验证签名的公钥
signetcheck.initVerify(mypubkey);
// 使用指定的 byte 数组更新要签名或验证的数据
signetcheck.update(info.getBytes());
System.out.println(info);
// 验证传入的签名
return signetcheck.verify(signed);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将二进制转化为16进制字符串
*
* @param b
* 二进制字节数组
* @return String
*/
public String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
/**
* 十六进制字符串转化为2进制
*
* @param hex
* @return
*/
public byte[] hex2byte(String hex) {
byte[] ret = new byte[8];
byte[] tmp = hex.getBytes();
for (int i = 0; i < 8; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/**
* 将两个ASCII字符合成一个字节; 如:"EF"--> 0xEF
*
* @param src0
* byte
* @param src1
* byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 将指定的对象写入指定的文件
*
* @param file
* 指定写入的文件
* @param objs
* 要写入的对象
*/
public void doObjToFile(String file, Object[] objs) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
for (int i = 0; i < objs.length; i++) {
oos.writeObject(objs[i]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 返回在文件中指定位置的对象
*
* @param file
* 指定的文件
* @param i
* 从1开始
* @return
*/
public Object getObjFromFile(String file, int i) {
ObjectInputStream ois = null;
Object obj = null;
try {
FileInputStream fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
for (int j = 0; j < i; j++) {
obj = ois.readObject();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
CryptTest jiami = new CryptTest();
// 执行MD5加密"Hello world!"
System.out.println("Hello经过MD5:" + jiami.encryptToMD5("Hello"));
// 生成一个DES算法的密匙
SecretKey key = jiami.createSecretKey("DES");
// 用密匙加密信息"Hello world!"
String str1 = jiami.encryptToDES(key, "Hello");
System.out.println("使用des加密信息Hello为:" + str1);
// 使用这个密匙解密
String str2 = jiami.decryptByDES(key, str1);
System.out.println("解密后为:" + str2);
// 创建公匙和私匙
jiami.createPairKey();
// 对Hello world!使用私匙进行签名
jiami.signToInfo("Hello", "mysign.bat");
// 利用公匙对签名进行验证。
if (jiami.validateSign("mysign.bat")) {
System.out.println("Success!");
} else {
System.out.println("Fail!");
}
}
}
E. 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);
}
}
}
F. Des加密解密方法 用java C#和C++三种方式实现
Solaris下的系统,有一个用C做的加密工具,调用Sunwcry的des(1)对文件进行加密,然后在java中对文件进行解密。java中用的是标准的DES/CBC/NoPadding算法,可是解密后发现开头有8byte的数据出错了,请高人指点一下。
cbc_encrypt.c : 加密用的C程序
cbc_decrypt.c:解密用的C程序
TestDescbc.java:解密用的java程序
Test01.dat原始文件
Test03.dat cbc_encrypt加密后的文件
Test05.dat cbc_decrypt解密后的文件
Test06.dat TestDescbc解密后的文件
G. 如何用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;
}
}
H. Java 加密解密的方法都有哪些
加密解密并非java才有的,所有编程语言都有加密和解密。
目前的加密解密主要可分为以下2大类:
对称秘钥加密:如DES算法,3DES算法,TDEA算法,Blowfish算法,RC5算法,IDEA算法等。其主要特点是加密方和解密方都有同一个密码,加密方和解密方可以使用秘钥任意加密解密。
非对称密码加密:这种加密方式加密方仅有加密秘钥,对加密后的密文无法反向解密,解密方仅有解密秘钥,无法对明文进行加密。
另外还有一些摘要算法,比如MD5和HASH此类算法不可逆,但经常用来作为确认字段或者对一些重要匹配信息签名防止明文内容被修改。
I. 用java实现des加密和解密
一个用DES来加密、解密的类
http://www.javanb.com/java/1/17816.html
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* 字符串工具集合
* @author Liudong
*/
public class StringUtils {
private static final String PASSWORD_CRYPT_KEY = "__jDlog_";
private final static String DES = "DES";
/**
* 加密
* @param src 数据源
* @param key 密钥,长度必须是8的倍数
* @return 返回加密后的数据
* @throws Exception
*/
public static byte[] encrypt(byte[] src, byte[] key)throws Exception {
//DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密匙数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密匙工厂,然后用它把DESKeySpec转换成
// 一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
// 现在,获取数据并加密
// 正式执行加密操作
return cipher.doFinal(src);
}
/**
* 解密
* @param src 数据源
* @param key 密钥,长度必须是8的倍数
* @return 返回解密后的原始数据
* @throws Exception
*/
public static byte[] decrypt(byte[] src, byte[] key)throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密匙数据创建一个DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
// 一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
// 现在,获取数据并解密
// 正式执行解密操作
return cipher.doFinal(src);
}
/**
* 密码解密
* @param data
* @return
* @throws Exception
*/
public final static String decrypt(String data){
try {
return new String(decrypt(hex2byte(data.getBytes()),
PASSWORD_CRYPT_KEY.getBytes()));
}catch(Exception e) {
}
return null;
}
/**
* 密码加密
* @param password
* @return
* @throws Exception
*/
public final static String encrypt(String password){
try {
return byte2hex(encrypt(password.getBytes(),PASSWORD_CRYPT_KEY.getBytes())); }catch(Exception e) {
}
return null;
}
比较长, 转了一部分.
J. Java中用Base64编程的文件批量加密解密工具程序代码
/** * BASE64解密 * * @param key * @return * @throws Exception */
public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } /** * BASE64加密 * * @param key * @return * @throws Exception */ public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); }