當前位置:首頁 » 編程語言 » java文件加密解密

java文件加密解密

發布時間: 2023-08-29 10:43:14

Ⅰ 請問用java如何對文件進行加密解密

packagecom.palic.pss.afcs.worldthrough.common.util;

importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;

importrepack.com.thoughtworks.xstream.core.util.Base64Encoder;
/**
*AES加密解密
*@authorEX-CHENQI004
*
*/
publicclassAesUtils{
publicstaticfinalStringcKey="assistant7654321";
/**
*加密--把加密後的byte數組先進行二進制轉16進制在進行base64編碼
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringencrypt(StringsSrc,StringsKey)throwsException{
if(sKey==null){
("ArgumentsKeyisnull.");
}
if(sKey.length()!=16){
(
"ArgumentsKey'lengthisnot16.");
}
byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);

byte[]encrypted=cipher.doFinal(sSrc.getBytes("UTF-8"));
StringtempStr=parseByte2HexStr(encrypted);

Base64Encoderencoder=newBase64Encoder();
returnencoder.encode(tempStr.getBytes("UTF-8"));
}

/**
*解密--先進行base64解碼,在進行16進制轉為2進制然後再解碼
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringdecrypt(StringsSrc,StringsKey)throwsException{

if(sKey==null){
("499");
}
if(sKey.length()!=16){
("498");
}

byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);

Base64Encoderencoder=newBase64Encoder();
byte[]encrypted1=encoder.decode(sSrc);

StringtempStr=newString(encrypted1,"utf-8");
encrypted1=parseHexStr2Byte(tempStr);
byte[]original=cipher.doFinal(encrypted1);
StringoriginalString=newString(original,"utf-8");
returnoriginalString;
}

/**
*將二進制轉換成16進制
*
*@parambuf
*@return
*/
(bytebuf[]){
StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
returnsb.toString();
}

/**
*將16進制轉換為二進制
*
*@paramhexStr
*@return
*/
publicstaticbyte[]parseHexStr2Byte(StringhexStr){
if(hexStr.length()<1)
returnnull;
byte[]result=newbyte[hexStr.length()/2];
for(inti=0;i<hexStr.length()/2;i++){
inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);
intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),
16);
result[i]=(byte)(high*16+low);
}
returnresult;
}
publicstaticvoidmain(String[]args)throwsException{
/*
*加密用的Key可以用26個字母和數字組成,最好不要用保留字元,雖然不會錯,至於怎麼裁決,個人看情況而定
*/
StringcKey="assistant7654321";
//需要加密的字串
StringcSrc="123456";
//加密
longlStart=System.currentTimeMillis();
StringenString=encrypt(cSrc,cKey);
System.out.println("加密後的字串是:"+enString);
longlUseTime=System.currentTimeMillis()-lStart;
System.out.println("加密耗時:"+lUseTime+"毫秒");
//解密
lStart=System.currentTimeMillis();
StringDeString=decrypt(enString,cKey);
System.out.println("解密後的字串是:"+DeString);
lUseTime=System.currentTimeMillis()-lStart;
System.out.println("解密耗時:"+lUseTime+"毫秒");
}
}

Ⅱ 如何利用JAVA對文檔進行加密和解密處理,完整的java類

我以前上密碼學課寫過一個DES加解密的程序,是自己實現的,不是通過調用java庫函數,代碼有點長,帶有用戶界面。需要的話聯系我

Ⅲ 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,並將其加入到消息中,然後傳輸。接收方利用與發送方共享的密鑰進行鑒別認證等。

Ⅳ Java文件加解密

做網站有時會處理一些上傳下載的文件 可能會用到加解密功能 以下是一個加解密方法

Java代碼

import java io File;

import java io FileInputStream;

import java io FileOutputStream;

import java io IOException;

import nf Conf;

import mon time TimeHandler;

/**

* 加解密單元

* @author lupingui

* : :

*/

public class EncryptDecrypt {

//加解密KEY 這個不能變動 這里可以由任意的字元組成 盡量用特殊字元

static final byte[] KEYVALUE = getBytes();

//讀取位元組的長度

static final int BUFFERLEN = ;

//加密臨時存儲目錄

static final String TRANSIT_DIR_ENC = ;

//解密臨時存儲目錄

static final String TRANSIT_DIR_DEC = ;

/**

* 文件加密

* @param oldFile 待加密文件

* @param saveFileName 加密後文件保存路徑

* @return

* @throws IOException

*/

public static boolean encryptFile(File oldFile String saveFileName) throws IOException{

//如果傳入的文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return false;

}

FileInputStream in = new FileInputStream(oldFile);

//加密後存儲的文件

File file = new File(saveFileName);

if (!file exists()){

return false;

}

//讀取待加密文件加密後寫入加密存儲文件中

FileOutputStream out = new FileOutputStream(file);

int c pos keylen;

pos = ;

keylen = KEYVALUE length;

byte buffer[] = new byte[BUFFERLEN];

while ((c = in read(buffer)) != ) {

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

buffer[i] ^= KEYVALUE[pos];

out write(buffer[i]);

pos++;

if (pos == keylen){

pos = ;

}

}

}

in close();

out close();

return true;

}

/**

* 文件加密

* @param oldFile:待加密文件

* @param saveFile 加密後的文件

* @return

* @throws IOException

*/

public static boolean encryptFile(File oldFile File saveFile) throws IOException{

//如果傳入的文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile() || !saveFile exists() || !saveFile isFile()){

return false;

}

FileInputStream in = new FileInputStream(oldFile);

//讀取待加密文件加密後寫入加密存儲文件中

FileOutputStream out = new FileOutputStream(saveFile);

int c pos keylen;

pos = ;

keylen = KEYVALUE length;

byte buffer[] = new byte[BUFFERLEN];

while ((c = in read(buffer)) != ) {

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

buffer[i] ^= KEYVALUE[pos];

out write(buffer[i]);

pos++;

if (pos == keylen){

pos = ;

}

}

}

in close();

out close();

return true;

}

/**

* 文件加密

* @param oldFile 待加密文件

* @return

* @throws IOException

*/

public static File encryptFile(File oldFile) throws IOException{

//如果傳入的文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return null;

}

FileInputStream in = new FileInputStream(oldFile);

//臨時加密文件存儲目錄

File dirFile = new File(TRANSIT_DIR_ENC);

//如果臨時存儲目錄不存在或不是目錄則直接返回

if (!dirFile exists() || !dirFile isDirectory()){

return null;

}

//加密後存儲的文件

File file = new File(dirFile enc_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName());

if (!file exists()){

file createNewFile();

}

//讀取待加密文件加密後寫入加密存儲文件中

FileOutputStream out = new FileOutputStream(file);

int c pos keylen;

pos = ;

keylen = KEYVALUE length;

byte buffer[] = new byte[BUFFERLEN];

while ((c = in read(buffer)) != ) {

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

buffer[i] ^= KEYVALUE[pos];

out write(buffer[i]);

pos++;

if (pos == keylen){

pos = ;

}

}

}

in close();

out close();

//返回加密後的文件

return file;

}

/**

* 文件加密

* @param oldFileName 待加密文件路徑

* @return

* @throws IOException

* @throws Exception

*/

public static File encryptFile(String oldFileName) throws IOException {

//如果待加密文件路徑不正確則直接返回

if (oldFileName == null || oldFileName trim() equals( )){

return null;

}

//待加密文件

File oldFile = new File(oldFileName);

//如果傳入的文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return null;

}

//調用文件加密方法並返回結果

return encryptFile(oldFile);

}

/**

* 文件解密

* @param oldFile 待解密文件

* @return

* @throws IOException

*/

public static File decryptFile(File oldFile) throws IOException{

//如果待解密文件不存在或者不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return null;

}

FileInputStream in = new FileInputStream(oldFile);

//臨時解密文件存儲目錄

File dirFile = new File(TRANSIT_DIR_DEC);

//如果臨時解密文件存儲目錄不存在或不是目錄則返回

if (!dirFile exists() || !dirFile isDirectory()){

return null;

}

//解密存儲文件

File file = new File(dirFile dec_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName() substring(oldFile getName() lastIndexOf( )));

if (!file exists()){

file createNewFile();

}

//讀取待解密文件並進行解密存儲

FileOutputStream out = new FileOutputStream(file);

int c pos keylen;

pos = ;

keylen = KEYVALUE length;

byte buffer[] = new byte[BUFFERLEN];

while ((c = in read(buffer)) != ) {

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

buffer[i] ^= KEYVALUE[pos];

out write(buffer[i]);

pos++;

if (pos == keylen){

pos = ;

}

}

}

in close();

out close();

//返回解密結果文件

return file;

}

/**

* 文件解密

* @param oldFileName 待解密文件路徑

* @return

* @throws Exception

*/

public static File decryptFile(String oldFileName) throws Exception {

//如果待解密文件路徑不正確則直接返回

if (oldFileName == null || oldFileName trim() equals( )){

return null;

}

//待解密文件

File oldFile = new File(oldFileName);

//如果待解密文件不存在或不是文件則直接返回

if (!oldFile exists() || !oldFile isFile()){

return null;

}

//調用文件解密方法並返回結果

return decryptFile(oldFile);

}

lishixin/Article/program/Java/hx/201311/26983

Ⅳ java中如何實現對文件和字元串加密. 解密

DES 密鑰生成,加解密方法,,你可以看一下

//DES 密鑰生成工具
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class GenKey {

private static final String DES = "DES";
public static final String SKEY_NAME = "key.des";

public static void genKey1(String path) {

// 密鑰
SecretKey skey = null;
// 密鑰隨機數生成
SecureRandom sr = new SecureRandom();
//生成密鑰文件
File file = genFile(path);

try {
// 獲取密鑰生成實例
KeyGenerator gen = KeyGenerator.getInstance(DES);
// 初始化密鑰生成器
gen.init(sr);
// 生成密鑰
skey = gen.generateKey();
// System.out.println(skey);

ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* @param file : 生成密鑰的路徑
* SecretKeyFactory 方式生成des密鑰
* */
public static void genKey2(String path) {
// 密鑰隨機數生成
SecureRandom sr = new SecureRandom();
// byte[] bytes = {11,12,44,99,76,45,1,8};
byte[] bytes = sr.generateSeed(20);
// 密鑰
SecretKey skey = null;
//生成密鑰文件路徑
File file = genFile(path);

try {
//創建deskeyspec對象
DESKeySpec desKeySpec = new DESKeySpec(bytes,9);
//實例化des密鑰工廠
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
//生成密鑰對象
skey = keyFactory.generateSecret(desKeySpec);
//寫出密鑰對象
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

private static File genFile(String path) {
String temp = null;
File newFile = null;
if (path.endsWith("/") || path.endsWith("\\")) {
temp = path;
} else {
temp = path + "/";
}

File pathFile = new File(temp);
if (!pathFile.exists())
pathFile.mkdirs();

newFile = new File(temp+SKEY_NAME);

return newFile;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
genKey2("E:/a/aa/");
}

}

//DES加解密方法

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
*制卡文件加/解密 加密方式DES
*/
public class SecUtil {

public static final Log log = LogFactory.getLog(SecUtil.class);

/**
* 解密
*
* @param keyPath
* 密鑰路徑
* @param source
* 解密前文件
* @param dest
* 解密後文件
*/
public static void decrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
// 讀取加密密鑰
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
log.info("Error when read keyFile");
throw new RuntimeException(ey1);
} catch (Exception ey2) {
log.info("error when read the keyFile");
throw new RuntimeException(ey2);
}
// 用key產生Cipher
Cipher cipher = null;
try {
// 設置演算法,應該與加密時的設置一樣
cipher = Cipher.getInstance("DES");
// 設置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception ey3) {
log.info("Error when create the cipher");
throw new RuntimeException(ey3);
}
// 取得要解密的文件並解密
File file = new File(source);
String filename = file.getName();
try {
// 輸出流,請注意文件名稱的獲取
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(dest));
// 輸入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(file)), cipher);
int thebyte = 0;
while ((thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
} catch (Exception ey5) {
log.info("Error when encrypt the file");
throw new RuntimeException(ey5);
}
}

/**
* 加密
* @param keyPath 密鑰路徑
* @param source 加密前文件
* @param dest 加密後文件
*/
public static void encrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
// 讀取加密密鑰
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
log.info("Error when read keyFile");
throw new RuntimeException(ey1);
} catch (Exception ey2) {
log.info("error when read the keyFile");
throw new RuntimeException(ey2);
}
// 用key產生Cipher
Cipher cipher = null;
try {
// 設置演算法,應該與加密時的設置一樣
cipher = Cipher.getInstance("DES");
// 設置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (Exception ey3) {
log.info("Error when create the cipher");
throw new RuntimeException(ey3);
}
// 取得要解密的文件並解密
File file = new File(source);
String filename = file.getName();
try {
// 輸出流,請注意文件名稱的獲取
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(dest));
// 輸入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(file)), cipher);
int thebyte = 0;
while ((thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
} catch (Exception ey5) {
log.info("Error when encrypt the file");
throw new RuntimeException(ey5);
}
}

}

Ⅵ 如何用java實現文件(不只是txt文本)的整體加密解密

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.NoSuchAlgorithmException;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjavax.crypto.Cipher;

/**
*文件加密解密
*加解密需要依靠以下四個屬性,
;
staticKeyPairkeyPair;
staticRSAPrivateKeyprivateKey;
staticRSAPublicKeypublicKey;
*@authoryoung
*
*/
publicclassRSAEncrypt{

;

staticKeyPairkeyPair;

staticRSAPrivateKeyprivateKey;

staticRSAPublicKeypublicKey;

static{
try{
//實例類型
keyPairGen=KeyPairGenerator.getInstance("RSA");
//初始化長度
keyPairGen.initialize(512);
//聲場KeyPair
keyPair=keyPairGen.generateKeyPair();
//Generatekeys
privateKey=(RSAPrivateKey)keyPair.getPrivate();
publicKey=(RSAPublicKey)keyPair.getPublic();
}catch(NoSuchAlgorithmExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args){
RSAEncryptencrypt=newRSAEncrypt();
Filefile=newFile(
"C:\DocumentsandSettings\Administrator.DCB5E0D91E0D436\桌面\sdf.txt");
FilenewFile=newFile(
"C:\DocumentsandSettings\Administrator.DCB5E0D91E0D436\桌面\sdf1.txt");
encrypt.encryptFile(encrypt,file,newFile);
Filefile1=newFile(
"C:\DocumentsandSettings\Administrator.DCB5E0D91E0D436\桌面\sdf1.txt");
FilenewFile1=newFile(
"C:\DocumentsandSettings\Administrator.DCB5E0D91E0D436\桌面\sdf2.txt");
encrypt.decryptFile(encrypt,file1,newFile1);
}

/**
*加密文件
*@paramencryptRSAEncrypt對象
*@paramfile源文件
*@paramnewFile目標文件
*/
publicvoidencryptFile(RSAEncryptencrypt,Filefile,FilenewFile){
try{
InputStreamis=newFileInputStream(file);
OutputStreamos=newFileOutputStream(newFile);

byte[]bytes=newbyte[53];
while(is.read(bytes)>0){
byte[]e=encrypt.encrypt(RSAEncrypt.publicKey,bytes);
bytes=newbyte[53];
os.write(e,0,e.length);
}
os.close();
is.close();
System.out.println("writesuccess");
}catch(Exceptione){
e.printStackTrace();
}
}

/**
*解密文件
*@paramencryptRSAEncrypt對象
*@paramfile
*@paramnewFile
*/
publicvoiddecryptFile(RSAEncryptencrypt,Filefile,FilenewFile){
try{
InputStreamis=newFileInputStream(file);
OutputStreamos=newFileOutputStream(newFile);
byte[]bytes1=newbyte[64];
while(is.read(bytes1)>0){
byte[]de=encrypt.decrypt(RSAEncrypt.privateKey,bytes1);
bytes1=newbyte[64];
os.write(de,0,de.length);
}
os.close();
is.close();
System.out.println("writesuccess");

}catch(Exceptione){
e.printStackTrace();
}
}

/**
*加密實現
**EncryptString.*
*
*@returnbyte[]加密後的位元組數組
*/
protectedbyte[]encrypt(RSAPublicKeypublicKey,byte[]obj){
if(publicKey!=null){
try{
Ciphercipher=Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
returncipher.doFinal(obj);
}catch(Exceptione){
e.printStackTrace();
}
}
returnnull;
}

/**
*解密實現
**Basicdecryptmethod*
*
*@returnbyte[]解密後的位元組數組
*/
protectedbyte[]decrypt(RSAPrivateKeyprivateKey,byte[]obj){
if(privateKey!=null){
try{
Ciphercipher=Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,privateKey);
returncipher.doFinal(obj);
}catch(Exceptione){
e.printStackTrace();
}
}
returnnull;
}
}

Ⅶ 漫談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

熱點內容
編程課v 發布:2025-02-04 08:45:00 瀏覽:105
模擬器能有手機腳本么 發布:2025-02-04 08:39:50 瀏覽:757
android顯示html圖片 發布:2025-02-04 08:35:31 瀏覽:791
如何查學信網賬號及密碼 發布:2025-02-04 08:33:55 瀏覽:502
linux32位jdk 發布:2025-02-04 08:33:55 瀏覽:247
康佳伺服器連接失敗是怎麼回事 發布:2025-02-04 08:18:51 瀏覽:916
編譯編譯有什麼 發布:2025-02-04 08:05:52 瀏覽:735
讓外網訪問內網伺服器 發布:2025-02-04 08:02:20 瀏覽:783
奶塊腳本菜地 發布:2025-02-04 07:46:35 瀏覽:238
條形碼識別源碼 發布:2025-02-04 07:45:55 瀏覽:457