首页 > 编程知识 正文

用java实现des解密,java的des解密报错given

时间:2023-12-27 22:27:38 阅读:326437 作者:RINA

本文目录一览:

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解密后的文件

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要怎么实现zeropadding的des解密

package com.va.util;

import com.zoki.util.Charset;

import java.security.InvalidAlgorithmParameterException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.crypto.BadPaddingException;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.SecretKeyFactory;

import javax.crypto.SecretKey;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.spec.IvParameterSpec;

/**

 * 注意:DES加密和解密过程中,密钥长度都必须是8的倍数。br

 * 当默认用DES,JAVA会用ECB模式,因此这里IV向量没有作用,这里,但当用CBC模式下,如果还是用SecureRandom,

 * 则每次加密的结果都会不一样,因为JAVA内部会用随机的IV来初始化Cipher对象,如示例代码,

 * 由于Cipher.getInstance("DES/CBC/PKCS5Padding")使用了CBC,

 * 因此我这里用的javax.crypto.spec.IvParameterSpec包下的IvParameterSpec来初始化向量IVbr

 * JAVA中默认的算法为ECB,默认填充方式为PKCS5Padding

 */

public class DES {

    private DES() {

    }

    /**

     * 加密

     *

     * @param src byte[] 加密的数据源

     * @param password byte[] 加密秘钥

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

     */

    public static byte[] encrypt(byte[] src, byte[] password) {

        try {

            DESKeySpec desKey = new DESKeySpec(password);

            //创建一个密匙工厂,然后用它把DESKeySpec转换成

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

            SecretKey securekey = keyFactory.generateSecret(desKey);

            //Cipher对象实际完成加密操作

            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

            //ECB模式下,iv不需要

            IvParameterSpec iv = new IvParameterSpec(password);

            //用密匙初始化Cipher对象

            cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);

            //现在,获取数据并加密

            //正式执行加密操作

            return cipher.doFinal(src);

        } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException ex) {

            Logger.getLogger(DES.class.getName()).log(Level.SEVERE, null, ex);

        }

        return null;

    }

    /**

     * 加密

     *

     * @param src byte[] 加密的数据源

     * @param password String 加密秘钥

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

     */

    public static byte[] encrypt(byte[] src, String password) {

        byte[] keyBytes = password.getBytes(Charset.utf8);

        return encrypt(src, keyBytes);

    }

    /**

     * 解密

     *

     * @param src byte[] 解密的数据源

     * @param password byte[] 解密秘钥

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

     */

    public static byte[] decrypt(byte[] src, byte[] password) {

        try {

            // DES算法要求有一个可信任的随机数源

            //SecureRandom random = new SecureRandom();

            // 创建一个DESKeySpec对象

            DESKeySpec desKey = new DESKeySpec(password);

            // 创建一个密匙工厂

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

            // 将DESKeySpec对象转换成SecretKey对象

            SecretKey securekey = keyFactory.generateSecret(desKey);

            // Cipher对象实际完成解密操作,CBC为加密模式,

            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

            //ECB模式下,iv不需要

            IvParameterSpec iv = new IvParameterSpec(password);

            // 用密匙初始化Cipher对象

            cipher.init(Cipher.DECRYPT_MODE, securekey, iv);

            // 真正开始解密操作

            return cipher.doFinal(src);

        } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) {

            Logger.getLogger(DES.class.getName()).log(Level.SEVERE, null, ex);

        }

        return null;

    }

    /**

     * 解密

     *

     * @param src byte[] 解密的数据源

     * @param password String 解密秘钥

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

     */

    public static byte[] decrypt(byte[] src, String password) {

        byte[] keyBytes = password.getBytes(Charset.utf8);

        return decrypt(src, keyBytes);

    }

}

求用JAVA实现的DES算法

package des;

import java.io.*;

import java.nio.*;

import java.nio.channels.FileChannel;

public class FileDES{

private static final boolean enc=true; //加密

private static final boolean dec=false; //解密

private String srcFileName;

private String destFileName;

private String inKey;

private boolean actionType;

private File srcFile;

private File destFile;

private Des des;

private void analyzePath(){

String dirName;

int pos=srcFileName.lastIndexOf("/");

dirName=srcFileName.substring(0,pos);

File dir=new File(dirName);

if (!dir.exists()){

System.err.println(dirName+" is not exist");

System.exit(1);

}else if(!dir.isDirectory()){

System.err.println(dirName+" is not a directory");

System.exit(1);

}

pos=destFileName.lastIndexOf("/");

dirName=destFileName.substring(0,pos);

dir=new File(dirName);

if (!dir.exists()){

if(!dir.mkdirs()){

System.out.println ("can not creat directory:"+dirName);

System.exit(1);

}

}else if(!dir.isDirectory()){

System.err.println(dirName+" is not a directory");

System.exit(1);

}

}

private static int replenish(FileChannel channel,ByteBuffer buf) throws IOException{

long byteLeft=channel.size()-channel.position();

if(byteLeft==0L)

return -1;

buf.position(0);

buf.limit(buf.position()+(byteLeft8 ? (int)byteLeft :8));

return channel.read(buf);

}

private void file_operate(boolean flag){

des=new Des(inKey);

FileOutputStream outputFile=null;

try {

outputFile=new FileOutputStream(srcFile,true);

}catch (java.io.FileNotFoundException e) {

e.printStackTrace(System.err);

}

FileChannel outChannel=outputFile.getChannel();

try{

if(outChannel.size()%2!=0){

ByteBuffer bufTemp=ByteBuffer.allocate(1);

bufTemp.put((byte)32);

bufTemp.flip();

outChannel.position(outChannel.size());

outChannel.write(bufTemp);

bufTemp.clear();

}

}catch(Exception ex){

ex.printStackTrace(System.err);

System.exit(1);

}

FileInputStream inFile=null;

try{

inFile=new FileInputStream(srcFile);

}catch(java.io.FileNotFoundException e){

e.printStackTrace(System.err);

//System.exit(1);

}

outputFile=null;

try {

outputFile=new FileOutputStream(destFile,true);

}catch (java.io.FileNotFoundException e) {

e.printStackTrace(System.err);

}

FileChannel inChannel=inFile.getChannel();

outChannel=outputFile.getChannel();

ByteBuffer inBuf=ByteBuffer.allocate(8);

ByteBuffer outBuf=ByteBuffer.allocate(8);

try{

String srcStr;

String destStr;

while(true){

if (replenish(inChannel,inBuf)==-1) break;

srcStr=((ByteBuffer)(inBuf.flip())).asCharBuffer().toString();

inBuf.clear();

if (flag)

destStr=des.enc(srcStr,srcStr.length());

else

destStr=des.dec(srcStr,srcStr.length());

outBuf.clear();

if (destStr.length()==4){

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

outBuf.putChar(destStr.charAt(i));

}

outBuf.flip();

}else{

outBuf.position(0);

outBuf.limit(2*destStr.length());

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

outBuf.putChar(destStr.charAt(i));

}

outBuf.flip();

}

try {

outChannel.write(outBuf);

outBuf.clear();

}catch (java.io.IOException ex) {

ex.printStackTrace(System.err);

}

}

System.out.println (inChannel.size());

System.out.println (outChannel.size());

System.out.println ("EoF reached.");

inFile.close();

outputFile.close();

}catch(java.io.IOException e){

e.printStackTrace(System.err);

System.exit(1);

}

}

public FileDES(String srcFileName,String destFileName,String inKey,boolean actionType){

this.srcFileName=srcFileName;

this.destFileName=destFileName;

this.actionType=actionType;

analyzePath();

srcFile=new File(srcFileName);

destFile=new File(destFileName);

this.inKey=inKey;

if (actionType==enc)

file_operate(enc);

else

file_operate(dec);

}

public static void main(String[] args){

String file1=System.getProperty("user.dir")+"/111.doc";

String file2=System.getProperty("user.dir")+"/222.doc";

String file3=System.getProperty("user.dir")+"/333.doc";

String passWord="1234ABCD";

FileDES fileDes=new FileDES(file1,file2,passWord,true);

FileDES fileDes1=new FileDES(file2,file3,passWord,false);

}

用java实现des加密和解密

一个用DES来加密、解密的类

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;

}

比较长, 转了一部分.

如何使用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

*/

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!");

}

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。