导航:首页 > 编程语言 > jsjavades加密解密

jsjavades加密解密

发布时间:2022-05-14 15:41:17

❶ (高分)javascript实现des加密

搞定,已经可以了

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<title>DES算法-Code by 梅雪香</title>
<style type="text/css">
textarea{width:600px; height:150px;}
body{font-size:12px}
input{font-size:12px}
</style>
<script language="JavaScript">
<!--
var DES = {
// initial permutation IP
IP_Table : [
58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7
],
// final permutation IP^-1
IPR_Table : [
40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25
],
// permuted choice table (key)
PC1_Table : [
57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4
],
// permuted choice key (table)
PC2_Table : [
14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32
],
// number left rotations of pc1
LOOP_Table : [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1],
// expansion operation matrix
E_Table : [
32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1
],
// 32-bit permutation function P used on the output of the S-boxes
P_Table : [ 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 ],

// The (in)famous S-boxes
S_Box : [
// S1
[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]],
// S2
[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
[ 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
[ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]],
// S3
[[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[ 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]],
// S4
[[ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[ 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]],
// S5
[[ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]],
// S6
[[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[ 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]],
// S7
[[ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[ 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]],
// S8
[[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
[ 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]]
],
Oct2Bin : ["0000","0001","0010","0011","0100","0101","0110","0111",
"1000","1001","1010","1011","1100","1101","1110","1111" ],
//str 为八位的字符
subKeys : new Array(16),
key : "",
text : ""
};

DES.init = function(key,text){
if(key != this.key){
this.key=key;
this.GenSubKey();
}
this.text= text + " ".substring(0,parseInt("07654321".charAt( text.length%8 ),10));
};

DES.GenSubKey = function(){
var arr = this.Permute( this.Byte2Bit(this.key) , this.PC1_Table);
var AL = arr.slice(0,28);
var AR = arr.slice(28,56);
for(var i=0; i<16; i++) {
for(var j=0,k=this.LOOP_Table[i];j<k;j++){
AL.push(AL.shift());
AR.push(AR.shift());
}
this.subKeys[i] = this.Permute( AL.concat(AR) , this.PC2_Table );
}
};
//数组ar存储二进制数据,该函数将从头开始的每八位转换成对应的字符
DES.Bit2Byte = function(ar,fCh){
var str="";
if(fCh == "byte"){
var tmpAr = ar.join("").match(/.{8}/g);
for(var i=0,j=tmpAr.length; i<j; i++)
str += String.fromCharCode(parseInt(tmpAr[i],2));
}
else if(fCh == "hex"){
var tmpAr = ar.join("").match(/.{4}/g);
for(var i=0,j=tmpAr.length; i<j; i++)
str += "0123456789abcdef".charAt(parseInt(tmpAr[i],2));
}
else return "Error:Second param is wrong.";
return str;
};
//将字符串转换成二进制数组
DES.Byte2Bit = function(str){
for(var i=0,j=8*str.length,ar = [],ch=""; i<j; i++){
var k = 7 - i%8;
if(k == 7) ch = str.charCodeAt(parseInt(i/8,10));
ar.push( (ch >> k) & 1 );
}
return ar;
};

//将16进制字符串转变成二进制数组
DES.Hex2Bin = function(str){
for(var i=0,j=str.length,s=""; i<j; i++)
s += this.Oct2Bin[ parseInt(str.charAt(i),16)];
return s.split("");
};

DES.Xor = function(A,B){
for(var i=0,j=B.length,rtn=new Array(j); i<j; i++)
rtn[i] = A[i] ^ B[i];
return rtn;
}

DES.Permute = function(ar,tb){
for(var i=0,j=tb.length,rtn=new Array(j);i<j;i++)
rtn[i] = ar[tb[i]-1];
return rtn;
};

DES.F_func = function(Ri,Ki)
{
return this.Permute( this.S_func( this.Xor( this.Permute( Ri , this.E_Table ) , Ki) ) , this.P_Table);
};
//ar为输入48位串数组
DES.S_func = function(ar){
for(var i=0,arRtn = [];i<8;i++){
var x = i*6;
var j = parseInt(""+ar[x]+ar[x+5],2);
var k = parseInt(ar.slice(x+1,x+5).join(""),2);
arRtn = arRtn.concat( this.Oct2Bin[ this.S_Box[i][j][k] ].split("") );
}
return arRtn;
}

//mode参数为处理模式."Encrypt":加密 "Decrypt":解密,默认为加密
DES.Encrypt = function(mode){
mode = mode?mode:"Encrypt";
if(mode=="Decrypt")
var plainTextAr = this.Hex2Bin(this.text).join("").match(/.{64}/g);
else
var plainTextAr = this.Byte2Bit(this.text).join("").match(/.{64}/g);
for(var i=0,j=plainTextAr.length;i<j;i++){
var arr = this.Permute(plainTextAr[i].split(""),this.IP_Table)
var AL = arr.slice(0,32);
var AR = arr.slice(32,64);
if(mode == "Decrypt"){
for(var k=15;k>-1;k--){
var tmp = AR.slice(0,32);
AR = this.Xor(this.F_func(AR,this.subKeys[k]) , AL);
AL = tmp;
}
}
else{
for(var k=0;k<16;k++){
var tmp = AR.slice(0,32);
AR = this.Xor(this.F_func(AR,this.subKeys[k]) , AL);
AL = tmp;
}
}
plainTextAr[i] = this.Bit2Byte(this.Permute(AR.concat(AL), this.IPR_Table),(mode=="Decrypt"?"byte":"hex"));
}
return plainTextAr.join("").trim();
}
String.prototype.trim = function(){ return this.replace(/\s+$/g,"");}
//-->
</script>

<script language="JavaScript">
<!--
var $ = document.getElementById;
function jiami(){
DES.init($("txtKey").value,encodeURI($("taText").value) );
$("taCipher").value = DES.Encrypt();
}
function jiemi(){
DES.init($("txtKey").value,$("taCipher").value );
$("taText").value =decodeURI(DES.Encrypt("Decrypt"));
}
//-->
</script>
</head>

<body>
请输入加(解)密密钥:<input id="txtKey" type="text" onfocus="this.select()" value="47944980" size="10">
<font color="red">(*目前密钥只能是八位)</font><br>

未加密文本:<br>
<textarea id="taText">Hi,I'm meixuexiang.</textarea>
<input type="button" value="clear" onclick="document.all[this.sourceIndex-1].value=''"><br>
<input type="button" value="Encrypt" onclick="jiami()">
<input type="button" value="Decrypt" onclick="jiemi()"><br><br>
加密后文本:<br>
<textarea id="taCipher"></textarea>
<input type="button" value="clear" onclick="document.all[this.sourceIndex-1].value=''"><br>
<p>code by meixx(<a href="http://www.blogjava.net/mxx">梅雪香</a>) 2006-10-18 23:00 <a href="mailto:[email protected]">信息反馈</a></p>
</body>
</html>

❷ 如何使用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!");
}
}
}

❸ 为什么 CryptoJS DES 加密的结果和 Java DES 不一样

最近需要对数据进行加密/解密, 因此选用了CryptoJS库, 对数据做DES算法的加密/解密

首选查看官方示例, 将密文进行Base64编码, 掉进一个大坑
<script src="htt p:/ /crypto-js.googlecod e.c om/svn/tags/3.1.2/build/rollups/tripledes.js"></script>
<script>
var encrypted = CryptoJS.DES.encrypt("Message", "Secret Passphrase");
// ciphertext changed every time you run it
// 加密的结果不应该每次都是一样的吗?
console.log(encrypted.toString(), encrypted.ciphertext.toString(CryptoJS.enc.Base64));
var decrypted = CryptoJS.DES.decrypt(encrypted, "Secret Passphrase");
console.log(decrypted.toString(CryptoJS.enc.Utf8));
</script>

对这些加密算法不了解, 只能求助Google
des encrypion: js encrypted value does not match the java encrypted value
In cryptoJS you have to convert the key to hex and useit as word just like above (otherwise it will be considered as passphrase)
For the key, when you pass a string, it's treated as a passphrase and used to derive an actual key and IV. Or you can pass a WordArray that represents the actual key.

原来是我指定key的方式不对, 直接将字符串做为参数, 想当然的以为这就是key, 其实不然, CryptoJS会根据这个字符串算出真正的key和IV(各种新鲜名词不解释, 问我也没用, 我也不懂 -_-")

那么我们只需要将key和iv对应的字符串转成CryptoJS的WordArray类型, 在DES加密时做为参数传入即可, 这样对Message这个字符串加密, 每次得到的密文都是YOa3le0I+dI=
var keyHex = CryptoJS.enc.Utf8.parse('abcd1234');
var ivHex = CryptoJS.enc.Utf8.parse('inputvec');
var encrypted = CryptoJS.DES.encrypt('Message', keyHex, { iv: ivHex });

这样是不是就万事OK了? 哪有, 谁知道这坑是一个接一个啊.
我们再试试Java这边的DES加密是不是和这个结果一样, 具体实现请参考Simple Java Class to DES Encrypt Strings

果真掉坑里了, Java通过DES加密Message这个字符串得到的结果是8dKft9vkZ4I=和CryptoJS算出来的不一样啊...亲

继续求助Google
C# and Java DES Encryption value are not identical
SunJCE provider uses ECB as the default mode, and PKCS5Padding as the default padding scheme for DES.(JCA Doc)
This means that in the case of the SunJCE provider,
Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");
and
Cipher c1 = Cipher.getInstance("DES");
are equivalent statements.

原来是CryptoJS进行DES加密时, 默认的模式和padding方式和Java默认的不一样造成的, 必须使用ECB mode和PKCS5Padding, 但是CryptoJS中只有Pkcs7, 不管了, 试试看...
<script src="htt p:/ /crypto-js.googleco de.c om/svn/tags/3.1.2/build/rollups/tripledes.js"></script>
<script src="ht tp:/ /crypto-js.googleco de.c om/svn/tags/3.1.2/build/components/mode-ecb.js"></script>
<script>
var keyHex = CryptoJS.enc.Utf8.parse('abcd1234');
var encrypted = CryptoJS.DES.encrypt('Message', keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log(encrypted.toString(), encrypted.ciphertext.toString(CryptoJS.enc.Base64));
</script>

咦...使用Pkcs7能得到和Java DES一样的结果了, 哇塞...好神奇
那我们试试统一Java也改成Cipher.getInstance("DES/ECB/PKCS7Padding")试试, 结果得到一个大大的错误
Error:java.security.NoSuchAlgorithmException: Cannot find any provider supporting DES/ECB/PKCS7Padding

没办法, 继续Google
java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/ECB/PKCS7PADDING
I will point out that PKCS#5 and PKCS#7 actually specify exactly the same type of padding (they are the same!), but it's called #5 when used in this context. :)

这位大侠给出的解释是: PKCS#5和PKCS#7是一样的padding方式, 对加密算法一知半解, 我也只能暂且认可这个解释了.

忙完了DES的加密, 接下来就是使用CryptoJS来解密了. 我们需要直接解密DES加密后的base64密文字符串. CryptoJS好像没有提供直接解密DES密文字符串的方法啊, 他的整个加密/解密过程都是内部自己在玩, 解密时需要用到加密的结果对象, 这不是坑我吗?

只好研究下CryptoJS DES加密后返回的对象, 发现有一个属性ciphertext, 就是密文的WordArray, 那么解密的时候, 我们是不是只要提供这个就行了呢?
var keyHex = CryptoJS.enc.Utf8.parse('abcd1234');
// direct decrypt ciphertext
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse('8dKft9vkZ4I=')
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log(decrypted.toString(CryptoJS.enc.Utf8));

果不其然, 到此为止, 问题全部解决, 豁然开朗...

完整代码请参考CryptoJS-DES.html
Use CryptoJS encrypt message by DES and direct decrypt ciphertext, compatible with Java Cipher.getInstance("DES")

❹ Java用Des方式加密之后,php怎么解密

DES是一种标准的数据加密算法,关于这个算法的详细介绍可以参考wiki和网络:
php中有一个扩展可以支持DES的加密算法,是:extension=php_mcrypt.dll
在配置文件中将这个扩展打开还不能够在windows环境下使用
需要将PHP文件夹下的 libmcrypt.dll 拷贝到系统的 system32 目录下,这是通过phpinfo可以查看到mcrypt表示这个模块可以正常试用了。
下面是PHP中使用DES加密解密的一个例子:
//$input - stuff to decrypt
//$key - the secret key to use
function do_mencrypt($input, $key)
{
$input = str_replace(""n", "", $input);
$input = str_replace(""t", "", $input);
$input = str_replace(""r", "", $input);
$key = substr(md5($key), 0, 24);
$td = mcrypt_mole_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
return trim(chop(base64_encode($encrypted_data)));
}
//$input - stuff to decrypt
//$key - the secret key to use
function do_mdecrypt($input, $key)
{
$input = str_replace(""n", "", $input);
$input = str_replace(""t", "", $input);
$input = str_replace(""r", "", $input);
$input = trim(chop(base64_decode($input)));
$td = mcrypt_mole_open('tripledes', '', 'ecb', '');
$key = substr(md5($key), 0, 24);
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
return trim(chop($decrypted_data));
}

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

比较长, 转了一部分.

❻ 求一个java des32加密解密算法

packagecn.xinxi.des;

importjava.security.Key;
importjava.security.Security;

importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.SecretKey;
importjavax.crypto.SecretKeyFactory;
importjavax.crypto.spec.DESKeySpec;
importorg.apache.commons.codec.binary.Hex;
importorg.bouncycastle.jce.provider.BouncyCastleProvider;


publicclassDES{
privatestaticfinalStringstr="xinxi";
publicstaticvoidmain(String[]args)throwsException{
jdkDES();
bcDES();
}
publicstaticvoidjdkDES()throwsException{
//生成key
//KeyGenerator,密钥生成器
KeyGeneratorkeyGenerator=KeyGenerator.getInstance("DES");
keyGenerator.init(56);//指定keysize这里使用默认值56位
//声称密钥
SecretKeysecreKey=keyGenerator.generateKey();
byte[]bytesKey=secreKey.getEncoded();

//key转换(恢复密钥)
// SecretKeyconvertSecreKey=newSecretKeySpec(bytesKey,"DES");//与下面三行效果貌似差不多
DESKeySpecdesKeySpec=newDESKeySpec(bytesKey);
SecretKeyFactoryfactory=SecretKeyFactory.getInstance("DES");
// System.out.println(keyGenerator.getProvider());
KeyconvertSecreKey=factory.generateSecret(desKeySpec);

//加密
Ciphercipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加密算法/工作方式/填充方式
cipher.init(Cipher.ENCRYPT_MODE,convertSecreKey);//模式(此处是加密模式)、key
byte[]result=cipher.doFinal(str.getBytes());//参数是要被加密的内容
System.out.println("JDKDES加密结果:"+Hex.encodeHexString(result));//转成16进制

//解密生成key和key转换与加密一样
cipher.init(Cipher.DECRYPT_MODE,convertSecreKey);//模式(此处是解密模式)、key
result=cipher.doFinal(result);
System.out.println("JDKDES解密结果:"+newString(result));
}
publicstaticvoidbcDES()throwsException{
Security.addProvider(newBouncyCastleProvider());

//生成key
KeyGeneratorkeyGenerator=KeyGenerator.getInstance("DES","BC");
// System.out.println(keyGenerator.getProvider());
keyGenerator.init(56);//指定keysize这里使用默认值56位
SecretKeysecreKey=keyGenerator.generateKey();
byte[]bytesKey=secreKey.getEncoded();

//key转换
DESKeySpecdesKeySpec=newDESKeySpec(bytesKey);
SecretKeyFactoryfactory=SecretKeyFactory.getInstance("DES");
KeyconvertSecreKey=factory.generateSecret(desKeySpec);

//加密
Ciphercipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加密算法/工作方式/填充方式
cipher.init(Cipher.ENCRYPT_MODE,convertSecreKey);//模式(此处是加密模式)、key
byte[]result=cipher.doFinal(str.getBytes());//参数是要被加密的内容
System.out.println("BCDES加密结果:"+Hex.encodeHexString(result));//转成16进制

//解密生成key和key转换与加密一样
cipher.init(Cipher.DECRYPT_MODE,convertSecreKey);//模式(此处是解密模式)、key
result=cipher.doFinal(result);
System.out.println("BCDES解密结果:"+newString(result));
}
}

是你想要的么?

❼ 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 DES加密解密算法

bcprov-ext-jdk16-143.jar
应该放到你应用的classpath下。放ext中,修改java.security 我在windows系统下居然无效的。但在linux/unix下是好的

❿ 如何用JAVA实现字符串简单加密解密

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

阅读全文

与jsjavades加密解密相关的资料

热点内容
手机号码如何加密 浏览:424
沈阳程序员培训学校 浏览:538
一般服务器如何配置 浏览:895
图片怎样加密发邮件 浏览:619
万虹电脑文件夹密码忘记了怎么办 浏览:631
rc108单片机 浏览:867
战雷如何改变服务器 浏览:674
mactelnet命令 浏览:51
压缩袋压缩了拿出来 浏览:401
安卓手机相机怎么设置权限 浏览:121
美女程序员转行做主播 浏览:671
办理解压房产 浏览:575
道路工程概论pdf 浏览:388
超棒数学速算法大全 浏览:937
小米易语言登录源码 浏览:31
砖墙内加密钢筋 浏览:992
乡关何处pdf 浏览:84
小猪领赞小程序源码 浏览:336
python曲线如何原路返回 浏览:431
pdf快速看图破解版 浏览:295