導航:首頁 > 編程語言 > java的crypt

java的crypt

發布時間:2023-03-08 07:16:45

java怎麼實現php 的crypt

/****************************************************************************
*JCrypt.java
*
*Java-
*
*,[email protected]
*
****************************************************************************/

publicclassJCrypt
{
privateJCrypt(){}

=16;

privatestaticfinalintcon_salt[]=
{
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,
0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,
0x0A,0x0B,0x05,0x06,0x07,0x08,0x09,0x0A,
0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,
0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,
0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22,
0x23,0x24,0x25,0x20,0x21,0x22,0x23,0x24,
0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,
0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,
0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,
0x3D,0x3E,0x3F,0x00,0x00,0x00,0x00,0x00,
};


privatestaticfinalintcov_2char[]=
{
0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,
0x36,0x37,0x38,0x39,0x41,0x42,0x43,0x44,
0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,
0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,
0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62,
0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,
0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,
0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A
};

(byteb)
{
intvalue=(int)b;

return(value>=0?value:value+256);
}

(byteb[],intoffset)
{
intvalue;

value=byteToUnsigned(b[offset++]);
value|=(byteToUnsigned(b[offset++])<<8);
value|=(byteToUnsigned(b[offset++])<<16);
value|=(byteToUnsigned(b[offset++])<<24);

return(value);
}

(intiValue,byteb[],intoffset)
{
b[offset++]=(byte)((iValue)&0xff);
b[offset++]=(byte)((iValue>>>8)&0xff);
b[offset++]=(byte)((iValue>>>16)&0xff);
b[offset++]=(byte)((iValue>>>24)&0xff);
}

privatestaticfinalvoidPERM_OP(inta,intb,intn,intm,intresults[])
{
intt;

t=((a>>>n)^b)&m;
a^=t<<n;
b^=t;

results[0]=a;
results[1]=b;
}

privatestaticfinalintHPERM_OP(inta,intn,intm)
{
intt;

t=((a<<(16-n))^a)&m;
a=a^t^(t>>>(16-n));

return(a);
}

privatestaticint[]des_set_key(bytekey[])
{
intschele[]=newint[ITERATIONS*2];

intc=fourBytesToInt(key,0);
intd=fourBytesToInt(key,4);

intresults[]=newint[2];

PERM_OP(d,c,4,0x0f0f0f0f,results);
d=results[0];c=results[1];

c=HPERM_OP(c,-2,0xcccc0000);
d=HPERM_OP(d,-2,0xcccc0000);

PERM_OP(d,c,1,0x55555555,results);
d=results[0];c=results[1];

PERM_OP(c,d,8,0x00ff00ff,results);
c=results[0];d=results[1];

PERM_OP(d,c,1,0x55555555,results);
d=results[0];c=results[1];

d=(((d&0x000000ff)<<16)|(d&0x0000ff00)|
((d&0x00ff0000)>>>16)|((c&0xf0000000)>>>4));
c&=0x0fffffff;

ints,t;
intj=0;

for(inti=0;i<ITERATIONS;i++)
{
if(shifts2[i])
{
c=(c>>>2)|(c<<26);
d=(d>>>2)|(d<<26);
}
else
{
c=(c>>>1)|(c<<27);
d=(d>>>1)|(d<<27);
}

c&=0x0fffffff;
d&=0x0fffffff;

s=skb[0][(c)&0x3f]|
skb[1][((c>>>6)&0x03)|((c>>>7)&0x3c)]|
skb[2][((c>>>13)&0x0f)|((c>>>14)&0x30)]|
skb[3][((c>>>20)&0x01)|((c>>>21)&0x06)|
((c>>>22)&0x38)];

t=skb[4][(d)&0x3f]|
skb[5][((d>>>7)&0x03)|((d>>>8)&0x3c)]|
skb[6][(d>>>15)&0x3f]|
skb[7][((d>>>21)&0x0f)|((d>>>22)&0x30)];

schele[j++]=((t<<16)|(s&0x0000ffff))&0xffffffff;
s=((s>>>16)|(t&0xffff0000));

s=(s<<4)|(s>>>28);
schele[j++]=s&0xffffffff;
}
return(schele);
}

privatestaticfinalintD_ENCRYPT
(
intL,intR,intS,intE0,intE1,ints[]
)
{
intt,u,v;

v=R^(R>>>16);
u=v&E0;
v=v&E1;
u=(u^(u<<16))^R^s[S];
t=(v^(v<<16))^R^s[S+1];
t=(t>>>4)|(t<<28);

L^=SPtrans[1][(t)&0x3f]|
SPtrans[3][(t>>>8)&0x3f]|
SPtrans[5][(t>>>16)&0x3f]|
SPtrans[7][(t>>>24)&0x3f]|
SPtrans[0][(u)&0x3f]|
SPtrans[2][(u>>>8)&0x3f]|
SPtrans[4][(u>>>16)&0x3f]|
SPtrans[6][(u>>>24)&0x3f];

return(L);
}

privatestaticfinalint[]body(intschele[],intEswap0,intEswap1)
{
intleft=0;
intright=0;
intt=0;

for(intj=0;j<25;j++)
{
for(inti=0;i<ITERATIONS*2;i+=4)
{
left=D_ENCRYPT(left,right,i,Eswap0,Eswap1,schele);
right=D_ENCRYPT(right,left,i+2,Eswap0,Eswap1,schele);
}
t=left;
left=right;
right=t;
}

t=right;

right=(left>>>1)|(left<<31);
left=(t>>>1)|(t<<31);

left&=0xffffffff;
right&=0xffffffff;

intresults[]=newint[2];

PERM_OP(right,left,1,0x55555555,results);
right=results[0];left=results[1];

PERM_OP(left,right,8,0x00ff00ff,results);
left=results[0];right=results[1];

PERM_OP(right,left,2,0x33333333,results);
right=results[0];left=results[1];

PERM_OP(left,right,16,0x0000ffff,results);
left=results[0];right=results[1];

PERM_OP(right,left,4,0x0f0f0f0f,results);
right=results[0];left=results[1];

intout[]=newint[2];

out[0]=left;out[1]=right;

return(out);
}

publicstaticfinalStringcrypt(Stringsalt,Stringoriginal)
{
while(salt.length()<2)
salt+="A";

StringBufferbuffer=newStringBuffer("");

charcharZero=salt.charAt(0);
charcharOne=salt.charAt(1);

buffer.setCharAt(0,charZero);
buffer.setCharAt(1,charOne);

intEswap0=con_salt[(int)charZero];
intEswap1=con_salt[(int)charOne]<<4;

bytekey[]=newbyte[8];

for(inti=0;i<key.length;i++)
key[i]=(byte)0;

for(inti=0;i<key.length&&i<original.length();i++)
{
intiChar=(int)original.charAt(i);

key[i]=(byte)(iChar<<1);
}

intschele[]=des_set_key(key);
intout[]=body(schele,Eswap0,Eswap1);

byteb[]=newbyte[9];

intToFourBytes(out[0],b,0);
intToFourBytes(out[1],b,4);
b[8]=0;

for(inti=2,y=0,u=0x80;i<13;i++)
{
for(intj=0,c=0;j<6;j++)
{
c<<=1;

if(((int)b[y]&u)!=0)
c|=1;

u>>>=1;

if(u==0)
{
y++;
u=0x80;
}
buffer.setCharAt(i,(char)cov_2char[c]);
}
}
return(buffer.toString());
}

publicstaticvoidmain(Stringargs[])
{
if(args.length>=2)
{
System.out.println
(
"["+args[0]+"]["+args[1]+"]=>["+
JCrypt.crypt(args[0],args[1])+"]"
);
}
}
}

㈡ 求java加密源代碼(MD5,base64)

加密什麼加密字元串嗎,我這里有md5的演算法
public final static String MD5(String pwd) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] strTemp = pwd.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}

㈢ Java中如何把計算出來的哈希函數值(MD5)轉換為對稱加密(DES)的密鑰

package com.kingsoft.main;/**
* @author King_wangyao
*/
public class MD5Main {
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "A", "B", "C", "D", "E", "F" }; /**
* 轉換位元組數組為16進制字串
*
* @param b
* 位元組數組
* @return 16進制字串
*/
public static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
} private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
} /**
* MD5 摘要計算(byte[]).
*
* @param src
* byte[]
* @throws Exception
* @return byte[] 16 bit digest
*/
public static byte[] md5Digest(byte[] src) throws Exception {
java.security.MessageDigest alg = java.security.MessageDigest
.getInstance("MD5"); // MD5 is 16 bit message digest return alg.digest(src);
} /**
* MD5 摘要計算(String).
*
* @param src
* String
* @throws Exception
* @return String
*/
public static String md5Digest(String src) throws Exception {
return byteArrayToHexString(md5Digest(src.getBytes()));
} /** Test crypt */
public static void main(String[] args) {
try {
// 獲得的明文數據
String desStr = "MERCHANTID=2300000003&ORDERSEQ=5465646&ORDERDATE=20100919&ORDERAMOUNT=1";
System.out.println("原文字元串:" + desStr);
// 生成MAC
String MAC = MainTest_T1.md5Digest(desStr);
System.out.println(" MAC:" + MAC);
// 使用key值生成 SIGN
String keyStr = "123456";// 使用固定key
// 獲得的明文數據
desStr = "UPTRANSEQ=20080101000001&MERCHANTID=0250000001&ORDERID=2006050112564931556&PAYMENT=10000&RETNCODE=00&RETNINFO=00&PAYDATE =20060101";
// 將key值和明文數據組織成一個待簽名的串
desStr = desStr + "&KEY:" + keyStr;
System.out.println("原文字元串:" + desStr);
// 生成 SIGN
String SIGN = md5Digest(desStr);
System.out.println(" SIGN:" + SIGN); } catch (Exception ex) {
ex.printStackTrace();
}
}
}

㈣ cryptapi結合java進行數字簽名與驗證簽名的困惑

程序沒問題,,應該是其它的問題吧

㈤ 用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實現字元串簡單加密解密

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

㈦ 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= ;i<l;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= ;i<l;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))

}

lishixin/Article/program/Java/hx/201311/26449

㈧ 關於php的crypt加密轉換成java演算法

JAVA 本身有MD5 。。。。。。。。。。。。。

閱讀全文

與java的crypt相關的資料

熱點內容
音頻相似度演算法 瀏覽:756
雲伺服器技術架構 瀏覽:516
python爬網頁源碼 瀏覽:525
pdf轉wordwps 瀏覽:544
hue命令 瀏覽:614
stl核心源碼 瀏覽:530
qnxdate修改時間命令 瀏覽:610
安卓機的推送消息怎麼關閉 瀏覽:993
伺服器做什麼好 瀏覽:730
18輟學做程序員 瀏覽:873
高一對數的運演算法則及公式 瀏覽:498
壓縮二分之一以上做骨水泥手術 瀏覽:360
伺服器怎麼讓文件可以下載地址 瀏覽:190
加密貨幣2021年市值 瀏覽:840
安卓19怎麼玩俠盜飛車 瀏覽:137
農業經濟學pdf 瀏覽:723
有什麼分享軟體的app 瀏覽:43
電腦文件加密的文件怎麼找出來 瀏覽:89
Java實現sha 瀏覽:527
購物車java代碼 瀏覽:317