189 8069 5689

java生成密钥源代码 java密钥库

des密钥如何生成 java

package Encrypt;

创新互联长期为成百上千客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为大厂企业提供专业的成都网站设计、做网站大厂网站改版等技术服务。拥有10多年丰富建站经验和众多成功案例,为您定制开发。

import java.security.*;

import javax.crypto.*;

import sun.misc.*;

/**

* 使用DES加密与解密,可对byte[],String类型进行加密与解密

* 密文可使用String,byte[]存储.

* 方法:

* void getKey(String strKey)从strKey的字条生成一个Key

* String getEncString(String strMing)对strMing进行加密,返回String密文

* String getDesString(String strMi)对strMin进行解密,返回String明文

* byte[] getEncCode(byte[] byteS)byte[]型的加密

* byte[] getDesCode(byte[] byteD)byte[]型的解密

*/

public class Encrypt{

private Key key;

private byte[] byteMi = null;

private byte[] byteMing = null;

private String strMi= "";

private String strM= "";

// 根据参数生成KEY

public void setKey(String strKey){

try{

KeyGenerator _generator = KeyGenerator.getInstance("DES");

_generator.init(new SecureRandom(strKey.getBytes()));

this.key = _generator.generateKey();

_generator=null;

}

catch(Exception e){

e.printStackTrace();

}

}

// 加密String明文输入,String密文输出

public void setEncString(String strMing){

BASE64Encoder base64en = new BASE64Encoder();

try {

this.byteMing = strMing.getBytes("UTF8");

this.byteMi = this.getEncCode(this.byteMing);

this.strMi = base64en.encode(this.byteMi);

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

this.byteMing = null;

this.byteMi = null;

}

}

//加密以byte[]明文输入,byte[]密文输出

private byte[] getEncCode(byte[] byteS){

byte[] byteFina = null;

Cipher cipher;

try

{

cipher = Cipher.getInstance("DES");

cipher.init(Cipher.ENCRYPT_MODE,key);

byteFina = cipher.doFinal(byteS);

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

cipher = null;

}

return byteFina;

}

// 解密:以String密文输入,String明文输出

public void setDesString(String strMi){

BASE64Decoder base64De = new BASE64Decoder();

try

{

this.byteMi = base64De.decodeBuffer(strMi);

this.byteMing = this.getDesCode(byteMi);

this.strM = new String(byteMing,"UTF8");

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

base64De = null;

byteMing = null;

byteMi = null;

}

}

// 解密以byte[]密文输入,以byte[]明文输出

private byte[] getDesCode(byte[] byteD){

Cipher cipher;

byte[] byteFina=null;

try{

cipher = Cipher.getInstance("DES");

cipher.init(Cipher.DECRYPT_MODE,key);

byteFina = cipher.doFinal(byteD);

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

cipher=null;

}

return byteFina;

}

//返回加密后的密文strMi

public String getStrMi()

{

return strMi;

}

//返回解密后的明文

public String getStrM()

{

return strM;

}

}

*注意:因为我用的时候是作为后台的BEAN来调用的,所以没有写main函数,也就不能直接运行了。必须加一个main()函数才能做为一个完成的JAVA程序使用。一个很简单的 main()函数就ok了,不用我写在这里了吧?呵呵!

在WEB前台调用这个BEAN文件时的语句:

jsp:useBean id="abc" scope="page" class="oaweb.Encrypt" /

//id="abc" 用来初始化一个对象

%

//明文加密:

String key = “06”; //初始化密钥。

abc.setKey(key); //调用set函数设置密钥。

abc.setEncString(re[i][j]);//将要加密的明文传送给Encrypt.java进行加密计算。

String Mi=abc.getStrMi(); //调用get函数获取加密后密文。

%

//变量Mi就是密文.

%

//密文解密:

abc. setDesString(String Mi); //将要解密的密文传送给Encrypt.java进行解密计算。

String M=abc. String getStrM(); //调用get函数获取解密后明文。

%

//变量M就是明文.

java加密解密代码

package com.cube.limail.util;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;/**

* 加密解密类

*/

public class Eryptogram

{

private static String Algorithm ="DES";

private String key="CB7A92E3D3491964";

//定义 加密算法,可用 DES,DESede,Blowfish

static boolean debug = false ;

/**

* 构造子注解.

*/

public Eryptogram ()

{

} /**

* 生成密钥

* @return byte[] 返回生成的密钥

* @throws exception 扔出异常.

*/

public static byte [] getSecretKey () throws Exception

{

KeyGenerator keygen = KeyGenerator.getInstance (Algorithm );

SecretKey deskey = keygen.generateKey ();

System.out.println ("生成密钥:"+bytesToHexString (deskey.getEncoded ()));

if (debug ) System.out.println ("生成密钥:"+bytesToHexString (deskey.getEncoded ()));

return deskey.getEncoded ();

} /**

* 将指定的数据根据提供的密钥进行加密

* @param input 需要加密的数据

* @param key 密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte [] encryptData (byte [] input ,byte [] key ) throws Exception

{

SecretKey deskey = new javax.crypto.spec.SecretKeySpec (key ,Algorithm );

if (debug )

{

System.out.println ("加密前的二进串:"+byte2hex (input ));

System.out.println ("加密前的字符串:"+new String (input ));

} Cipher c1 = Cipher.getInstance (Algorithm );

c1.init (Cipher.ENCRYPT_MODE ,deskey );

byte [] cipherByte =c1.doFinal (input );

if (debug ) System.out.println ("加密后的二进串:"+byte2hex (cipherByte ));

return cipherByte ;

} /**

* 将给定的已加密的数据通过指定的密钥进行解密

* @param input 待解密的数据

* @param key 密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte [] decryptData (byte [] input ,byte [] key ) throws Exception

{

SecretKey deskey = new javax.crypto.spec.SecretKeySpec (key ,Algorithm );

if (debug ) System.out.println ("解密前的信息:"+byte2hex (input ));

Cipher c1 = Cipher.getInstance (Algorithm );

c1.init (Cipher.DECRYPT_MODE ,deskey );

byte [] clearByte =c1.doFinal (input );

if (debug )

{

System.out.println ("解密后的二进串:"+byte2hex (clearByte ));

System.out.println ("解密后的字符串:"+(new String (clearByte )));

} return clearByte ;

} /**

* 字节码转换成16进制字符串

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的16进制字符串

*/

public static 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 ;

if (n b.length -1 ) hs =hs +":";

} return hs.toUpperCase ();

}

/**

* 字符串转成字节数组.

* @param hex 要转化的字符串.

* @return byte[] 返回转化后的字符串.

*/

public static byte[] hexStringToByte(String hex) {

int len = (hex.length() / 2);

byte[] result = new byte[len];

char[] achar = hex.toCharArray();

for (int i = 0; i len; i++) {

int pos = i * 2;

result[i] = (byte) (toByte(achar[pos]) 4 | toByte(achar[pos + 1]));

}

return result;

}

private static byte toByte(char c) {

byte b = (byte) "0123456789ABCDEF".indexOf(c);

return b;

}

/**

* 字节数组转成字符串.

* @param String 要转化的字符串.

* @return 返回转化后的字节数组.

*/

public static final String bytesToHexString(byte[] bArray) {

StringBuffer sb = new StringBuffer(bArray.length);

String sTemp;

for (int i = 0; i bArray.length; i++) {

sTemp = Integer.toHexString(0xFF bArray[i]);

if (sTemp.length() 2)

sb.append(0);

sb.append(sTemp.toUpperCase());

}

return sb.toString();

}

/**

* 从数据库中获取密钥.

* @param deptid 企业id.

* @return 要返回的字节数组.

* @throws Exception 可能抛出的异常.

*/

public static byte[] getSecretKey(long deptid) throws Exception {

byte[] key=null;

String value=null;

//CommDao dao=new CommDao();

// List list=dao.getRecordList("from Key k where k.deptid="+deptid);

//if(list.size()0){

//value=((com.csc.sale.bean.Key)list.get(0)).getKey();

value = "CB7A92E3D3491964";

key=hexStringToByte(value);

//}

if (debug)

System.out.println("密钥:" + value);

return key;

}

public String encryptData2(String data) {

String en = null;

try {

byte[] key=hexStringToByte(this.key);

en = bytesToHexString(encryptData(data.getBytes(),key));

} catch (Exception e) {

e.printStackTrace();

}

return en;

}

public String decryptData2(String data) {

String de = null;

try {

byte[] key=hexStringToByte(this.key);

de = new String(decryptData(hexStringToByte(data),key));

} catch (Exception e) {

e.printStackTrace();

}

return de;

}

} 加密使用: byte[] key=Eryptogram.getSecretKey(deptid); //获得钥匙(字节数组)

byte[] tmp=Eryptogram.encryptData(password.getBytes(), key); //传入密码和钥匙,获得加密后的字节数组的密码

password=Eryptogram.bytesToHexString(tmp); //将字节数组转化为字符串,获得加密后的字符串密码解密与之差不多

JAVA简单文件加密 求JAVA源代码

md5加密:

package com.ncs.pki.util;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class MD5Test {

private static MessageDigest digest = null;

public synchronized static final String hash(String data) {

if (digest == null) {

try {

digest = MessageDigest.getInstance("MD5");

} catch (NoSuchAlgorithmException nsae) {

System.err.println(

"Failed to load the MD5 MessageDigest. "

+ "Jive will be unable to function normally.");

nsae.printStackTrace();

}

}

// Now, compute hash.

digest.update(data.getBytes());

return encodeHex(digest.digest());

}

public static final String encodeHex(byte[] bytes) {

StringBuffer buf = new StringBuffer(bytes.length * 2);

int i;

for (i = 0; i bytes.length; i++) {

if (((int) bytes[i] 0xff) 0x10) {

buf.append("0");

}

buf.append(Long.toString((int) bytes[i] 0xff, 16));

}

return buf.toString();

}

public static String test(){

return null;

}

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println(MD5Test.hash("123456"));

}

}

3des加密:

package com.ncs.pki.util;

import java.security.Key;

import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

public class DesEncrypt {

/**

*

* 使用DES加密与解密,可对byte[],String类型进行加密与解密 密文可使用String,byte[]存储.

*

* 方法: void getKey(String strKey)从strKey的字条生成一个Key

*

* String getEncString(String strMing)对strMing进行加密,返回String密文 String

* getDesString(String strMi)对strMin进行解密,返回String明文

*

*byte[] getEncCode(byte[] byteS)byte[]型的加密 byte[] getDesCode(byte[]

* byteD)byte[]型的解密

*/

Key key;

/**

* 根据参数生成KEY

*

* @param strKey

*/

public void getKey(String strKey) {

try {

KeyGenerator _generator = KeyGenerator.getInstance("DES");

_generator.init(new SecureRandom(strKey.getBytes()));

this.key = _generator.generateKey();

_generator = null;

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 加密String明文输入,String密文输出

*

* @param strMing

* @return

*/

public String getEncString(String strMing) {

byte[] byteMi = null;

byte[] byteMing = null;

String strMi = "";

BASE64Encoder base64en = new BASE64Encoder();

try {

byteMing = strMing.getBytes("UTF8");

byteMi = this.getEncCode(byteMing);

strMi = base64en.encode(byteMi);

} catch (Exception e) {

e.printStackTrace();

} finally {

base64en = null;

byteMing = null;

byteMi = null;

}

return strMi;

}

/**

* 解密 以String密文输入,String明文输出

*

* @param strMi

* @return

*/

public String getDesString(String strMi) {

BASE64Decoder base64De = new BASE64Decoder();

byte[] byteMing = null;

byte[] byteMi = null;

String strMing = "";

try {

byteMi = base64De.decodeBuffer(strMi);

byteMing = this.getDesCode(byteMi);

strMing = new String(byteMing, "UTF8");

} catch (Exception e) {

e.printStackTrace();

} finally {

base64De = null;

byteMing = null;

byteMi = null;

}

return strMing;

}

/**

* 加密以byte[]明文输入,byte[]密文输出

*

* @param byteS

* @return

*/

private byte[] getEncCode(byte[] byteS) {

byte[] byteFina = null;

Cipher cipher;

try {

cipher = Cipher.getInstance("DES");

cipher.init(Cipher.ENCRYPT_MODE, key);

byteFina = cipher.doFinal(byteS);

} catch (Exception e) {

e.printStackTrace();

} finally {

cipher = null;

}

return byteFina;

}

/**

* 解密以byte[]密文输入,以byte[]明文输出

*

* @param byteD

* @return

*/

private byte[] getDesCode(byte[] byteD) {

Cipher cipher;

byte[] byteFina = null;

try {

cipher = Cipher.getInstance("DES");

cipher.init(Cipher.DECRYPT_MODE, key);

byteFina = cipher.doFinal(byteD);

} catch (Exception e) {

e.printStackTrace();

} finally {

cipher = null;

}

return byteFina;

}

public static void main(String[] args) {

System.out.println("des demo");

DesEncrypt des = new DesEncrypt();// 实例化一个对像

des.getKey("MYKEY");// 生成密匙

System.out.println("key=MYKEY");

String strEnc = des.getEncString("111111");// 加密字符串,返回String的密文

System.out.println("密文=" + strEnc);

String strDes = des.getDesString(strEnc);// 把String 类型的密文解密

System.out.println("明文=" + strDes);

}

}

求java加密源代码(MD5,base64)

import java.security.*;

import javax.crypto.*;

/**

* 本例解释如何利用DES私钥加密算法加解密

*

* @author Devon

* @version 1.0 04/03/10

*/

public class SingleKeyExample {

public static void main(String[] args) {

try {

String algorithm = "DES"; //定义加密算法,可用 DES,DESede,Blowfish

String message = "Hello World. 这是待加密的信息";

// 生成个DES密钥

KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);

keyGenerator.init(56); //选择DES算法,密钥长度必须为56位

Key key = keyGenerator.generateKey(); //生成密钥

// 生成Cipher对象

Cipher cipher = Cipher.getInstance("DES");

//用密钥加密明文(message),生成密文(cipherText)

cipher.init(Cipher.ENCRYPT_MODE, key); //操作模式为加密(Cipher.ENCRYPT_MODE),key为密钥

byte[] cipherText = cipher.doFinal(message.getBytes()); //得到加密后的字节数组

System.out.println("加密后的信息: " + new String(cipherText));

//用密钥加密明文(plainText),生成密文(cipherByte)

cipher.init(Cipher.DECRYPT_MODE, key); //操作模式为解密,key为密钥

byte[] sourceText = cipher.doFinal(cipherText); //获得解密后字节数组

System.out.println("解密后的信息: " + new String(sourceText));

} catch (Exception ex) {

ex.printStackTrace();

}

}

}

/**

* @author Devon

*/

import java.security.*;

import java.security.spec.*;

import javax.crypto.*;

public class PairKeyExample {

public static void main(String argv[]) {

try {

String algorithm = "RSA"; //定义加密算法,可用 DES,DESede,Blowfish

String message = "张三,你好,我是李四";

//产生张三的密钥对(keyPairZhang)

KeyPairGenerator keyGeneratorZhang =

KeyPairGenerator.getInstance(algorithm); //指定采用的算法

keyGeneratorZhang.initialize(1024); //指定密钥长度为1024位

KeyPair keyPairZhang = keyGeneratorZhang.generateKeyPair(); //产生密钥对

System.out.println("生成张三的公钥对");

// 张三生成公钥(publicKeyZhang)并发送给李四,这里发送的是公钥的数组字节

byte[] publicKeyZhangEncode = keyPairZhang.getPublic().getEncoded();

//通过网络或磁盘等方式,把公钥编码传送给李四

//李四接收到张三编码后的公钥,将其解码

KeyFactory keyFacoryLi = KeyFactory.getInstance(algorithm); //得到KeyFactory对象

X509EncodedKeySpec x509KeySpec =

new X509EncodedKeySpec(publicKeyZhangEncode); //公钥采用X.509编码

PublicKey publicKeyZhang = keyFacoryLi.generatePublic(x509KeySpec); //将公钥的KeySpec对象转换为公钥

System.out.println("李四成功解码,得到张三的公钥");

//李四用张三的公钥加密信息,并发送给李四

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); //得到Cipher对象

cipher.init(Cipher.ENCRYPT_MODE, publicKeyZhang); //用张三的公钥初始化Cipher对象

byte[] cipherMessage = cipher.doFinal(message.getBytes()); //得到加密信息

System.out.println("加密后信息:" + new String(cipherMessage));

System.out.println("加密完成,发送给李四...");

//张三用自己的私钥解密从李四处收到的信息

cipher.init(Cipher.DECRYPT_MODE, keyPairZhang.getPrivate()); //张三用其私钥初始化Cipher对象

byte[] originalMessage = cipher.doFinal(cipherMessage); //得到解密后信息

System.out.println("张三收到信息,解密后为:" + new String(originalMessage));

} catch (Exception ex) {

ex.printStackTrace();

}

}

}

用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;

import com.huateng.util.common.Log;

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();

Log.sKeyPath(path);

} 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();

Log.sKeyPath(path);

} 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/");

}

}

/*加解密*/

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;

public class SecUtil {

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) {

throw new RuntimeException(ey1);

}

catch (Exception ey2) {

throw new RuntimeException(ey2);

}

//用key产生Cipher

Cipher cipher = null;

try {

//设置算法,应该与加密时的设置一样

cipher = Cipher.getInstance("DES");

//设置解密模式

cipher.init(Cipher.DECRYPT_MODE, key);

}

catch (Exception ey3) {

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) {

throw new RuntimeException(ey5);

}

}

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) {

throw new RuntimeException(ey1);

}

catch (Exception ey2) {

throw new RuntimeException(ey2);

}

//用key产生Cipher

Cipher cipher = null;

try {

//设置算法,应该与加密时的设置一样

cipher = Cipher.getInstance("DES");

//设置解密模式

cipher.init(Cipher.ENCRYPT_MODE, key);

}

catch (Exception ey3) {

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) {

throw new RuntimeException(ey5);

}

}

}

java des 加密 解密 密钥随机取得方法

java DES 加密 解密 生成随机密钥

举例说明:

//保存生成的key

public static void saveDesKey() {

try {

SecureRandom sr = new SecureRandom();

// 选择的DES算法生成一个KeyGenerator对象

KeyGenerator kg = KeyGenerator.getInstance("DES");

kg.init(sr);

// 相对路径 需要新建 conf 文件夹

// String fileName = "conf/DesKey.xml";

// 绝对路径

String fileName = "d:/DesKey.xml";

FileOutputStream fos = new FileOutputStream(fileName);

ObjectOutputStream oos = new ObjectOutputStream(fos);

// 生成密钥

Key key = kg.generateKey();

oos.writeObject(key);

oos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

//获取生成的key

public static Key getKey() {

Key kp = null;

try {

// 相对路径 需要新建 conf 文件夹

// String fileName = "conf/DesKey.xml";

// InputStream is = Encrypt.class.getClassLoader().getResourceAsStream(fileName);

// 绝对路径

String fileName = "d:/DesKey.xml";

FileInputStream is = new FileInputStream(fileName);

ObjectInputStream oos = new ObjectInputStream(is);

kp = (Key) oos.readObject();

oos.close();

} catch (Exception e) {

e.printStackTrace();

}

return kp;

}

//加密开始

public static void encrypt(String file, String dest) throws Exception {

Cipher cipher = Cipher.getInstance("DES");

cipher.init(Cipher.ENCRYPT_MODE, getKey());

InputStream is = new FileInputStream(file);

OutputStream out = new FileOutputStream(dest);

CipherInputStream cis = new CipherInputStream(is, cipher);

byte[] buffer = new byte[1024];

int r;

while ((r = cis.read(buffer)) 0) {

out.write(buffer, 0, r);

}

cis.close();

is.close();

out.close();

}

//解密开始

public static void decrypt(String file, String dest) throws Exception {

Cipher cipher = Cipher.getInstance("DES");

cipher.init(Cipher.DECRYPT_MODE, getKey());

InputStream is = new FileInputStream(file);

OutputStream out = new FileOutputStream(dest);

CipherOutputStream cos = new CipherOutputStream(out, cipher);

byte[] buffer = new byte[1024];

int r;

while ((r = is.read(buffer)) = 0) {

cos.write(buffer, 0, r);

}

cos.close();

out.close();

is.close();

}

}

//des加密主方法

public class DES {

public static void main(String[] args) throws Exception {

Encrypt.saveDesKey();

System.out.println("生成key");

Encrypt.getKey();

System.out.println("获取key");

Encrypt.encrypt("d:\\hello.txt", "d:\\encrypt.txt");

System.out.println("加密");

Encrypt.decrypt("d:\\encrypt.txt", "d:\\decrypt.txt");

System.out.println("解密");

}

以上方法亲测可用。


文章题目:java生成密钥源代码 java密钥库
网页链接:http://cdxtjz.cn/article/doddpdd.html

其他资讯