「javades密钥生成」des密钥生成过程

博主:adminadmin 2022-12-26 19:09:08 65

今天给各位分享javades密钥生成的知识,其中也会对des密钥生成过程进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

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

}

}

}

des密钥如何生成 java

package Encrypt;

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密码加密与解密

以下两个类可以很方便的完成字符串的加密和解密

加密 CryptHelper encrypt(password)

解密 CrypHelper decrypt(password)

代码如下

CryptUtils java

[java]

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密钥

*

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

* @throws exception

*             扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (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 ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

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

*

* @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 ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

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

*

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

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

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;il;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

//      return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

//      System out println(decoder decodeBuffer(value))

//      return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密钥

*

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

* @throws exception

*             扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (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 ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

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

*

* @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 ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

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

*

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

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

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;il;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

//  return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

//  System out println(decoder decodeBuffer(value))

//  return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

CryptHelper java

[java]

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes  = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

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

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

}

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes  = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

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

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

lishixinzhi/Article/program/Java/hx/201311/26449

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("解密");

}

以上方法亲测可用。

关于javades密钥生成和des密钥生成过程的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-12-26,除非注明,否则均为首码项目网原创文章,转载请注明出处。