導航:首頁 > 編程語言 > java向量des

java向量des

發布時間:2022-07-14 12:22:10

java中怎麼搞定DES演算法 完整頁

public class DESUtil {
static Key key ;

public DESUtil() {

}

static{
setKey("1q2w3e4r");
}

/**
* 根據參數生成 KEY
*/
public static void setKey(String strKey) {
try {
KeyGenerator _generator = KeyGenerator.getInstance ( "DES" );
_generator.init( new SecureRandom(strKey.getBytes()));
key = _generator.generateKey();
_generator = null ;
} catch (Exception e) {
throw new RuntimeException(
"Error initializing SqlMap class. Cause: " + e);
}
}

/**
* 加密 String 明文輸入 ,String 密文輸出
*/
public static String encryptStr(String strMing) {
byte [] byteMi = null ;
byte [] byteMing = null ;
String strMi = "" ;
BASE64Encoder base64en = new BASE64Encoder();
try {
byteMing = strMing.getBytes( "UTF8" );
byteMi =encryptByte(byteMing);
strMi = base64en.encode(byteMi);
} catch (Exception e) {
throw new RuntimeException(
"Error initializing SqlMap class. Cause: " + e);
} finally {
base64en = null ;
byteMing = null ;
byteMi = null ;
}
return strMi;
}

/**
* 解密 以 String 密文輸入 ,String 明文輸出
*
* @param strMi
* @return
*/
public static String decryptStr(String strMi) {
BASE64Decoder base64De = new BASE64Decoder();
byte [] byteMing = null ;
byte [] byteMi = null ;
String strMing = "" ;
try {
byteMi = base64De.decodeBuffer(strMi);
byteMing = decryptByte(byteMi);
strMing = new String(byteMing, "UTF8" );
} catch (Exception e) {
throw new RuntimeException(
"Error initializing SqlMap class. Cause: " + e);
} finally {
base64De = null ;
byteMing = null ;
byteMi = null ;
}
return strMing;
}

/**
* 加密以 byte[] 明文輸入 ,byte[] 密文輸出
*
* @param byteS
* @return
*/
private static byte [] encryptByte( byte [] byteS) {
byte [] byteFina = null ;
Cipher cipher;
try {
cipher = Cipher.getInstance ( "DES" );
cipher.init(Cipher.ENCRYPT_MODE , key );
byteFina = cipher.doFinal(byteS);
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null ;
}
return byteFina;
}

/**
* 解密以 byte[] 密文輸入 , 以 byte[] 明文輸出
*
* @param byteD
* @return
*/
private static byte [] decryptByte( byte [] byteD) {
Cipher cipher;
byte [] byteFina = null ;
try {
cipher = Cipher.getInstance ( "DES" );
cipher.init(Cipher. DECRYPT_MODE , key );
byteFina = cipher.doFinal(byteD);
} catch (Exception e) {
throw new RuntimeException(
"Error initializing SqlMap class. Cause: " + e);
} finally {
cipher = null ;
}
return byteFina;
}

/**
* 文件 file 進行加密並保存目標文件 destFile 中
*
* @param file
* 要加密的文件 如 c:/test/srcFile.txt
* @param destFile
* 加密後存放的文件名 如 c:/ 加密後文件 .txt
*/
public static void encryptFile(String file, String destFile) throws Exception {
Cipher cipher = Cipher.getInstance ( "DES" );
// cipher.init(Cipher.ENCRYPT_MODE, getKey());
cipher.init(Cipher. ENCRYPT_MODE , key );
InputStream is = new FileInputStream(file);
OutputStream out = new FileOutputStream(destFile);
CipherInputStream cis = new CipherInputStream(is, cipher);
byte [] buffer = new byte [1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}
cis.close();
is.close();
out.close();
}

/**
* 文件採用 DES 演算法解密文件
*
* @param file
* 已加密的文件 如 c:/ 加密後文件 .txt *
* @param destFile
* 解密後存放的文件名 如 c:/ test/ 解密後文件 .txt
*/
public static void decryptFile(String file, String dest) throws Exception {
Cipher cipher = Cipher.getInstance ( "DES" );
cipher.init(Cipher. DECRYPT_MODE , key );
InputStream is = new FileInputStream(file);
OutputStream out = new FileOutputStream(dest);
CipherOutputStream cos = new CipherOutputStream(out, cipher);
byte [] buffer = new byte [1024];
int r;
while ((r = is.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}
cos.close();
out.close();
is.close();
}
}

⑵ 用java實現des演算法

package des;

import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;

public class FileDES{
private static final boolean enc=true; //加密
private static final boolean dec=false; //解密

private String srcFileName;
private String destFileName;
private String inKey;
private boolean actionType;
private File srcFile;
private File destFile;
private Des des;

private void analyzePath(){
String dirName;
int pos=srcFileName.lastIndexOf("/");
dirName=srcFileName.substring(0,pos);
File dir=new File(dirName);
if (!dir.exists()){
System.err.println(dirName+" is not exist");
System.exit(1);
}else if(!dir.isDirectory()){
System.err.println(dirName+" is not a directory");
System.exit(1);
}

pos=destFileName.lastIndexOf("/");
dirName=destFileName.substring(0,pos);
dir=new File(dirName);
if (!dir.exists()){
if(!dir.mkdirs()){
System.out.println ("can not creat directory:"+dirName);
System.exit(1);
}
}else if(!dir.isDirectory()){
System.err.println(dirName+" is not a directory");
System.exit(1);
}
}

private static int replenish(FileChannel channel,ByteBuffer buf) throws IOException{
long byteLeft=channel.size()-channel.position();
if(byteLeft==0L)
return -1;
buf.position(0);
buf.limit(buf.position()+(byteLeft<8 ? (int)byteLeft :8));
return channel.read(buf);
}

private void file_operate(boolean flag){
des=new Des(inKey);
FileOutputStream outputFile=null;
try {
outputFile=new FileOutputStream(srcFile,true);
}catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel=outputFile.getChannel();

try{
if(outChannel.size()%2!=0){
ByteBuffer bufTemp=ByteBuffer.allocate(1);
bufTemp.put((byte)32);
bufTemp.flip();
outChannel.position(outChannel.size());
outChannel.write(bufTemp);
bufTemp.clear();
}
}catch(Exception ex){
ex.printStackTrace(System.err);
System.exit(1);
}
FileInputStream inFile=null;
try{
inFile=new FileInputStream(srcFile);
}catch(java.io.FileNotFoundException e){
e.printStackTrace(System.err);
//System.exit(1);
}
outputFile=null;
try {
outputFile=new FileOutputStream(destFile,true);
}catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}

FileChannel inChannel=inFile.getChannel();
outChannel=outputFile.getChannel();

ByteBuffer inBuf=ByteBuffer.allocate(8);
ByteBuffer outBuf=ByteBuffer.allocate(8);

try{
String srcStr;
String destStr;
while(true){

if (replenish(inChannel,inBuf)==-1) break;
srcStr=((ByteBuffer)(inBuf.flip())).asCharBuffer().toString();
inBuf.clear();
if (flag)
destStr=des.enc(srcStr,srcStr.length());
else
destStr=des.dec(srcStr,srcStr.length());
outBuf.clear();
if (destStr.length()==4){
for (int i = 0; i<4; i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}else{
outBuf.position(0);
outBuf.limit(2*destStr.length());
for (int i = 0; i<destStr.length(); i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}

try {
outChannel.write(outBuf);
outBuf.clear();
}catch (java.io.IOException ex) {
ex.printStackTrace(System.err);
}
}
System.out.println (inChannel.size());
System.out.println (outChannel.size());
System.out.println ("EoF reached.");
inFile.close();
outputFile.close();
}catch(java.io.IOException e){
e.printStackTrace(System.err);
System.exit(1);
}
}

public FileDES(String srcFileName,String destFileName,String inKey,boolean actionType){
this.srcFileName=srcFileName;
this.destFileName=destFileName;
this.actionType=actionType;
analyzePath();
srcFile=new File(srcFileName);
destFile=new File(destFileName);
this.inKey=inKey;
if (actionType==enc)
file_operate(enc);
else
file_operate(dec);
}

public static void main(String[] args){
String file1=System.getProperty("user.dir")+"/111.doc";
String file2=System.getProperty("user.dir")+"/222.doc";
String file3=System.getProperty("user.dir")+"/333.doc";
String passWord="1234ABCD";
FileDES fileDes=new FileDES(file1,file2,passWord,true);
FileDES fileDes1=new FileDES(file2,file3,passWord,false);
}

⑶ C#與JAVA的DES加密解密

本來就是沒有初始化向量這個東西。。。。。可能是C#運行自己提供P盒或者S盒,而java使用ANSI默認的P盒和S盒了。。。你得去看C#的文檔說明。。

加密過程本來就是只需要明文和密鑰,C#估計只是多給一個參數罷了。。。看看文檔去

###################################
什麼叫「初始化向量」?我記得上密碼學的時候DES裡面沒有這個概念~~~

DES演算法流程就是固定的。可變的只有P盒和S盒。不知道你說的「初始化向量」是不是S盒

加密和解密只是密鑰擴展的順序顛倒,其他演算法完全一樣。

P盒不是保密的,S盒設計方式保密但是可以在網上美國安全局網站上找到設計好的S盒。

如果你說真有什麼「初始化向量」,那可能你用的是前向反饋模式產生序列密碼,不過這樣的話,保持相同的初始向量也是可能的啊。估計是你程序寫的問題。。。而且這樣安全性可能你沒有辦法考證吧。。。

還有。。。你沒有搞錯吧。。。DES是64位的。。。。你用8位能搞什麼。。。

還有。。看樣子你是用C#自帶的工具來加密的。。。DES概念裡面確實沒有什麼「初始化向量」,具體怎麼搞你找密碼學的書看看吧。。。

還有一點。。。。是不是C#裡面可以選擇輪迭次數???默認是16次,還有你要看好是DES還是3DES。

⑷ mysql 解密JAVA 用des加密數據

標准DES算採用約定向量1計算默認情況C#Java向量相同 結致能補位等算造檢查算詳細設置設置行

⑸ 求用JAVA實現的DES演算法

package des;

import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;

public class FileDES{
private static final boolean enc=true; //加密
private static final boolean dec=false; //解密

private String srcFileName;
private String destFileName;
private String inKey;
private boolean actionType;
private File srcFile;
private File destFile;
private Des des;

private void analyzePath(){
String dirName;
int pos=srcFileName.lastIndexOf("/");
dirName=srcFileName.substring(0,pos);
File dir=new File(dirName);
if (!dir.exists()){
System.err.println(dirName+" is not exist");
System.exit(1);
}else if(!dir.isDirectory()){
System.err.println(dirName+" is not a directory");
System.exit(1);
}

pos=destFileName.lastIndexOf("/");
dirName=destFileName.substring(0,pos);
dir=new File(dirName);
if (!dir.exists()){
if(!dir.mkdirs()){
System.out.println ("can not creat directory:"+dirName);
System.exit(1);
}
}else if(!dir.isDirectory()){
System.err.println(dirName+" is not a directory");
System.exit(1);
}
}

private static int replenish(FileChannel channel,ByteBuffer buf) throws IOException{
long byteLeft=channel.size()-channel.position();
if(byteLeft==0L)
return -1;
buf.position(0);
buf.limit(buf.position()+(byteLeft<8 ? (int)byteLeft :8));
return channel.read(buf);
}

private void file_operate(boolean flag){
des=new Des(inKey);
FileOutputStream outputFile=null;
try {
outputFile=new FileOutputStream(srcFile,true);
}catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel=outputFile.getChannel();

try{
if(outChannel.size()%2!=0){
ByteBuffer bufTemp=ByteBuffer.allocate(1);
bufTemp.put((byte)32);
bufTemp.flip();
outChannel.position(outChannel.size());
outChannel.write(bufTemp);
bufTemp.clear();
}
}catch(Exception ex){
ex.printStackTrace(System.err);
System.exit(1);
}
FileInputStream inFile=null;
try{
inFile=new FileInputStream(srcFile);
}catch(java.io.FileNotFoundException e){
e.printStackTrace(System.err);
//System.exit(1);
}
outputFile=null;
try {
outputFile=new FileOutputStream(destFile,true);
}catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}

FileChannel inChannel=inFile.getChannel();
outChannel=outputFile.getChannel();

ByteBuffer inBuf=ByteBuffer.allocate(8);
ByteBuffer outBuf=ByteBuffer.allocate(8);

try{
String srcStr;
String destStr;
while(true){

if (replenish(inChannel,inBuf)==-1) break;
srcStr=((ByteBuffer)(inBuf.flip())).asCharBuffer().toString();
inBuf.clear();
if (flag)
destStr=des.enc(srcStr,srcStr.length());
else
destStr=des.dec(srcStr,srcStr.length());
outBuf.clear();
if (destStr.length()==4){
for (int i = 0; i<4; i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}else{
outBuf.position(0);
outBuf.limit(2*destStr.length());
for (int i = 0; i<destStr.length(); i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}

try {
outChannel.write(outBuf);
outBuf.clear();
}catch (java.io.IOException ex) {
ex.printStackTrace(System.err);
}
}
System.out.println (inChannel.size());
System.out.println (outChannel.size());
System.out.println ("EoF reached.");
inFile.close();
outputFile.close();
}catch(java.io.IOException e){
e.printStackTrace(System.err);
System.exit(1);
}
}

public FileDES(String srcFileName,String destFileName,String inKey,boolean actionType){
this.srcFileName=srcFileName;
this.destFileName=destFileName;
this.actionType=actionType;
analyzePath();
srcFile=new File(srcFileName);
destFile=new File(destFileName);
this.inKey=inKey;
if (actionType==enc)
file_operate(enc);
else
file_operate(dec);
}

public static void main(String[] args){
String file1=System.getProperty("user.dir")+"/111.doc";
String file2=System.getProperty("user.dir")+"/222.doc";
String file3=System.getProperty("user.dir")+"/333.doc";
String passWord="1234ABCD";
FileDES fileDes=new FileDES(file1,file2,passWord,true);
FileDES fileDes1=new FileDES(file2,file3,passWord,false);
}

⑹ DES加密解密問題,java 和 C#

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.IO;
usingSystem.Security;
usingSystem.Security.Cryptography;
/*----------------------------------------------
*DES加密、解密類庫,字元串加密結果使用BASE64編碼返回,支持文件的加密和解密
*作者:三角貓/DeltaCat
*網址:

*轉載務必保留此信息
*---------------------------------------------
*/
namespaceZU14
{
publicsealedclassDES
{
stringiv="1234的yzo";
stringkey="123在yzo";
///<summary>
///DES加密偏移量,必須是>=8位長的字元串
///</summary>
publicstringIV
{
get{returniv;}
set{iv=value;}
}
///<summary>
///DES加密的私鑰,必須是8位長的字元串
///</summary>
publicstringKey
{
get{returnkey;}
set{key=value;}
}
///<summary>
///對字元串進行DES加密
///</summary>
///<paramname="sourceString">待加密的字元串</param>
///<returns>加密後的BASE64編碼的字元串</returns>
publicstringEncrypt(stringsourceString)
{
byte[]btKey=Encoding.Default.GetBytes(key);
byte[]btIV=Encoding.Default.GetBytes(iv);
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
using(MemoryStreamms=newMemoryStream())
{
byte[]inData=Encoding.Default.GetBytes(sourceString);
try
{
using(CryptoStreamcs=newCryptoStream(ms,des.CreateEncryptor(btKey,btIV),CryptoStreamMode.Write))
{
cs.Write(inData,0,inData.Length);
cs.FlushFinalBlock();
}
returnConvert.ToBase64String(ms.ToArray());
}
catch
{
throw;
}
}
}
///<summary>
///對DES加密後的字元串進行解密
///</summary>
///<paramname="encryptedString">待解密的字元串</param>
///<returns>解密後的字元串</returns>
publicstringDecrypt(stringencryptedString)
{
byte[]btKey=Encoding.Default.GetBytes(key);
byte[]btIV=Encoding.Default.GetBytes(iv);
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
using(MemoryStreamms=newMemoryStream())
{
byte[]inData=Convert.FromBase64String(encryptedString);
try
{
using(CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(btKey,btIV),CryptoStreamMode.Write))
{
cs.Write(inData,0,inData.Length);
cs.FlushFinalBlock();
}
returnEncoding.Default.GetString(ms.ToArray());
}
catch
{
throw;
}
}
}
///<summary>
///對文件內容進行DES加密
///</summary>
///<paramname="sourceFile">待加密的文件絕對路徑</param>
///<paramname="destFile">加密後的文件保存的絕對路徑</param>
publicvoidEncryptFile(stringsourceFile,stringdestFile)
{
if(!File.Exists(sourceFile))thrownewFileNotFoundException("指定的文件路徑不存在!",sourceFile);
byte[]btKey=Encoding.Default.GetBytes(key);
byte[]btIV=Encoding.Default.GetBytes(iv);
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
byte[]btFile=File.ReadAllBytes(sourceFile);
using(FileStreamfs=newFileStream(destFile,FileMode.Create,FileAccess.Write))
{
try
{
using(CryptoStreamcs=newCryptoStream(fs,des.CreateEncryptor(btKey,btIV),CryptoStreamMode.Write))
{
cs.Write(btFile,0,btFile.Length);
cs.FlushFinalBlock();
}
}
catch
{
throw;
}
finally
{
fs.Close();
}
}
}
///<summary>
///對文件內容進行DES加密,加密後覆蓋掉原來的文件
///</summary>
///<paramname="sourceFile">待加密的文件的絕對路徑</param>
publicvoidEncryptFile(stringsourceFile)
{
EncryptFile(sourceFile,sourceFile);
}
///<summary>
///對文件內容進行DES解密
///</summary>
///<paramname="sourceFile">待解密的文件絕對路徑</param>
///<paramname="destFile">解密後的文件保存的絕對路徑</param>
publicvoidDecryptFile(stringsourceFile,stringdestFile)
{
if(!File.Exists(sourceFile))thrownewFileNotFoundException("指定的文件路徑不存在!",sourceFile);
byte[]btKey=Encoding.Default.GetBytes(key);
byte[]btIV=Encoding.Default.GetBytes(iv);
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
byte[]btFile=File.ReadAllBytes(sourceFile);
using(FileStreamfs=newFileStream(destFile,FileMode.Create,FileAccess.Write))
{
try
{
using(CryptoStreamcs=newCryptoStream(fs,des.CreateDecryptor(btKey,btIV),CryptoStreamMode.Write))
{
cs.Write(btFile,0,btFile.Length);
cs.FlushFinalBlock();
}
}
catch
{
throw;
}
finally
{
fs.Close();
}
}
}
///<summary>
///對文件內容進行DES解密,加密後覆蓋掉原來的文件
///</summary>
///<paramname="sourceFile">待解密的文件的絕對路徑</param>
publicvoidDecryptFile(stringsourceFile)
{
DecryptFile(sourceFile,sourceFile);
}
}
}

⑺ JAVA和.NET使用DES對稱加密的區別

JAVA和.NET的系統類庫里都有封裝DES對稱加密的實現方式,但是對外暴露的介面卻各不相同,甚至有時會讓自己難以解決其中的問題,比如JAVA加密後的結果在.NET中解密不出來等,由於最近項目有跨JAVA和.NET的加解密,經過我的分析調試,終於讓它們可以互相加密解密了。

DES加密
DES是一種對稱加密(Data Encryption Standard)演算法,以前我寫過一篇文章:.NET中加密解密相關知識,有過簡單描述。
DES演算法一般有兩個關鍵點,第一個是加密演算法,第二個是數據補位。

加密演算法常見的有ECB模式和CBC模式:
ECB模式:電子密本方式,這是JAVA封裝的DES演算法的默認模式,就是將數據按照8個位元組一段進行DES加密或解密得到一段8個位元組的密文或者明文,最後一段不足8個位元組,則補足8個位元組(注意:這里就涉及到數據補位了)進行計算,之後按照順序將計算所得的數據連在一起即可,各段數據之間互不影響。
CBC模式:密文分組鏈接方式,這是.NET封裝的DES演算法的默認模式,它比較麻煩,加密步驟如下:
1、首先將數據按照8個位元組一組進行分組得到D1D2......Dn(若數據不是8的整數倍,就涉及到數據補位了)
2、第一組數據D1與向量I異或後的結果進行DES加密得到第一組密文C1(注意:這里有向量I的說法,ECB模式下沒有使用向量I)
3、第二組數據D2與第一組的加密結果C1異或以後的結果進行DES加密,得到第二組密文C2
4、之後的數據以此類推,得到Cn
5、按順序連為C1C2C3......Cn即為加密結果。

數據補位一般有NoPadding和PKCS7Padding(JAVA中是PKCS5Padding)填充方式,PKCS7Padding和PKCS5Padding實際只是協議不一樣,根據相關資料說明:PKCS5Padding明確定義了加密塊是8位元組,PKCS7Padding加密快可以是1-255之間。但是封裝的DES演算法默認都是8位元組,所以可以認為他們一樣。數據補位實際是在數據不滿8位元組的倍數,才補充到8位元組的倍數的填充過程。
NoPadding填充方式:演算法本身不填充,比如.NET的padding提供了有None,Zeros方式,分別為不填充和填充0的方式。
PKCS7Padding(PKCS5Padding)填充方式:為.NET和JAVA的默認填充方式,對加密數據位元組長度對8取余為r,如r大於0,則補8-r個位元組,位元組為8-r的值;如果r等於0,則補8個位元組8。比如:
加密字元串為為AAA,則補位為AAA55555;加密字元串為BBBBBB,則補位為BBBBBB22;加密字元串為CCCCCCCC,則補位為CCCCCCCC88888888。

⑻ 誰能幫我將java中的DES演算法改成用C#來實現

C#也有DES加密。

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// DES加密解密
/// </summary>
public static class DES
{

//默認密鑰向量
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

/// <summary>
/// DES加密字元串
/// </summary>
/// <param name="encryptString">待加密的字元串</param>
/// <param name="encryptKey">加密密鑰,要求為8位</param>
/// <returns>加密成功返回加密後的字元串,失敗返回源串</returns>
public static string Encode(string encryptString, string encryptKey)
{
encryptKey = StringHelper.GetSubString(encryptKey, 8, "");
encryptKey = encryptKey.PadRight(8, ' ');
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());

}

/// <summary>
/// DES解密字元串
/// </summary>
/// <param name="decryptString">待解密的字元串</param>
/// <param name="decryptKey">解密密鑰,要求為8位,和加密密鑰相同</param>
/// <returns>解密成功返回解密後的字元串,失敗返源串</returns>
public static string Decode(string decryptString, string decryptKey)
{
try
{
decryptKey = StringHelper.GetSubString(decryptKey, 8, "");
decryptKey = decryptKey.PadRight(8, ' ');
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();

MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return "";
}

}

}

⑼ Java中 DES加密演算法

三個文件:
一:skey_DES.java
//對稱秘鑰生成及對象化保存
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Skey_DES
{
public static void main(String args[])throws Exception
{
KeyGenerator kg=KeyGenerator.getInstance("DESede");
kg.init(168);
SecretKey k=kg.generateKey();
FileOutputStream f=new FileOutputStream("key1.txt");
ObjectOutputStream b= new ObjectOutputStream(f);
b.writeObject(k);
}
};

二:SEnc.java
//對稱秘鑰加密,使用位元組碼
import java.io.*;
import java.security.*;
import javax.crypto.*;

public class SEnc
{
public static void main(String args[]) throws Exception
{
String s="";

FileInputStream f=new FileInputStream("key1.txt");
ObjectInputStream b=new ObjectInputStream(f);
Key k=(Key)b.readObject();
Cipher cp=Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE,k);

byte ptext[]=s.getBytes("UTF8");
for(int i=0;i<ptext.length;i++)
{
System.out.print(ptext[i]+",");
}
System.out.println("");
byte ctext[]=cp.doFinal(ptext);
for(int i=0;i<ctext.length;i++)
{
System.out.print(ctext[i]+",");
}
FileOutputStream f2=new FileOutputStream("SEnc.txt");
f2.write(ctext);
}
};
三:SDec.java
//使用對稱秘鑰解密
import java.io.*;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class SDec
{
public static void main(String args[])throws Exception
{
FileInputStream f=new FileInputStream("SEnc.txt");
int num=f.available();
byte[] ctext=new byte[num];
f.read(ctext);

FileInputStream f2=new FileInputStream("key1.txt");
ObjectInputStream b=new ObjectInputStream(f2);
Key k=(Key)b.readObject();
Cipher cp=Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE,k);

byte[] ptext=cp.doFinal(ctext);
String p=new String(ptext,"UTF8");
System.out.println(p);
}
};

⑽ java要怎麼實現zeropadding的des解密

packagecom.va.util;
importcom.zoki.util.Charset;
importjava.security.;
importjava.security.InvalidKeyException;
importjava.security.NoSuchAlgorithmException;
importjava.security.spec.InvalidKeySpecException;
importjava.util.logging.Level;
importjava.util.logging.Logger;
importjavax.crypto.BadPaddingException;
importjavax.crypto.spec.DESKeySpec;
importjavax.crypto.SecretKeyFactory;
importjavax.crypto.SecretKey;
importjavax.crypto.Cipher;
importjavax.crypto.IllegalBlockSizeException;
importjavax.crypto.NoSuchPaddingException;
importjavax.crypto.spec.IvParameterSpec;
/**
*注意:DES加密和解密過程中,密鑰長度都必須是8的倍數。<br>
*當默認用DES,JAVA會用ECB模式,因此這里IV向量沒有作用,這里,但當用CBC模式下,如果還是用SecureRandom,
*則每次加密的結果都會不一樣,因為JAVA內部會用隨機的IV來初始化Cipher對象,如示例代碼,
*由於Cipher.getInstance("DES/CBC/PKCS5Padding")使用了CBC,
*因此我這里用的javax.crypto.spec.IvParameterSpec包下的IvParameterSpec來初始化向量IV<br>
*JAVA中默認的演算法為ECB,默認填充方式為PKCS5Padding
*/
publicclassDES{
privateDES(){
}
/**
*加密
*
*@paramsrcbyte[]加密的數據源
*@parampasswordbyte[]加密秘鑰
*@returnbyte[]加密後的數據
*/
publicstaticbyte[]encrypt(byte[]src,byte[]password){
try{
DESKeySpecdesKey=newDESKeySpec(password);
//創建一個密匙工廠,然後用它把DESKeySpec轉換成
SecretKeyFactorykeyFactory=SecretKeyFactory.getInstance("DES");
SecretKeysecurekey=keyFactory.generateSecret(desKey);
//Cipher對象實際完成加密操作
Ciphercipher=Cipher.getInstance("DES/CBC/PKCS5Padding");
//ECB模式下,iv不需要
IvParameterSpeciv=newIvParameterSpec(password);
//用密匙初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE,securekey,iv);
//現在,獲取數據並加密
//正式執行加密操作
returncipher.doFinal(src);
}catch(InvalidKeyException|NoSuchAlgorithmException|InvalidKeySpecException|NoSuchPaddingException|IllegalBlockSizeException|BadPaddingException|ex){
Logger.getLogger(DES.class.getName()).log(Level.SEVERE,null,ex);
}
returnnull;
}
/**
*加密
*
*@paramsrcbyte[]加密的數據源
*@parampasswordString加密秘鑰
*@returnbyte[]加密後的數據
*/
publicstaticbyte[]encrypt(byte[]src,Stringpassword){
byte[]keyBytes=password.getBytes(Charset.utf8);
returnencrypt(src,keyBytes);
}
/**
*解密
*
*@paramsrcbyte[]解密的數據源
*@parampasswordbyte[]解密秘鑰
*@returnbyte[]解密後的數據
*/
publicstaticbyte[]decrypt(byte[]src,byte[]password){
try{
//DES演算法要求有一個可信任的隨機數源
//SecureRandomrandom=newSecureRandom();
//創建一個DESKeySpec對象
DESKeySpecdesKey=newDESKeySpec(password);
//創建一個密匙工廠
SecretKeyFactorykeyFactory=SecretKeyFactory.getInstance("DES");
//將DESKeySpec對象轉換成SecretKey對象
SecretKeysecurekey=keyFactory.generateSecret(desKey);
//Cipher對象實際完成解密操作,CBC為加密模式,
Ciphercipher=Cipher.getInstance("DES/CBC/PKCS5Padding");
//ECB模式下,iv不需要
IvParameterSpeciv=newIvParameterSpec(password);
//用密匙初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE,securekey,iv);
//真正開始解密操作
returncipher.doFinal(src);
}catch(InvalidKeyException|NoSuchAlgorithmException|InvalidKeySpecException|NoSuchPaddingException||IllegalBlockSizeException|BadPaddingExceptionex){
Logger.getLogger(DES.class.getName()).log(Level.SEVERE,null,ex);
}
returnnull;
}
/**
*解密
*
*@paramsrcbyte[]解密的數據源
*@parampasswordString解密秘鑰
*@returnbyte[]解密後的數據
*/
publicstaticbyte[]decrypt(byte[]src,Stringpassword){
byte[]keyBytes=password.getBytes(Charset.utf8);
returndecrypt(src,keyBytes);
}
}

閱讀全文

與java向量des相關的資料

熱點內容
解壓的玩具教程可愛版 瀏覽:364
哪個求職app比較靠譜 瀏覽:886
java的讀法 瀏覽:59
nod32區域網伺服器地址 瀏覽:1000
數碼科技解壓 瀏覽:235
新網的雲伺服器管理界面復雜嗎 瀏覽:367
無人聲解壓強迫症視頻 瀏覽:571
計算機編譯運行 瀏覽:639
單片機嵌套 瀏覽:988
python字元串中符號 瀏覽:787
python正則表達式貪婪模式 瀏覽:648
愛國精神指的是什麼app 瀏覽:408
壽司解壓系列全集視頻 瀏覽:913
物體三維重建演算法 瀏覽:984
fuli直播app哪個好 瀏覽:918
租辦公室用什麼app 瀏覽:106
醫師定期考核刷題app哪個好 瀏覽:338
導出dmp文件命令 瀏覽:288
手機百度網盤怎麼解壓密碼文件 瀏覽:585
索引重新編譯 瀏覽:606