當前位置:首頁 » 編程語言 » java簡單加密

java簡單加密

發布時間: 2023-08-18 12:51:27

『壹』 用java設計一個簡單的加密、解密演算法,用該演算法來實現對數據的加密、解密

簡單的?

用異或就可以了..!

importjava.util.Scanner;

publicclass加密
{
privatestaticScannersc=newScanner(System.in);
publicstaticvoidmain(String[]Args)
{
System.out.println(" ================字元串加密演示===================== ");
init();
}
//初始化!
privatestaticvoidinit()
{
for(;;)
{
char[]arr=input();
jiaMi(arr,20140908);
jiaMi(20140908,arr);
}

}
//鍵盤錄取!
privatestaticchar[]input()
{
Strings=sc.nextLine();
inta=s.length();
char[]arr=newchar[a];
//char[]arr=s.toCharArray();
for(inti=0;i<s.length();i++)
{
arr[i]=s.charAt(i);
}
returnarr;
}
//加密!!
privatestaticvoidjiaMi(char[]arr,inta)
{
for(inti=0;i<arr.length;i++)
{
arr[i]=((char)(arr[i]^a));
}
System.out.println("加密完成!");
print(arr);
}
//解密!!
privatestaticvoidjiaMi(inta,char[]arr)
{
for(inti=0;i<arr.length;i++)
{
arr[i]=((char)(arr[i]^a));
}
System.out.println("解密完成");
print(arr);
}
//列印!!
privatestaticvoidprint(char[]arr)
{
for(inti=0;i<arr.length;i++)
{
System.out.print(arr[i]);
}
System.out.println(" ========================= ");
}
}

『貳』 漫談Java加密技術(二)

接下來我們介紹對稱加密演算法 最常用的莫過於DES數據加密演算法

DES

DES Data Encryption Standard 即數據加密演算法 是IBM公司於 年研究成功並公開發表的 DES演算法的入口參數有三個 Key Data Mode 其中Key為 個位元組共 位 是DES演算法的工作密鑰 Data也為 個位元組 位 是要被加密或被解密的數據 Mode為DES的工作方式 有兩種 加密或解密

DES演算法把 位的明文輸入塊變為 位的密文輸出塊 它所使用的密鑰也是 位

通過java代碼實現如下

importjava security Key;importjava security SecureRandom;importjavax crypto Cipher;importjavax crypto KeyGenerator;importjavax crypto SecretKey;importjavax crypto SecretKeyFactory;importjavax crypto spec DESKeySpec;/***//***DES安全編碼組件authorby;**<pre>*支持DES DESede(TripleDES 就是 DES) AES Blowfish RC RC (ARCFOUR)*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*具體內容需要關注JDKDocument&///docs/technotes/guides/security/l*</pre>**@author梁棟*@version *@since */{/***//***ALGORITHM演算法<br>*可替換為以下任意一種演算法 同時key值的size相應改變 **<pre>*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*</pre>**在KeytoKey(byte[]key)方法中使用下述代碼*<code>SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);</code>替換*<code>*DESKeySpecdks=newDESKeySpec(key);*SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);*SecretKeysecretKey=keyFactory generateSecret(dks);*</code>*/= DES ;/***//***轉換密鑰<br>**@paramkey*@return*@throwsException*/privatestaticKeytoKey(byte[]key)throwsException{DESKeySpecdks=newDESKeySpec(key);SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);SecretKeysecretKey=keyFactory generateSecret(dks);//當使用其他對稱加密演算法時 如AES Blowfish等演算法時 用下述代碼替換上述三行代碼//SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);returnsecretKey;}/***//***解密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]decrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher DECRYPT_MODE k);returncipher doFinal(data);}/***//***加密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]encrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher ENCRYPT_MODE k);returncipher doFinal(data);}/***//***生成密鑰**@return*@throwsException*/publicstaticStringinitKey()throwsException{returninitKey(null);}/***//***生成密鑰**@paramseed*@return*@throwsException*/publicstaticStringinitKey(Stringseed)throwsException{SecureRandomsecureRandom=null;if(seed!=null){secureRandom=newSecureRandom(decryptBASE (seed));}else{secureRandom=newSecureRandom();}KeyGeneratorkg=KeyGenerator getInstance(ALGORITHM);kg init(secureRandom);SecretKeysecretKey=kg generateKey();returnencryptBASE (secretKey getEncoded());}}

延續上一個類的實現 我們通過MD 以及SHA對字元串加密生成密鑰 這是比較常見的密鑰生成方式

再給出一個測試類

importstatic junit Assert *;import junit Test;/***//****@authorby;;*@version *@since */publicclassDESCoderTest{@Testpublicvoidtest()throwsException{StringinputStr= DES ;Stringkey=DESCoder initKey();System err println( 原文: +inputStr);System err println( 密鑰: +key);byte[]inputData=inputStr getBytes();inputData=DESCoder encrypt(inputData key);System err println( 加密後: +DESCoder encryptBASE (inputData));byte[]outputData=DESCoder decrypt(inputData key);StringoutputStr=newString(outputData);System err println( 解密後: +outputStr);assertEquals(inputStr outputStr);}}

得到的輸出內容如下

原文 DES

密鑰 f wEtRrV q =

加密後 C qe oNIzRY=

解密後 DES

由控制台得到的輸出 我們能夠比對加密 解密後結果一致 這是一種簡單的加密解密方式 只有一個密鑰

其實DES有很多同胞兄弟 如DESede(TripleDES) AES Blowfish RC RC (ARCFOUR) 這里就不過多闡述了 大同小異 只要換掉ALGORITHM換成對應的值 同時做一個代碼替換SecretKey secretKey = new SecretKeySpec(key ALGORITHM) 就可以了 此外就是密鑰長度不同了

/**

lishixin/Article/program/Java/gj/201311/27624

『叄』 如何使用java對密碼加密 加密方式aes

Java有相關的實現類:具體原理如下
對於任意長度的明文,AES首先對其進行分組,每組的長度為128位。分組之後將分別對每個128位的明文分組進行加密。
對於每個128位長度的明文分組的加密過程如下:
(1)將128位AES明文分組放入狀態矩陣中。
(2)AddRoundKey變換:對狀態矩陣進行AddRoundKey變換,與膨脹後的密鑰進行異或操作(密鑰膨脹將在實驗原理七中詳細討論)。
(3)10輪循環:AES對狀態矩陣進行了10輪類似的子加密過程。前9輪子加密過程中,每一輪子加密過程包括4種不同的變換,而最後一輪只有3種變換,前9輪的子加密步驟如下:
● SubBytes變換:SubBytes變換是一個對狀態矩陣非線性的變換;
● ShiftRows變換:ShiftRows變換對狀態矩陣的行進行循環移位;
● MixColumns變換:MixColumns變換對狀態矩陣的列進行變換;
● AddRoundKey變換:AddRoundKey變換對狀態矩陣和膨脹後的密鑰進行異或操作。
最後一輪的子加密步驟如下:
● SubBytes變換:SubBytes變換是一個對狀態矩陣非線性的變換;
● ShiftRows變換:ShiftRows變換對狀態矩陣的行進行循環移位;
● AddRoundKey變換:AddRoundKey變換對狀態矩陣和膨脹後的密鑰進行異或操作;
(4)經過10輪循環的狀態矩陣中的內容就是加密後的密文。
AES的加密演算法的偽代碼如下。

在AES演算法中,AddRoundKey變換需要使用膨脹後的密鑰,原始的128位密鑰經過膨脹會產生44個字(每個字為32位)的膨脹後的密鑰,這44個字的膨脹後的密鑰供11次AddRoundKey變換使用,一次AddRoundKey使用4個字(128位)的膨脹後的密鑰。
三.AES的分組過程
對於任意長度的明文,AES首先對其進行分組,分組的方法與DES相同,即對長度不足的明文分組後面補充0即可,只是每一組的長度為128位。
AES的密鑰長度有128比特,192比特和256比特三種標准,其他長度的密鑰並沒有列入到AES聯邦標准中,在下面的介紹中,我們將以128位密鑰為例。
四.狀態矩陣
狀態矩陣是一個4行、4列的位元組矩陣,所謂位元組矩陣就是指矩陣中的每個元素都是一個1位元組長度的數據。我們將狀態矩陣記為State,State中的元素記為Sij,表示狀態矩陣中第i行第j列的元素。128比特的明文分組按位元組分成16塊,第一塊記為「塊0」,第二塊記為「塊1」,依此類推,最後一塊記為「塊15」,然後將這16塊明文數據放入到狀態矩陣中,將這16塊明文數據放入到狀態矩陣中的方法如圖2-2-1所示。

塊0

塊4

塊8

塊12

塊1

塊5

塊9

塊13

塊2

塊6

塊10

塊14

塊3

塊7

塊11

塊15

圖2-2-1 將明文塊放入狀態矩陣中
五.AddRoundKey變換
狀態矩陣生成以後,首先要進行AddRoundKey變換,AddRoundKey變換將狀態矩陣與膨脹後的密鑰進行按位異或運算,如下所示。

其中,c表示列數,數組W為膨脹後的密鑰,round為加密輪數,Nb為狀態矩陣的列數。
它的過程如圖2-2-2所示。

圖2-2-2 AES演算法AddRoundKey變換
六.10輪循環
經過AddRoundKey的狀態矩陣要繼續進行10輪類似的子加密過程。前9輪子加密過程中,每一輪要經過4種不同的變換,即SubBytes變換、ShiftRows變換、MixColumns變換和AddRoundKey變換,而最後一輪只有3種變換,即SubBytes變換、ShiftRows變換和AddRoundKey變換。AddRoundKey變換已經討論過,下面分別討論餘下的三種變換。
1.SubBytes變換
SubBytes是一個獨立作用於狀態位元組的非線性變換,它由以下兩個步驟組成:
(1)在GF(28)域,求乘法的逆運算,即對於α∈GF(28)求β∈GF(28),使αβ =βα = 1mod(x8 + x4 + x3 + x + 1)。
(2)在GF(28)域做變換,變換使用矩陣乘法,如下所示:

由於所有的運算都在GF(28)域上進行,所以最後的結果都在GF(28)上。若g∈GF(28)是GF(28)的本原元素,則對於α∈GF(28),α≠0,則存在
β ∈ GF(28),使得:
β = gαmod(x8 + x4 + x3 + x + 1)
由於g255 = 1mod(x8 + x4 + x3 + x + 1)
所以g255-α = β-1mod(x8 + x4 + x3 + x + 1)
根據SubBytes變換演算法,可以得出SubBytes的置換表,如表2-2-1所示,這個表也叫做AES的S盒。該表的使用方法如下:狀態矩陣中每個元素都要經過該表替換,每個元素為8比特,前4比特決定了行號,後4比特決定了列號,例如求SubBytes(0C)查表的0行C列得FE。
表2-2-1 AES的SubBytes置換表

它的變換過程如圖2-2-3所示。

圖2-2-3 SubBytes變換
AES加密過程需要用到一些數學基礎,其中包括GF(2)域上的多項式、GF(28)域上的多項式的計算和矩陣乘法運算等,有興趣的同學請參考相關的數學書籍。
2.ShiftRows變換
ShiftRows變換比較簡單,狀態矩陣的第1行不發生改變,第2行循環左移1位元組,第3行循環左移2位元組,第4行循環左移3位元組。ShiftRows變換的過程如圖2-2-4所示。

圖2-2-4 AES的ShiftRows變換
3.MixColumns變換
在MixColumns變換中,狀態矩陣的列看作是域GF(28)的多項式,模(x4+1)乘以c(x)的結果:
c(x)=(03)x3+(01)x2+(01)x+(02)
這里(03)為十六進製表示,依此類推。c(x)與x4+1互質,故存在逆:
d(x)=(0B)x3+(0D)x2+(0G)x+(0E)使c(x)•d(x) = (D1)mod(x4+1)。
設有:

它的過程如圖2-2-5所示。

圖2-2-5 AES演算法MixColumns變換
七.密鑰膨脹
在AES演算法中,AddRoundKey變換需要使用膨脹後的密鑰,膨脹後的密鑰記為子密鑰,原始的128位密鑰經過膨脹會產生44個字(每個字為32位)的子密鑰,這44個字的子密鑰供11次AddRoundKey變換使用,一次AddRoundKey使用4個字(128位)的膨脹後的密鑰。
密鑰膨脹演算法是以字為基礎的(一個字由4個位元組組成,即32比特)。128比特的原始密鑰經過膨脹後將產生44個字的子密鑰,我們將這44個密鑰保存在一個字數組中,記為W[44]。128比特的原始密鑰分成16份,存放在一個位元組的數組:Key[0],Key[1]……Key[15]中。
在密鑰膨脹演算法中,Rcon是一個10個字的數組,在數組中保存著演算法定義的常數,分別為:
Rcon[0] = 0x01000000
Rcon[1] = 0x02000000
Rcon[2] = 0x04000000
Rcon[3] = 0x08000000
Rcon[4] = 0x10000000
Rcon[5] = 0x20000000
Rcon[6] = 0x40000000
Rcon[7] = 0x80000000
Rcon[8] = 0x1b000000
Rcon[9] = 0x36000000
另外,在密鑰膨脹中包括其他兩個操作RotWord和SubWord,下面對這兩個操作做說明:
RotWord( B0,B1,B2,B3 )對4個位元組B0,B1,B2,B3進行循環移位,即
RotWord( B0,B1,B2,B3 ) = ( B1,B2,B3,B0 )
SubWord( B0,B1,B2,B3 )對4個位元組B0,B1,B2,B3使用AES的S盒,即
SubWord( B0,B1,B2,B3 ) = ( B』0,B』1,B』2,B』3 )
其中,B』i = SubBytes(Bi),i = 0,1,2,3。
密鑰膨脹的演算法如下:

八.解密過程
AES的加密和解密過程並不相同,首先密文按128位分組,分組方法和加密時的分組方法相同,然後進行輪變換。
AES的解密過程可以看成是加密過程的逆過程,它也由10輪循環組成,每一輪循環包括四個變換分別為InvShiftRows變換、InvSubBytes變換、InvMixColumns變換和AddRoundKey變換;
這個過程可以描述為如下代碼片段所示:

九.InvShiftRows變換
InvShiftRows變換是ShiftRows變換的逆過程,十分簡單,指定InvShiftRows的變換如下。
Sr,(c+shift(r,Nb))modNb= Sr,c for 0 < r< 4 and 0 ≤ c < Nb
圖2-2-6演示了這個過程。

圖2-2-6 AES演算法InvShiftRows變換
十.InvSubBytes變換
InvSubBytes變換是SubBytes變換的逆變換,利用AES的S盒的逆作位元組置換,表2-2-2為InvSubBytes變換的置換表。
表2-2-2 InvSubBytes置換表

十一.InvMixColumns變換
InvMixColumns變換與MixColumns變換類似,每列乘以d(x)
d(x) = (OB)x3 + (0D)x2 + (0G)x + (0E)
下列等式成立:
( (03)x3 + (01)x2 + (01)x + (02) )⊙d(x) = (01)
上面的內容可以描述為以下的矩陣乘法:

十二.AddRoundKey變換
AES解密過程的AddRoundKey變換與加密過程中的AddRoundKey變換一樣,都是按位與子密鑰做異或操作。解密過程的密鑰膨脹演算法也與加密的密鑰膨脹演算法相同。最後狀態矩陣中的數據就是明文。

『肆』 可變MD5加密(Java實現)

可變在這里含義很簡單 就是最終的加密結果是可變的 而非必需按標准MD 加密實現 Java類庫security中的MessageDigest類就提供了MD 加密的支持 實現起來非常方便 為了實現更多效果 我們可以如下設計MD 工具類

Java代碼

package ** ** util;

import java security MessageDigest;

/**

* 標准MD 加密方法 使用java類庫的security包的MessageDigest類處理

* @author Sarin

*/

public class MD {

/**

* 獲得MD 加密密碼的方法

*/

public static String getMD ofStr(String origString) {

String origMD = null;

try {

MessageDigest md = MessageDigest getInstance( MD );

byte[] result = md digest(origString getBytes());

origMD = byteArray HexStr(result);

} catch (Exception e) {

e printStackTrace();

}

return origMD ;

}

/**

* 處理位元組數組得到MD 密碼的方法

*/

private static String byteArray HexStr(byte[] bs) {

StringBuffer *** = new StringBuffer();

for (byte b : bs) {

*** append(byte HexStr(b));

}

return *** toString();

}

/**

* 位元組標准移位轉十六進制方法

*/

private static String byte HexStr(byte b) {

String hexStr = null;

int n = b;

if (n < ) {

//若需要自定義加密 請修改這個移位演算法即可

n = b & x F + ;

}

hexStr = Integer toHexString(n / ) + Integer toHexString(n % );

return hexStr toUpperCase();

}

/**

* 提供一個MD 多次加密方法

*/

public static String getMD ofStr(String origString int times) {

String md = getMD ofStr(origString);

for (int i = ; i < times ; i++) {

md = getMD ofStr(md );

}

return getMD ofStr(md );

}

/**

* 密碼驗證方法

*/

public static boolean verifyPassword(String inputStr String MD Code) {

return getMD ofStr(inputStr) equals(MD Code);

}

/**

* 重載一個多次加密時的密碼驗證方法

*/

public static boolean verifyPassword(String inputStr String MD Code int times) {

return getMD ofStr(inputStr times) equals(MD Code);

}

/**

* 提供一個測試的主函數

*/

public static void main(String[] args) {

System out println( : + getMD ofStr( ));

System out println( : + getMD ofStr( ));

System out println( sarin: + getMD ofStr( sarin ));

System out println( : + getMD ofStr( ));

}

}

可以看出實現的過程非常簡單 因為由java類庫提供了處理支持 但是要清楚的是這種方式產生的密碼不是標準的MD 碼 它需要進行移位處理才能得到標准MD 碼 這個程序的關鍵之處也在這了 怎麼可變?調整移位演算法不就可變了么!不進行移位 也能夠得到 位的密碼 這就不是標准加密了 只要加密和驗證過程使用相同的演算法就可以了

MD 加密還是很安全的 像CMD 那些窮舉破解的只是針對標准MD 加密的結果進行的 如果自定義移位演算法後 它還有效么?可以說是無解的了 所以MD 非常安全可靠

為了更可變 還提供了多次加密的方法 可以在MD 基礎之上繼續MD 就是對 位的第一次加密結果再MD 恩 這樣去破解?沒有任何意義

這樣在MIS系統中使用 安全可靠 歡迎交流 希望對使用者有用

我們最後看看由MD 加密演算法實現的類 那是非常龐大的

Java代碼

import java lang reflect *;

/**

* **********************************************

* md 類實現了RSA Data Security Inc 在提交給IETF

* 的RFC 中的MD message digest 演算法

* ***********************************************

*/

public class MD {

/* 下面這些S S 實際上是一個 * 的矩陣 在原始的C實現中是用#define 實現的

這里把它們實現成為static final是表示了只讀 切能在同一個進程空間內的多個

Instance間共享*/

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final int S = ;

static final byte[] PADDING = {

};

/* 下面的三個成員是MD 計算過程中用到的 個核心數據 在原始的C實現中

被定義到MD _CTX結構中

*/

private long[] state = new long[ ]; // state (ABCD)

private long[] count = new long[ ]; // number of bits molo ^ (l *** first)

private byte[] buffer = new byte[ ]; // input buffer

/* digestHexStr是MD 的唯一一個公共成員 是最新一次計算結果的

進制ASCII表示

*/

public String digestHexStr;

/* digest 是最新一次計算結果的 進制內部表示 表示 bit的MD 值

*/

private byte[] digest = new byte[ ];

/*

getMD ofStr是類MD 最主要的公共方法 入口參數是你想要進行MD 變換的字元串

返回的是變換完的結果 這個結果是從公共成員digestHexStr取得的.

*/

public String getMD ofStr(String inbuf) {

md Init();

md Update(inbuf getBytes() inbuf length());

md Final();

digestHexStr = ;

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

digestHexStr += byteHEX(digest[i]);

}

return digestHexStr;

}

// 這是MD 這個類的標准構造函數 JavaBean要求有一個public的並且沒有參數的構造函數

public MD () {

md Init();

return;

}

/* md Init是一個初始化函數 初始化核心變數 裝入標準的幻數 */

private void md Init() {

count[ ] = L;

count[ ] = L;

///* Load magic initialization constants

state[ ] = x L;

state[ ] = xefcdab L;

state[ ] = x badcfeL;

state[ ] = x L;

return;

}

/* F G H I 是 個基本的MD 函數 在原始的MD 的C實現中 由於它們是

簡單的位運算 可能出於效率的考慮把它們實現成了宏 在java中 我們把它們

實現成了private方法 名字保持了原來C中的 */

private long F(long x long y long z) {

return (x & y) | ((~x) & z);

}

private long G(long x long y long z) {

return (x & z) | (y & (~z));

}

private long H(long x long y long z) {

return x ^ y ^ z;

}

private long I(long x long y long z) {

return y ^ (x | (~z));

}

/*

FF GG HH和II將調用F G H I進行近一步變換

FF GG HH and II transformations for rounds and

Rotation is separate from addition to prevent reputation

*/

private long FF(long a long b long c long d long x long s long ac) {

a += F(b c d) + x + ac;

a = ((int) a << s) | ((int) a >>> ( s));

a += b;

return a;

}

private long GG(long a long b long c long d long x long s long ac) {

a += G(b c d) + x + ac;

a = ((int) a << s) | ((int) a >>> ( s));

a += b;

return a;

}

private long HH(long a long b long c long d long x long s long ac) {

a += H(b c d) + x + ac;

a = ((int) a << s) | ((int) a >>> ( s));

a += b;

return a;

}

private long II(long a long b long c long d long x long s long ac) {

a += I(b c d) + x + ac;

a = ((int) a << s) | ((int) a >>> ( s));

a += b;

return a;

}

/*

md Update是MD 的主計算過程 inbuf是要變換的位元組串 inputlen是長度 這個

函數由getMD ofStr調用 調用之前需要調用md init 因此把它設計成private的

*/

private void md Update(byte[] inbuf int inputLen) {

int i index partLen;

byte[] block = new byte[ ];

index = (int) (count[ ] >>> ) & x F;

// /* Update number of bits */

if ((count[ ] += (inputLen << )) < (inputLen << ))

count[ ]++;

count[ ] += (inputLen >>> );

partLen = index;

// Transform as many times as possible

if (inputLen >= partLen) {

md Memcpy(buffer inbuf index partLen);

md Transform(buffer);

for (i = partLen; i + < inputLen; i += ) {

md Memcpy(block inbuf i );

md Transform(block);

}

index = ;

} else

i = ;

///* Buffer remaining input */

md Memcpy(buffer inbuf index i inputLen i);

}

/*

md Final整理和填寫輸出結果

*/

private void md Final() {

byte[] bits = new byte[ ];

int index padLen;

///* Save number of bits */

Encode(bits count );

///* Pad out to mod

index = (int) (count[ ] >>> ) & x f;

padLen = (index < ) ? ( index) : ( index);

md Update(PADDING padLen);

///* Append length (before padding) */

md Update(bits );

///* Store state in digest */

Encode(digest state );

}

/* md Memcpy是一個內部使用的byte數組的塊拷貝函數 從input的inpos開始把len長度的

位元組拷貝到output的outpos位置開始

*/

private void md Memcpy(byte[] output byte[] input int outpos int inpos int len) {

int i;

for (i = ; i < len; i++)

output[outpos + i] = input[inpos + i];

}

/*

md Transform是MD 核心變換程序 有md Update調用 block是分塊的原始位元組

*/

private void md Transform(byte block[]) {

long a = state[ ] b = state[ ] c = state[ ] d = state[ ];

long[] x = new long[ ];

Decode(x block );

/* Round */

a = FF(a b c d x[ ] S xd aa L); /* */

d = FF(d a b c x[ ] S xe c b L); /* */

c = FF(c d a b x[ ] S x dbL); /* */

b = FF(b c d a x[ ] S xc bdceeeL); /* */

a = FF(a b c d x[ ] S xf c fafL); /* */

d = FF(d a b c x[ ] S x c aL); /* */

c = FF(c d a b x[ ] S xa L); /* */

b = FF(b c d a x[ ] S xfd L); /* */

a = FF(a b c d x[ ] S x d L); /* */

d = FF(d a b c x[ ] S x b f afL); /* */

c = FF(c d a b x[ ] S xffff bb L); /* */

b = FF(b c d a x[ ] S x cd beL); /* */

a = FF(a b c d x[ ] S x b L); /* */

d = FF(d a b c x[ ] S xfd L); /* */

c = FF(c d a b x[ ] S xa eL); /* */

b = FF(b c d a x[ ] S x b L); /* */

/* Round */

a = GG(a b c d x[ ] S xf e L); /* */

d = GG(d a b c x[ ] S xc b L); /* */

c = GG(c d a b x[ ] S x e a L); /* */

b = GG(b c d a x[ ] S xe b c aaL); /* */

a = GG(a b c d x[ ] S xd f dL); /* */

d = GG(d a b c x[ ] S x L); /* */

c = GG(c d a b x[ ] S xd a e L); /* */

b = GG(b c d a x[ ] S xe d fbc L); /* */

a = GG(a b c d x[ ] S x e cde L); /* */

d = GG(d a b c x[ ] S xc d L); /* */

c = GG(c d a b x[ ] S xf d d L); /* */

b = GG(b c d a x[ ] S x a edL); /* */

a = GG(a b c d x[ ] S xa e e L); /* */

d = GG(d a b c x[ ] S xfcefa f L); /* */

c = GG(c d a b x[ ] S x f d L); /* */

b = GG(b c d a x[ ] S x d a c aL); /* */

/* Round */

a = HH(a b c d x[ ] S xfffa L); /* */

d = HH(d a b c x[ ] S x f L); /* */

c = HH(c d a b x[ ] S x d d L); /* */

b = HH(b c d a x[ ] S xfde cL); /* */

a = HH(a b c d x[ ] S xa beea L); /* */

d = HH(d a b c x[ ] S x bdecfa L); /* */

c = HH(c d a b x[ ] S xf bb b L); /* */

b = HH(b c d a x[ ] S xbebfbc L); /* */

a = HH(a b c d x[ ] S x b ec L); /* */

d = HH(d a b c x[ ] S xeaa faL); /* */

c = HH(c d a b x[ ] S xd ef L); /* */

b = HH(b c d a x[ ] S x d L); /* */

a = HH(a b c d x[ ] S xd d d L); /* */

d = HH(d a b c x[ ] S xe db e L); /* */

c = HH(c d a b x[ ] S x fa cf L); /* */

b = HH(b c d a x[ ] S xc ac L); /* */

/* Round */

a = II(a b c d x[ ] S xf L); /* */

d = II(d a b c x[ ] S x aff L); /* */

c = II(c d a b x[ ] S xab a L); /* */

b = II(b c d a x[ ] S xfc a L); /* */

a = II(a b c d x[ ] S x b c L); /* */

d = II(d a b c x[ ] S x f ccc L); /* */

c = II(c d a b x[ ] S xffeff dL); /* */

b = II(b c d a x[ ] S x dd L); /* */

a = II(a b c d x[ ] S x fa e fL); /* */

d = II(d a b c x[ ] S xfe ce e L); /* */

c = II(c d a b x[ ] S xa L); /* */

b = II(b c d a x[ ] S x e a L); /* */

a = II(a b c d x[ ] S xf e L); /* */

d = II(d a b c x[ ] S xbd af L); /* */

c = II(c d a b x[ ] S x ad d bbL); /* */

b = II(b c d a x[ ] S xeb d L); /* */

state[ ] += a;

state[ ] += b;

state[ ] += c;

state[ ] += d;

}

/*Encode把long數組按順序拆成byte數組 因為java的long類型是 bit的

只拆低 bit 以適應原始C實現的用途

*/

private void Encode(byte[] output long[] input int len) {

int i j;

for (i = j = ; j < len; i++ j += ) {

output[j] = (byte) (input[i] & xffL);

output[j + ] = (byte) ((input[i] >>> ) & xffL);

output[j + ] = (byte) ((input[i] >>> ) & xffL);

output[j + ] = (byte) ((input[i] >>> ) & xffL);

}

}

/*Decode把byte數組按順序合成成long數組 因為java的long類型是 bit的

只合成低 bit 高 bit清零 以適應原始C實現的用途

*/

private void Decode(long[] output byte[] input int len) {

int i j;

for (i = j = ; j < len; i++ j += )

output[i] = b iu(input[j]) | (b iu(input[j + ]) << ) | (b iu(input[j + ]) << )

| (b iu(input[j + ]) << );

return;

}

/*

b iu是我寫的一個把byte按照不考慮正負號的原則的"升位"程序 因為java沒有unsigned運算

*/

public static long b iu(byte b) {

return b < ? b & x F + : b;

}

/*byteHEX() 用來把一個byte類型的數轉換成十六進制的ASCII表示

因為java中的byte的toString無法實現這一點 我們又沒有C語言中的

sprintf(outbuf % X ib)

*/

public static String byteHEX(byte ib) {

char[] Digit = { A B C D E F };

char[] ob = new char[ ];

ob[ ] = Digit[(ib >>> ) & X F];

ob[ ] = Digit[ib & X F];

String s = new String(ob);

return s;

}

public static void main(String args[]) {

MD m = new MD ();

if (Array getLength(args) == ) { //如果沒有參數 執行標準的Test Suite

System out println( MD Test suite: );

System out println( MD ( ): + m getMD ofStr( ));

System out println( MD ( a ): + m getMD ofStr( a ));

System out println( MD ( abc ): + m getMD ofStr( abc ));

System out println( MD ( ): + m getMD ofStr( ));

System out println( MD ( ): + m getMD ofStr( ));

System out println( MD ( message digest ): + m getMD ofStr( message digest ));

System out println( MD ( abcdefghijklmnopqrstuvwxyz ): + m getMD ofStr( abcdefghijklmnopqrstuvwxyz ));

System out println( MD ( ):

+ m getMD ofStr( ));

} else

System out println( MD ( + args[ ] + )= + m getMD ofStr(args[ ]));

}

lishixin/Article/program/Java/hx/201311/26604

『伍』 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

『陸』 怎樣為一個java程序加密 謝謝

只給編譯後的.jar文件,不給.java文件

不過要說明的是,java因為是位元組碼,所以沒有辦法防止被反編譯。
最多也就是做一下代碼混淆,比如把方法或變數名改成無意義的名稱,或者加一些完全無用的代碼進去,讓惡意攻擊的人難以看懂

『柒』 如何用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!");
}
}
}

『捌』 java最常用的幾種加密演算法

簡單的Java加密演算法有:
第一種. BASE
Base是網路上最常見的用於傳輸Bit位元組代碼的編碼方式之一,大家可以查看RFC~RFC,上面有MIME的詳細規范。Base編碼可用於在HTTP環境下傳遞較長的標識信息。例如,在Java Persistence系統Hibernate中,就採用了Base來將一個較長的唯一標識符(一般為-bit的UUID)編碼為一個字元串,用作HTTP表單和HTTP GET URL中的參數。在其他應用程序中,也常常需要把二進制數據編碼為適合放在URL(包括隱藏表單域)中的形式。此時,採用Base編碼具有不可讀性,即所編碼的數據不會被人用肉眼所直接看到。
第二種. MD
MD即Message-Digest Algorithm (信息-摘要演算法),用於確保信息傳輸完整一致。是計算機廣泛使用的雜湊演算法之一(又譯摘要演算法、哈希演算法),主流編程語言普遍已有MD實現。將數據(如漢字)運算為另一固定長度值,是雜湊演算法的基礎原理,MD的前身有MD、MD和MD。
MD演算法具有以下特點:
壓縮性:任意長度的數據,算出的MD值長度都是固定的。
容易計算:從原數據計算出MD值很容易。
抗修改性:對原數據進行任何改動,哪怕只修改個位元組,所得到的MD值都有很大區別。
弱抗碰撞:已知原數據和其MD值,想找到一個具有相同MD值的數據(即偽造數據)是非常困難的。
強抗碰撞:想找到兩個不同的數據,使它們具有相同的MD值,是非常困難的。
MD的作用是讓大容量信息在用數字簽名軟體簽署私人密鑰前被」壓縮」成一種保密的格式(就是把一個任意長度的位元組串變換成一定長的十六進制數字串)。除了MD以外,其中比較有名的還有sha-、RIPEMD以及Haval等。
第三種.SHA
安全哈希演算法(Secure Hash Algorithm)主要適用於數字簽名標准(Digital Signature Standard DSS)裡面定義的數字簽名演算法(Digital Signature Algorithm DSA)。對於長度小於^位的消息,SHA會產生一個位的消息摘要。該演算法經過加密專家多年來的發展和改進已日益完善,並被廣泛使用。該演算法的思想是接收一段明文,然後以一種不可逆的方式將它轉換成一段(通常更小)密文,也可以簡單的理解為取一串輸入碼(稱為預映射或信息),並把它們轉化為長度較短、位數固定的輸出序列即散列值(也稱為信息摘要或信息認證代碼)的過程。散列函數值可以說是對明文的一種「指紋」或是「摘要」所以對散列值的數字簽名就可以視為對此明文的數字簽名。
SHA-與MD的比較
因為二者均由MD導出,SHA-和MD彼此很相似。相應的,他們的強度和其他特性也是相似,但還有以下幾點不同:
對強行攻擊的安全性:最顯著和最重要的區別是SHA-摘要比MD摘要長 位。使用強行技術,產生任何一個報文使其摘要等於給定報摘要的難度對MD是^數量級的操作,而對SHA-則是^數量級的操作。這樣,SHA-對強行攻擊有更大的強度。
對密碼分析的安全性:由於MD的設計,易受密碼分析的攻擊,SHA-顯得不易受這樣的攻擊。
速度:在相同的硬體上,SHA-的運行速度比MD慢。
第四種.HMAC
HMAC(Hash Message Authentication Code,散列消息鑒別碼,基於密鑰的Hash演算法的認證協議。消息鑒別碼實現鑒別的原理是,用公開函數和密鑰產生一個固定長度的值作為認證標識,用這個標識鑒別消息的完整性。使用一個密鑰生成一個固定大小的小數據塊,即MAC,並將其加入到消息中,然後傳輸。接收方利用與發送方共享的密鑰進行鑒別認證等。

『玖』 java中使用MD5加密演算法進行加密

在各種應用系統的開發中 經常需要存儲用戶信息 很多地方都要存儲用戶密碼 而將用戶密碼直接存儲亮衫唯在伺服器上顯然是不安全的 本文簡要介紹工作中常用的 MD 加密演算法 希望能拋磚引玉

(一)消息摘要簡介

一個消息摘要就是一個數據塊的數字指紋 即對一個任意敬培長度的一個數據塊進行計算 產生一個唯一指印(對於SHA 是產生一個 位元組的二進制數組) 消息摘要是一種與消息認證碼結合使用以確保消息完整性的技術 主要使用單向散列函數演算法 可用於檢驗消息的完整性 和通過散列密碼直接以文本形式保存等 目前廣泛使用的演算法有MD MD SHA

消息摘要有兩個基本屬性

兩個不同的報文難以生成相同的摘要難以對指定的摘要生成一個報文 而可以由該報文反推算出該指定的摘要代表 美國國家標准技術研究所的SHA 和麻省理工學院Ronald Rivest提出的MD

(二)對字元串進行加密

/***//**利用MD 進行加密*@paramstr待加密的字元串*@return加密後的字元串*塌仔@沒有這種產生消息摘要的演算法*@*/publicStringEncoderByMd (Stringstr) UnsupportedEncodingException {//確定計算方法MessageDigestmd =MessageDigest getInstance( MD );BASE Encoderbase en=newBASE Encoder();//加密後的字元串Stringnewstr=base en encode(md digest(str getBytes( utf )));returnnewstr;}

調用函數 String str=

System out println(EncoderByMd (str))

輸出 eB eJF ptWaXm bijSPyxw==

(三)驗證密碼是否正確

/***//**判斷用戶密碼是否正確*@paramnewpasswd用戶輸入的密碼*@paramoldpasswd資料庫中存儲的密碼--用戶密碼的摘要*@return*@*@*/publicbooleancheckpassword(Stringnewpasswd Stringoldpasswd) UnsupportedEncodingException {if(EncoderByMd (newpasswd) equals(oldpasswd))returntrue;elsereturnfalse;} lishixin/Article/program/Java/hx/201311/26374

熱點內容
演算法牛人左 發布:2025-02-05 15:31:02 瀏覽:438
php篩選功能 發布:2025-02-05 15:29:09 瀏覽:167
ip匹配伺服器 發布:2025-02-05 15:10:35 瀏覽:909
php語法後 發布:2025-02-05 15:10:34 瀏覽:59
oppor9s怎麼壓縮文件 發布:2025-02-05 15:00:34 瀏覽:639
蘋果耳塞怎麼改安卓也能用 發布:2025-02-05 14:50:54 瀏覽:558
安卓如何鑒別手機真假 發布:2025-02-05 14:28:15 瀏覽:121
ffmpeglinux編譯 發布:2025-02-05 14:28:04 瀏覽:545
伺服器如何做界面 發布:2025-02-05 14:27:23 瀏覽:291
訪問學者單位推薦意見 發布:2025-02-05 14:13:05 瀏覽:854