導航:首頁 > 編程語言 > java二進制加密

java二進制加密

發布時間:2024-07-04 12:23:34

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

B. Java編程如何給數字加密

最簡單的,用異或運算。
你也可以自己寫個加密方法啊。
比如說:利用unicode字元加密啊。假設一個數字a它的unicode值是1234,你自己設計個函數,比如說y=2x^3+3,得到一個新的unicode字元,然後把這個unicode字元轉換為字母,這個字母可能是漢字,但更可能是外國符文,反正一般人不會認出來的。你解密的時候,倒推一下就行了。

C. 使用java做一個加密和隱藏文件的軟體,具體需要怎麼做求指導

不知道你打算怎麼加密呢?隱藏又是什麼意思?是將多個文件合成一個嗎?
因為從操作系統層面來說理應能看到所有合法的文件,因此想要讓操作系統都看不到基本上是不可能的(何況Java也是用的操作系統API來實現對文件的操作)。
就加密我說說我的想法吧,首先需要一個加密的演算法。這個演算法需要滿足:演算法可逆,雙向計算復雜度(時間/空間)低,安全程度高,可靠性高。另外可以考慮並行化來增加性能,因為現在的文件系統大多比較大,管理的東西都不小。
如果能找到這樣一個演算法,可以對於文件使用二進制的讀寫(Binary I/O),然後每讀到一定大小的數據就進行加密運算,並寫入目標加密文件中。如果是解密則是讀取數據進行解密運算。
題外話:我覺得實際上做這樣一個軟體也沒有必要,每次存取文件都需要進行大量的計算操作,也很容易破壞cache的局部性原理。如果真的需要對一部分文件進行加密,也有很多現成的工具可用,甚至於是說現在的壓縮文件都可以帶上密碼加密。所以我認為這個軟體的前景不大,當然如果只是用來玩一玩也是可以的,只不過演算法比較難找而已。(如果用RSA這種級別的演算法估計也行的吧……)

D. 分享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值。好比現在的ISO校驗,都是MD校驗。怎麼用?當然是把ISO經過MD後產生MD的值。一般下載linux-ISO的朋友都見過下載鏈接旁邊放著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,並將其加入到消息中,然後傳輸。接收方利用與發送方共享的密鑰進行鑒別認證等。

E. 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

F. java的MD5withRSA演算法可以看到解密的內容么

您好,
<一>. MD5加密演算法:
? ? ? ?消息摘要演算法第五版(Message Digest Algorithm),是一種單向加密演算法,只能加密、無法解密。然而MD5加密演算法已經被中國山東大學王小雲教授成功破譯,但是在安全性要求不高的場景下,MD5加密演算法仍然具有應用價值。
?1. 創建md5對象:?
<pre name="code" class="java">MessageDigest md5 = MessageDigest.getInstance("md5");
?2. ?進行加密操作:?
byte[] cipherData = md5.digest(plainText.getBytes());

?3. ?將其中的每個位元組轉成十六進制字元串:byte類型的數據最高位是符號位,通過和0xff進行與操作,轉換為int類型的正整數。?
String toHexStr = Integer.toHexString(cipher & 0xff);

?4. 如果該正數小於16(長度為1個字元),前面拼接0佔位:確保最後生成的是32位字元串。?
builder.append(toHexStr.length() == 1 ? "0" + toHexStr : toHexStr);

?5.?加密轉換之後的字元串為:?
?6. 完整的MD5演算法應用如下所示:?
/**
* 功能簡述: 測試MD5單向加密.
* @throws Exception
*/
@Test
public void test01() throws Exception {
String plainText = "Hello , world !";
MessageDigest md5 = MessageDigest.getInstance("md5");
byte[] cipherData = md5.digest(plainText.getBytes());
StringBuilder builder = new StringBuilder();
for(byte cipher : cipherData) {
String toHexStr = Integer.toHexString(cipher & 0xff);
builder.append(toHexStr.length() == 1 ? "0" + toHexStr : toHexStr);
}
System.out.println(builder.toString());
//
}

??
<二>. 使用BASE64進行加密/解密:
? ? ? ? 使用BASE64演算法通常用作對二進制數據進行加密,加密之後的數據不易被肉眼識別。嚴格來說,經過BASE64加密的數據其實沒有安全性可言,因為它的加密解密演算法都是公開的,典型的防菜鳥不防程序猿的呀。?經過標準的BASE64演算法加密後的數據,?通常包含/、+、=等特殊符號,不適合作為url參數傳遞,幸運的是Apache的Commons Codec模塊提供了對BASE64的進一步封裝。? (參見最後一部分的說明)
?1.?使用BASE64加密:?
BASE64Encoder encoder = new BASE64Encoder();
String cipherText = encoder.encode(plainText.getBytes());

? 2.?使用BASE64解密:?
BASE64Decoder decoder = new BASE64Decoder();
plainText = new String(decoder.decodeBuffer(cipherText));

? 3. 完整代碼示例:?
/**
* 功能簡述: 使用BASE64進行雙向加密/解密.
* @throws Exception
*/
@Test
public void test02() throws Exception {
BASE64Encoder encoder = new BASE64Encoder();
BASE64Decoder decoder = new BASE64Decoder();
String plainText = "Hello , world !";
String cipherText = encoder.encode(plainText.getBytes());
System.out.println("cipherText : " + cipherText);
//cipherText : SGVsbG8gLCB3b3JsZCAh
System.out.println("plainText : " +
new String(decoder.decodeBuffer(cipherText)));
//plainText : Hello , world !
}

??
<三>. 使用DES對稱加密/解密:
? ? ? ? ?數據加密標准演算法(Data Encryption Standard),和BASE64最明顯的區別就是有一個工作密鑰,該密鑰既用於加密、也用於解密,並且要求密鑰是一個長度至少大於8位的字元串。使用DES加密、解密的核心是確保工作密鑰的安全性。
?1.?根據key生成密鑰:?
DESKeySpec keySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("des");
SecretKey secretKey = keyFactory.generateSecret(keySpec);

? 2.?加密操作:?
Cipher cipher = Cipher.getInstance("des");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom());
byte[] cipherData = cipher.doFinal(plainText.getBytes());

? 3.?為了便於觀察生成的加密數據,使用BASE64再次加密:?
String cipherText = new BASE64Encoder().encode(cipherData);

? ? ?生成密文如下:PtRYi3sp7TOR69UrKEIicA==?
? 4.?解密操作:?
cipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom());
byte[] plainData = cipher.doFinal(cipherData);
String plainText = new String(plainData);

? 5. 完整的代碼demo:?
/**
* 功能簡述: 使用DES對稱加密/解密.
* @throws Exception
*/
@Test
public void test03() throws Exception {
String plainText = "Hello , world !";
String key = "12345678"; //要求key至少長度為8個字元

SecureRandom random = new SecureRandom();
DESKeySpec keySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("des");
SecretKey secretKey = keyFactory.generateSecret(keySpec);

Cipher cipher = Cipher.getInstance("des");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);
byte[] cipherData = cipher.doFinal(plainText.getBytes());
System.out.println("cipherText : " + new BASE64Encoder().encode(cipherData));
//PtRYi3sp7TOR69UrKEIicA==

cipher.init(Cipher.DECRYPT_MODE, secretKey, random);
byte[] plainData = cipher.doFinal(cipherData);
System.out.println("plainText : " + new String(plainData));
//Hello , world !
}

??
<四>. 使用RSA非對稱加密/解密:
? ? ? ? RSA演算法是非對稱加密演算法的典型代表,既能加密、又能解密。和對稱加密演算法比如DES的明顯區別在於用於加密、解密的密鑰是不同的。使用RSA演算法,只要密鑰足夠長(一般要求1024bit),加密的信息是不能被破解的。用戶通過https協議訪問伺服器時,就是使用非對稱加密演算法進行數據的加密、解密操作的。
? ? ? ?伺服器發送數據給客戶端時使用私鑰(private key)進行加密,並且使用加密之後的數據和私鑰生成數字簽名(digital signature)並發送給客戶端。客戶端接收到伺服器發送的數據會使用公鑰(public key)對數據來進行解密,並且根據加密數據和公鑰驗證數字簽名的有效性,防止加密數據在傳輸過程中被第三方進行了修改。
? ? ? ?客戶端發送數據給伺服器時使用公鑰進行加密,伺服器接收到加密數據之後使用私鑰進行解密。
?1.?創建密鑰對KeyPair:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("rsa");
keyPairGenerator.initialize(1024); //密鑰長度推薦為1024位.
KeyPair keyPair = keyPairGenerator.generateKeyPair();

? 2.?獲取公鑰/私鑰:
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

? 3.?伺服器數據使用私鑰加密:
Cipher cipher = Cipher.getInstance("rsa");
cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom());
byte[] cipherData = cipher.doFinal(plainText.getBytes());

? 4.?用戶使用公鑰解密:
cipher.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom());
byte[] plainData = cipher.doFinal(cipherData);

? 5.?伺服器根據私鑰和加密數據生成數字簽名:
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(privateKey);
signature.update(cipherData);
byte[] signData = signature.sign();

? 6.?用戶根據公鑰、加密數據驗證數據是否被修改過:
signature.initVerify(publicKey);
signature.update(cipherData);
boolean status = signature.verify(signData);

? 7. RSA演算法代碼demo:<img src="http://www.cxyclub.cn/Upload/Images/2014081321/99A5FC9C0C628374.gif" alt="尷尬" title="尷尬" border="0">
/**
* 功能簡述: 使用RSA非對稱加密/解密.
* @throws Exception
*/
@Test
public void test04() throws Exception {
String plainText = "Hello , world !";

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("rsa");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();

PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

Cipher cipher = Cipher.getInstance("rsa");
SecureRandom random = new SecureRandom();

cipher.init(Cipher.ENCRYPT_MODE, privateKey, random);
byte[] cipherData = cipher.doFinal(plainText.getBytes());
System.out.println("cipherText : " + new BASE64Encoder().encode(cipherData));
//gDsJxZM98U2GzHUtUTyZ/Ir/
///ONFOD0fnJoGtIk+T/+3yybVL8M+RI+HzbE/jdYa/+
//yQ+vHwHqXhuzZ/N8iNg=

cipher.init(Cipher.DECRYPT_MODE, publicKey, random);
byte[] plainData = cipher.doFinal(cipherData);
System.out.println("plainText : " + new String(plainData));
//Hello , world !

Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(privateKey);
signature.update(cipherData);
byte[] signData = signature.sign();
System.out.println("signature : " + new BASE64Encoder().encode(signData));
//+
//co64p6Sq3kVt84wnRsQw5mucZnY+/+vKKXZ3pbJMNT/4
///t9ewo+KYCWKOgvu5QQ=

signature.initVerify(publicKey);
signature.update(cipherData);
boolean status = signature.verify(signData);
System.out.println("status : " + status);
//true
}

閱讀全文

與java二進制加密相關的資料

熱點內容
如何刪除國服和諧文件 瀏覽:350
spss不可以直接導入excel文件 瀏覽:34
工程管理軟體源代碼 瀏覽:38
main什麼文件 瀏覽:653
win10打開魯大師就藍屏 瀏覽:897
電子版文件如何轉發 瀏覽:895
u盤文件誤刪恢復之後打不開 瀏覽:224
在win10設置qq郵箱 瀏覽:994
linux文件root 瀏覽:975
刪除不了的文件找不到進程 瀏覽:936
榮耀7卡槽更換教程 瀏覽:935
英文網站內鏈怎麼設置 瀏覽:584
微信出現了小程序 瀏覽:412
蘋果電腦怎麼刪除桌面文件 瀏覽:609
程序裡面什麼是數據結構 瀏覽:67
ios微信老是提示修復 瀏覽:665
鐵路社保如何下載app 瀏覽:378
蘋果手機鎖屏密碼不對 瀏覽:184
蘋果手機怎麼升級ios9 瀏覽:411
編程里的符號該怎麼打出來 瀏覽:294

友情鏈接