導航:首頁 > 編程語言 > desedejava

desedejava

發布時間:2023-04-07 09:56:43

java加密解密代碼

package com.cube.limail.util;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;/**
* 加密解密類
*/
public class Eryptogram
{
private static String Algorithm ="DES";
private String key="CB7A92E3D3491964";
//定義 加密演算法,可用 DES,DESede,Blowfish
static boolean debug = false ;
/**
* 構造子註解.
*/
public Eryptogram ()
{

} /**
* 生成密鑰
* @return byte[] 返回生成的密鑰
* @throws exception 扔出異常.
*/
public static byte [] getSecretKey () throws Exception
{
KeyGenerator keygen = KeyGenerator.getInstance (Algorithm );
SecretKey deskey = keygen.generateKey ();
System.out.println ("生成密鑰:"+bytesToHexString (deskey.getEncoded ()));
if (debug ) System.out.println ("生成密鑰:"+bytesToHexString (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 ("加密前的二進串:"+byte2hex (input ));
System.out.println ("加密前的字元串:"+new String (input ));

} Cipher c1 = Cipher.getInstance (Algorithm );
c1.init (Cipher.ENCRYPT_MODE ,deskey );
byte [] cipherByte =c1.doFinal (input );
if (debug ) System.out.println ("加密後的二進串:"+byte2hex (cipherByte ));
return cipherByte ;

} /**
* 將給定的已加密的數據通過指定的密鑰進行解密
* @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 ("解密前的信息:"+byte2hex (input ));
Cipher c1 = Cipher.getInstance (Algorithm );
c1.init (Cipher.DECRYPT_MODE ,deskey );
byte [] clearByte =c1.doFinal (input );
if (debug )
{
System.out.println ("解密後的二進串:"+byte2hex (clearByte ));
System.out.println ("解密後的字元串:"+(new String (clearByte )));

} return clearByte ;

} /**
* 位元組碼轉換成16進制字元串
* @param byte[] b 輸入要轉換的位元組碼
* @return String 返回轉換後的16進制字元串
*/
public static 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 ;
if (n <b.length -1 ) hs =hs +":";

} return hs.toUpperCase ();

}

/**
* 字元串轉成位元組數組.
* @param hex 要轉化的字元串.
* @return byte[] 返回轉化後的字元串.
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}

/**
* 位元組數組轉成字元串.
* @param String 要轉化的字元串.
* @return 返回轉化後的位元組數組.
*/
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}

/**
* 從資料庫中獲取密鑰.
* @param deptid 企業id.
* @return 要返回的位元組數組.
* @throws Exception 可能拋出的異常.
*/
public static byte[] getSecretKey(long deptid) throws Exception {
byte[] key=null;
String value=null;
//CommDao =new CommDao();
// List list=.getRecordList("from Key k where k.deptid="+deptid);
//if(list.size()>0){
//value=((com.csc.sale.bean.Key)list.get(0)).getKey();
value = "CB7A92E3D3491964";
key=hexStringToByte(value);
//}
if (debug)
System.out.println("密鑰:" + value);
return key;
}

public String encryptData2(String data) {
String en = null;
try {
byte[] key=hexStringToByte(this.key);
en = bytesToHexString(encryptData(data.getBytes(),key));
} catch (Exception e) {
e.printStackTrace();
}
return en;
}

public String decryptData2(String data) {
String de = null;
try {
byte[] key=hexStringToByte(this.key);
de = new String(decryptData(hexStringToByte(data),key));
} catch (Exception e) {
e.printStackTrace();
}
return de;
}
} 加密使用: byte[] key=Eryptogram.getSecretKey(deptid); //獲得鑰匙(位元組數組)
byte[] tmp=Eryptogram.encryptData(password.getBytes(), key); //傳入密碼和鑰匙,獲得加密後的位元組數組的密碼
password=Eryptogram.bytesToHexString(tmp); //將位元組數組轉化為字元串,獲得加密後的字元串密碼解密與之差不多

⑵ C#加密Java解密

DES加密 java與 C# 可以相互加密解密
這里的KEY採用Base64編碼,便用分發,因為Java的Byte范圍為-128至127,c#的Byte范圍是0-255
核心是確定Mode和Padding,關於這兩個的意思可以搜索3DES演算法相關文章
一個是C#採用CBC Mode,PKCS7 Padding,Java採用CBC Mode,PKCS5Padding Padding,
另一個是C#採用ECB Mode,PKCS7 Padding,Java採用ECB Mode,PKCS5Padding Padding,
Java的ECB模式不需要IV
對字元加密時,雙方採用的都是UTF-8編碼
C# 代碼

/// <summary>
/// DES3加密解密
/// </summary>
public class Des3
{
#region CBC模式**
/// <summary>
/// DES3 CBC模式加密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV</param>
/// <param name="data">明文的byte數組</param>
/// <returns>密文的byte數組</returns>
public static byte[] Des3EncodeCBC( byte[] key, byte[] iv, byte[] data )
{
//復制於MSDN
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
tdsp = new ();
tdsp.Mode = CipherMode.CBC; //默認值
tdsp.Padding = PaddingMode.PKCS7; //默認值
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream( mStream,
tdsp.CreateEncryptor( key, iv ),
CryptoStreamMode.Write );
// Write the byte array to the crypto stream and flush it.
cStream.Write( data, 0, data.Length );
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
/// <summary>
/// DES3 CBC模式解密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV</param>
/// <param name="data">密文的byte數組</param>
/// <returns>明文的byte數組</returns>
public static byte[] Des3DecodeCBC( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream( data );
tdsp = new ();
tdsp.Mode = CipherMode.CBC;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream( msDecrypt,
tdsp.CreateDecryptor( key, iv ),
CryptoStreamMode.Read );
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Length );
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
#endregion
#region ECB模式
/// <summary>
/// DES3 ECB模式加密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV(當模式為ECB時,IV無用)</param>
/// <param name="str">明文的byte數組</param>
/// <returns>密文的byte數組</returns>
public static byte[] Des3EncodeECB( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
tdsp = new ();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream( mStream,
tdsp.CreateEncryptor( key, iv ),
CryptoStreamMode.Write );
// Write the byte array to the crypto stream and flush it.
cStream.Write( data, 0, data.Length );
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
/// <summary>
/// DES3 ECB模式解密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV(當模式為ECB時,IV無用)</param>
/// <param name="str">密文的byte數組</param>
/// <returns>明文的byte數組</returns>
public static byte[] Des3DecodeECB( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream( data );
tdsp = new ();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream( msDecrypt,
tdsp.CreateDecryptor( key, iv ),
CryptoStreamMode.Read );
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Length );
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
#endregion
/// <summary>
/// 類測試
/// </summary>
public static void Test()
{
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
//key為abcdefghijklmnopqrstuvwx的Base64編碼
byte[] key = Convert.FromBase64String( "" );
byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; //當模式為ECB時,IV無用
byte[] data = utf8.GetBytes( "中國ABCabc123" );
System.Console.WriteLine( "ECB模式:" );
byte[] str1 = Des3.Des3EncodeECB( key, iv, data );
byte[] str2 = Des3.Des3DecodeECB( key, iv, str1 );
System.Console.WriteLine( Convert.ToBase64String( str1 ) );
System.Console.WriteLine( System.Text.Encoding.UTF8.GetString( str2 ) );
System.Console.WriteLine();
System.Console.WriteLine( "CBC模式:" );
byte[] str3 = Des3.Des3EncodeCBC( key, iv, data );
byte[] str4 = Des3.Des3DecodeCBC( key, iv, str3 );
System.Console.WriteLine( Convert.ToBase64String( str3 ) );
System.Console.WriteLine( utf8.GetString( str4 ) );
System.Console.WriteLine();
}
}
java 代碼:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Des3 {
public static void main(String[] args) throws Exception {
byte[] key=new BASE64Decoder().decodeBuffer("");
byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] data="中國ABCabc123".getBytes("UTF-8");

System.out.println("ECB加密解密");
byte[] str3 = des3EncodeECB(key,data );
byte[] str4 = ees3DecodeECB(key, str3);
System.out.println(new BASE64Encoder().encode(str3));
System.out.println(new String(str4, "UTF-8"));
System.out.println();
System.out.println("CBC加密解密");
byte[] str5 = des3EncodeCBC(key, keyiv, data);
byte[] str6 = des3DecodeCBC(key, keyiv, str5);
System.out.println(new BASE64Encoder().encode(str5));
System.out.println(new String(str6, "UTF-8"));
}
/**
* ECB加密,不要IV
* @param key 密鑰
* @param data 明文
* @return Base64編碼的密文
* @throws Exception
*/
public static byte[] des3EncodeECB(byte[] key, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, deskey);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* ECB解密,不要IV
* @param key 密鑰
* @param data Base64編碼的密文
* @return 明文
* @throws Exception
*/
public static byte[] ees3DecodeECB(byte[] key, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, deskey);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* CBC加密
* @param key 密鑰
* @param keyiv IV
* @param data 明文
* @return Base64編碼的密文
* @throws Exception
*/
public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* CBC解密
* @param key 密鑰
* @param keyiv IV
* @param data Base64編碼的密文
* @return 明文
* @throws Exception
*/
public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
}

⑶ 如何用Java進行3DES加密解密

Java進行3DES加密解密代碼如下:

<preclass="java"name="code">publicstaticStringbyte2hex(byte[]b){

Stringhs="";

Stringstmp="";

for(intn=0;n<b.length;n++){

stmp=Integer.toHexString(b[n]&0xFF);

if(stmp.length()==1)

hs+=("0"+stmp);

else

hs+=stmp;

}

returnhs.toUpperCase();

}</pre><br>

<pre></pre>

<p><br>

3DES的加密密鑰長度要求是24個位元組,本例中因為給定的密鑰只有16個位元組,所以需要填補至24個位元組。</p>

<p>其中"DESede/ECB/NoPadding",除此之外,3DES還支持"<spanstyle="color:#0000ff">DESede/CBC/PKCS5Padding</span>"模式。</p>

⑷ 如何用Java進行3DES加密解

有專門方法的,可以參考:攔洞租
import java.security.MessageDigest;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class TripleDESTest {

public static void main(String[] args) throws Exception {

String text = "kyle boon";

byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);

System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "kyle boon"
}

public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.Of(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}

final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);

final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
//簡兆 .encode(cipherText);

return cipherText;
}

public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"顫指
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.Of(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}

final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);

// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);

return new String(plainText, "UTF-8");
}
}

⑸ Java的des3解密方法。轉成c#

byte[] iv = utf8.GetBytes("25439768");改成byte[] iv = Convert.FromBase64String("25439768")

⑹ 如何用Java進行3DES加密解

最近一個合作商提出使用3DES交換數據,本來橡游尺他們有現成的代碼,可惜只有.net版本,我們的伺服器都是Linux,而且應用都是Java。於是對照他們提供的代碼改了一個Java的版本出來,主要是不熟悉3DES,折騰了一天,終於搞定。
所謂3DES,就是把DES做三次,當然不是簡單地DES DES DES就行了,中途有些特定的排列。這個我可不關心,呵呵,我的目的是使用它。
在網上搜索了一下3DES,找到很少資料。經過朋友介紹,找到GNU Crypto和Bouncy Castle兩個Java擴充包,裡面應該有3DES的實現吧。
從GNU Crypto入手,找到一個TripleDES的實現類,發現原來3DES還有一個名字叫DESede,在網上搜索TripleDES和DESede,呵呵,終於發現更多的資料了。
Java的安全API始終那麼難用,先創建一個cipher看看演算法在不在吧
Cipher cipher = Cipher.getInstance("DESede");

如果沒有拋異磨彎常的話,就證明這個演算法是有效的
突然想看看JDK有沒有內置DESede,於是撇開Crypto,直接測試,發現可以正確運行。在jce.jar裡面找到相關的類,JDK內置了。
於是直接用DES的代碼來改&測試,最後代碼變成這樣
SecureRandom sr = new SecureRandom();
DESedeKeySpec dks = new DESedeKeySpec(PASSWORD_CRYPT_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return new String(Hex.encodeHex(cipher.doFinal(str.getBytes())));

需要留意的是,要使用DESede的Spec、Factory和Cipher才行
事情還沒完結,合作商給過來的除了密鑰之外,還有一個IV向量。搜索了一下,發現有一個IvParameterSpec類,於是代碼變成這樣
SecureRandom sr = new SecureRandom();
DESedeKeySpec dks = new DESedeKeySpec(PASSWORD_CRYPT_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
IvParameterSpec iv = new IvParameterSpec(PASSWORD_IV.getBytes());
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, securekey, iv, sr);
return new String(Hex.encodeHex(cipher.doFinal(str.getBytes())));

但是,運行報錯了
java.security.: ECB mode cannot use IV

ECB是什麼呢?我的代碼完全沒有梁高寫ECB什麼的
又上網搜索,結果把DES的來龍去脈都搞清楚了

⑺ java的 DES 加密解密方法 求對應php的加密解密方法!!!!急切

DES是一種標準的數據加密演算法,關於這個演算法的詳細介紹可以參考wiki和網路:

php中有一個擴展可以支持DES的加密演算法,是:extension=php_mcrypt.dll

在配置文件中將這個擴展打開還不能夠在windows環境下使用

需要將PHP文件夾下的 libmcrypt.dll 拷貝到系統的 system32 目錄下,這是通過phpinfo可以查看到mcrypt表示這個模塊可以正常試用了。

下面是PHP中使用DES加密解密的一個例子:

//$input-stufftodecrypt
//$key-thesecretkeytouse

functiondo_mencrypt($input,$key)
{
$input=str_replace(""n","",$input);
$input=str_replace(""t","",$input);
$input=str_replace(""r","",$input);
$key=substr(md5($key),0,24);
$td=mcrypt_mole_open('tripledes','','ecb','');
$iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($td),MCRYPT_RAND);
mcrypt_generic_init($td,$key,$iv);
$encrypted_data=mcrypt_generic($td,$input);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
returntrim(chop(base64_encode($encrypted_data)));
}
//$input-stufftodecrypt
//$key-thesecretkeytouse

functiondo_mdecrypt($input,$key)
{
$input=str_replace(""n","",$input);
$input=str_replace(""t","",$input);
$input=str_replace(""r","",$input);
$input=trim(chop(base64_decode($input)));
$td=mcrypt_mole_open('tripledes','','ecb','');
$key=substr(md5($key),0,24);
$iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($td),MCRYPT_RAND);
mcrypt_generic_init($td,$key,$iv);
$decrypted_data=mdecrypt_generic($td,$input);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
returntrim(chop($decrypted_data));
}

參考自:http://www.cnblogs.com/cocowool/archive/2009/01/07/1371309.html

⑻ 如何用Java進行3DES加密解密

這里是例子,直接拿來用就可以了。
package com.nnff.des;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/*字元孝姿耐串冊談 DESede(3DES) 加密
* ECB模式/使用PKCS7方式填充不足位,目前給的密鑰是192位
* 3DES(即Triple DES)是DES向AES過渡的加密演算法(1999年,NIST將3-DES指定為過渡的
* 加密標准),是DES的一個更安全的巧春變形。它以DES為基本模塊,通過組合分組方法設計出分組加
* 密演算法,其具體實現如下:設Ek()和Dk()代表DES演算法的加密和解密過程,K代表DES演算法使用的
* 密鑰,P代表明文,C代表密表,這樣,
* 3DES加密過程為:C=Ek3(Dk2(Ek1(P)))
* 3DES解密過程為:P=Dk1((EK2(Dk3(C)))
* */
public class ThreeDes {

/**
* @param args在java中調用sun公司提供的3DES加密解密演算法時,需要使
* 用到$JAVA_HOME/jre/lib/目錄下如下的4個jar包:
*jce.jar
*security/US_export_policy.jar
*security/local_policy.jar
*ext/sunjce_provider.jar
*/

private static final String Algorithm = "DESede"; //定義加密演算法,可用 DES,DESede,Blowfish
//keybyte為加密密鑰,長度為24位元組
//src為被加密的數據緩沖區(源)
public static byte[] encryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);//在單一方面的加密或解密
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}

//keybyte為加密密鑰,長度為24位元組
//src為加密後的緩沖區
public static byte[] decryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//解密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}

//轉換成十六進制字元串
public static 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;
}
if(n<b.length-1)hs=hs+":";
}
return hs.toUpperCase();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加新安全演算法,如果用JCE就要把它添加進去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
final byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58,
(byte)0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51,
(byte)0xCB,
(byte)0xDD, 0x55, 0x66, 0x77, 0x29, 0x74,
(byte)0x98, 0x30, 0x40, 0x36,
(byte)0xE2
}; //24位元組的密鑰
String szSrc = "This is a 3DES test. 測試";
System.out.println("加密前的字元串:" + szSrc);
byte[] encoded = encryptMode(keyBytes,szSrc.getBytes());
System.out.println("加密後的字元串:" + new String(encoded));

byte[] srcBytes = decryptMode(keyBytes,encoded);
System.out.println("解密後的字元串:" + (new String(srcBytes)));
}
}

⑼ 如何使用JAVA實現對字元串的DES加密和解密

java加密字元串可以使用des加密演算法,實例如下:
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 加密解密
*
* @author shy.qiu
* @since http://blog.csdn.net/qiushyfm
*/
public class CryptTest {
/**
* 進行MD5加密
*
* @param info
* 要加密的信息
* @return String 加密後的字元串
*/
public String encryptToMD5(String info) {
byte[] digesta = null;
try {
// 得到一個md5的消息摘要
MessageDigest alga = MessageDigest.getInstance("MD5");
// 添加要進行計算摘要的信息
alga.update(info.getBytes());
// 得到該摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 將摘要轉為字元串
String rs = byte2hex(digesta);
return rs;
}
/**
* 進行SHA加密
*
* @param info
* 要加密的信息
* @return String 加密後的字元串
*/
public String encryptToSHA(String info) {
byte[] digesta = null;
try {
// 得到一個SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要進行計算摘要的信息
alga.update(info.getBytes());
// 得到該摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 將摘要轉為字元串
String rs = byte2hex(digesta);
return rs;
}
// //////////////////////////////////////////////////////////////////////////
/**
* 創建密匙
*
* @param algorithm
* 加密演算法,可用 DES,DESede,Blowfish
* @return SecretKey 秘密(對稱)密鑰
*/
public SecretKey createSecretKey(String algorithm) {
// 聲明KeyGenerator對象
KeyGenerator keygen;
// 聲明 密鑰對象
SecretKey deskey = null;
try {
// 返回生成指定演算法的秘密密鑰的 KeyGenerator 對象
keygen = KeyGenerator.getInstance(algorithm);
// 生成一個密鑰
deskey = keygen.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 返回密匙
return deskey;
}
/**
* 根據密匙進行DES加密
*
* @param key
* 密匙
* @param info
* 要加密的信息
* @return String 加密後的信息
*/
public String encryptToDES(SecretKey key, String info) {
// 定義 加密演算法,可用 DES,DESede,Blowfish
String Algorithm = "DES";
// 加密隨機數生成器 (RNG),(可以不寫)
SecureRandom sr = new SecureRandom();
// 定義要生成的密文
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密鑰和模式初始化Cipher對象
// 參數:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
c1.init(Cipher.ENCRYPT_MODE, key, sr);
// 對要加密的內容進行編碼處理,
cipherByte = c1.doFinal(info.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
// 返回密文的十六進制形式
return byte2hex(cipherByte);
}
/**
* 根據密匙進行DES解密
*
* @param key
* 密匙
* @param sInfo
* 要解密的密文
* @return String 返回解密後信息
*/
public String decryptByDES(SecretKey key, String sInfo) {
// 定義 加密演算法,
String Algorithm = "DES";
// 加密隨機數生成器 (RNG)
SecureRandom sr = new SecureRandom();
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密鑰和模式初始化Cipher對象
c1.init(Cipher.DECRYPT_MODE, key, sr);
// 對要解密的內容進行編碼處理
cipherByte = c1.doFinal(hex2byte(sInfo));
} catch (Exception e) {
e.printStackTrace();
}
// return byte2hex(cipherByte);
return new String(cipherByte);
}
// /////////////////////////////////////////////////////////////////////////////
/**
* 創建密匙組,並將公匙,私匙放入到指定文件中
*
* 默認放入mykeys.bat文件中
*/
public void createPairKey() {
try {
// 根據特定的演算法一個密鑰對生成器
KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
// 加密隨機數生成器 (RNG)
SecureRandom random = new SecureRandom();
// 重新設置此隨機對象的種子
random.setSeed(1000);
// 使用給定的隨機源(和默認的參數集合)初始化確定密鑰大小的密鑰對生成器
keygen.initialize(512, random);// keygen.initialize(512);
// 生成密鑰組
KeyPair keys = keygen.generateKeyPair();
// 得到公匙
PublicKey pubkey = keys.getPublic();
// 得到私匙
PrivateKey prikey = keys.getPrivate();
// 將公匙私匙寫入到文件當中
doObjToFile("mykeys.bat", new Object[] { prikey, pubkey });
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 利用私匙對信息進行簽名 把簽名後的信息放入到指定的文件中
*
* @param info
* 要簽名的信息
* @param signfile
* 存入的文件
*/
public void signToInfo(String info, String signfile) {
// 從文件當中讀取私匙
PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
// 從文件中讀取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
try {
// Signature 對象可用來生成和驗證數字簽名
Signature signet = Signature.getInstance("DSA");
// 初始化簽署簽名的私鑰
signet.initSign(myprikey);
// 更新要由位元組簽名或驗證的數據
signet.update(info.getBytes());
// 簽署或驗證所有更新位元組的簽名,返回簽名
byte[] signed = signet.sign();
// 將數字簽名,公匙,信息放入文件中
doObjToFile(signfile, new Object[] { signed, mypubkey, info });
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 讀取數字簽名文件 根據公匙,簽名,信息驗證信息的合法性
*
* @return true 驗證成功 false 驗證失敗
*/
public boolean validateSign(String signfile) {
// 讀取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
// 讀取簽名
byte[] signed = (byte[]) getObjFromFile(signfile, 1);
// 讀取信息
String info = (String) getObjFromFile(signfile, 3);
try {
// 初始一個Signature對象,並用公鑰和簽名進行驗證
Signature signetcheck = Signature.getInstance("DSA");
// 初始化驗證簽名的公鑰
signetcheck.initVerify(mypubkey);
// 使用指定的 byte 數組更新要簽名或驗證的數據
signetcheck.update(info.getBytes());
System.out.println(info);
// 驗證傳入的簽名
return signetcheck.verify(signed);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將二進制轉化為16進制字元串
*
* @param b
* 二進制位元組數組
* @return String
*/
public String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
/**
* 十六進制字元串轉化為2進制
*
* @param hex
* @return
*/
public byte[] hex2byte(String hex) {
byte[] ret = new byte[8];
byte[] tmp = hex.getBytes();
for (int i = 0; i < 8; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/**
* 將兩個ASCII字元合成一個位元組; 如:"EF"--> 0xEF
*
* @param src0
* byte
* @param src1
* byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 將指定的對象寫入指定的文件
*
* @param file
* 指定寫入的文件
* @param objs
* 要寫入的對象
*/
public void doObjToFile(String file, Object[] objs) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
for (int i = 0; i < objs.length; i++) {
oos.writeObject(objs[i]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 返回在文件中指定位置的對象
*
* @param file
* 指定的文件
* @param i
* 從1開始
* @return
*/
public Object getObjFromFile(String file, int i) {
ObjectInputStream ois = null;
Object obj = null;
try {
FileInputStream fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
for (int j = 0; j < i; j++) {
obj = ois.readObject();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
/**
* 測試
*
* @param args
*/
public static void main(String[] args) {
CryptTest jiami = new CryptTest();
// 執行MD5加密"Hello world!"
System.out.println("Hello經過MD5:" + jiami.encryptToMD5("Hello"));
// 生成一個DES演算法的密匙
SecretKey key = jiami.createSecretKey("DES");
// 用密匙加密信息"Hello world!"
String str1 = jiami.encryptToDES(key, "Hello");
System.out.println("使用des加密信息Hello為:" + str1);
// 使用這個密匙解密
String str2 = jiami.decryptByDES(key, str1);
System.out.println("解密後為:" + str2);
// 創建公匙和私匙
jiami.createPairKey();
// 對Hello world!使用私匙進行簽名
jiami.signToInfo("Hello", "mysign.bat");
// 利用公匙對簽名進行驗證。
if (jiami.validateSign("mysign.bat")) {
System.out.println("Success!");
} else {
System.out.println("Fail!");
}
}
}

⑽ des密鑰如何生成 java

package Encrypt;
import java.security.*;
import javax.crypto.*;
import sun.misc.*;
/**
* 使用DES加密與解密,可對byte[],String類型進行加密與解密
* 密文可使用String,byte[]存儲.
* 方法:
* void getKey(String strKey)從strKey的字條生成一個Key
* String getEncString(String strMing)對strMing進行加密,返回String密文
* String getDesString(String strMi)對strMin進行解密,返回String明文
* byte[] getEncCode(byte[] byteS)byte[]型的加密
* byte[] getDesCode(byte[] byteD)byte[]型的解密
*/
public class Encrypt{
private Key key;
private byte[] byteMi = null;
private byte[] byteMing = null;
private String strMi= "";
private String strM= "";
// 根據參數生成KEY
public void setKey(String strKey){
try{
KeyGenerator _generator = KeyGenerator.getInstance("DES");
_generator.init(new SecureRandom(strKey.getBytes()));
this.key = _generator.generateKey();
_generator=null;
}
catch(Exception e){
e.printStackTrace();
}

}
// 加密String明文輸入,String密文輸出
public void setEncString(String strMing){
BASE64Encoder base64en = new BASE64Encoder();
try {
this.byteMing = strMing.getBytes("UTF8");
this.byteMi = this.getEncCode(this.byteMing);
this.strMi = base64en.encode(this.byteMi);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{

this.byteMing = null;
this.byteMi = null;
}
}
//加密以byte[]明文輸入,byte[]密文輸出
private byte[] getEncCode(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;
}
// 解密:以String密文輸入,String明文輸出
public void setDesString(String strMi){
BASE64Decoder base64De = new BASE64Decoder();
try
{
this.byteMi = base64De.decodeBuffer(strMi);
this.byteMing = this.getDesCode(byteMi);
this.strM = new String(byteMing,"UTF8");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
base64De = null;
byteMing = null;
byteMi = null;
}

}
// 解密以byte[]密文輸入,以byte[]明文輸出
private byte[] getDesCode(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)
{
e.printStackTrace();
}
finally
{
cipher=null;
}
return byteFina;
}
//返回加密後的密文strMi
public String getStrMi()
{
return strMi;
}
//返回解密後的明文
public String getStrM()
{
return strM;
}
}
*注意:因為我用的時候是作為後台的BEAN來調用的,所以沒有寫main函數,也就不能直接運行了。必須加一個main()函數才能做為一個完成的JAVA程序使用。一個很簡單的 main()函數就ok了,不用我寫在這里了吧?呵呵!

在WEB前台調用這個BEAN文件時的語句:
<jsp:useBean id="abc" scope="page" class="oaweb.Encrypt" />
//id="abc" 用來初始化一個對象
<%
//明文加密:
String key = 「06」; //初始化密鑰。
abc.setKey(key); //調用set函數設置密鑰。
abc.setEncString(re[i][j]);//將要加密的明文傳送給Encrypt.java進行加密計算。
String Mi=abc.getStrMi(); //調用get函數獲取加密後密文。
%>
//變數Mi就是密文.
<%
//密文解密:
abc. setDesString(String Mi); //將要解密的密文傳送給Encrypt.java進行解密計算。
String M=abc. String getStrM(); //調用get函數獲取解密後明文。
%>
//變數M就是明文.

閱讀全文

與desedejava相關的資料

熱點內容
linuxsftp連接 瀏覽:934
光伏日發電量演算法 瀏覽:125
小肚皮app怎麼才有vip 瀏覽:616
php全形轉換半形 瀏覽:927
java字元序列 瀏覽:539
杭州編譯分布式存儲區塊鏈 瀏覽:575
材料壓縮曲線 瀏覽:247
linux命令排序 瀏覽:151
手機熱點加密為啥連接不上電腦 瀏覽:979
編譯器合並計算 瀏覽:959
android音頻曲線 瀏覽:343
linuxftp自動登錄 瀏覽:802
運行編譯後網頁 瀏覽:70
閱讀app怎麼使用 瀏覽:319
centos防火牆命令 瀏覽:432
命令行變更 瀏覽:332
linux設備和驅動 瀏覽:207
加密貨幣騙局破案 瀏覽:345
cc特徵碼加密 瀏覽:775
清空dns緩存命令 瀏覽:295