可能很長
,這是在我以前一個程序里摘出來的。
原理:用戶輸入創建密碼,機器讀取,並把每一位密碼進行加密,這里就是把每一位的
ascii碼加一(也可以有其他的加密方式),然後保存在文件里。解密時從文件中讀取保存的亂碼,然後把它每一位的asc
Ⅱ 如何實現c和java的des互相加解密
/*
* MD5 演算法
*/
public class MD5 {
// 全局數組
private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public MD5() {
}
// 返回形式為數字跟字元串
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
// System.out.println("iRet="+iRet);
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return strDigits[iD1] + strDigits[iD2];
}
// 返回形式只為數字
private static String byteToNum(byte bByte) {
int iRet = bByte;
System.out.println("iRet1=" + iRet);
if (iRet < 0) {
iRet += 256;
}
return String.valueOf(iRet);
}
// 轉換位元組數組為16進制字串
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}
public static String GetMD5Code(String strObj) {
String resultString = null;
try {
resultString = new String(strObj);
MessageDigest md = MessageDigest.getInstance("MD5");
// md.digest() 該函數返回值為存放哈希值結果的byte數組
resultString = byteToString(md.digest(strObj.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}
public static void main(String[] args) {
MD5 getMD5 = new MD5();
System.out.println(getMD5.GetMD5Code("000000"));
}
}
Ⅲ 如題,求Java的DES演算法代碼,可以用於解密用C語言寫的DES加密演算法!其中C語言代碼見問題補充
俺就是來幫助你這樣可愛的人。俺可是花了幾年的時間費了多大的力氣才能把這個東西弄出來!
DES加密還沒有AES嚴密:
packagecom.palic.pss.afcs.worldthrough.common.util;
importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;
importrepack.com.thoughtworks.xstream.core.util.Base64Encoder;
/**
*AES加密解密
*@author
*
*/
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+"毫秒");
}
}
Ⅳ 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;
}
}
Ⅳ des解密演算法,利用C語言解密JAVA語言加密的密碼。。密鑰為12345678,加密後的密文為:26d086be3a3a62fc
// C 語言 DES用的是 ECB模式, 沒有填充
// 因此Java端要對應, 你的明文是 liubiao 嗎?
// 另外 DES已經不安全了, 如果可以改為 3DES或者 AES吧。
public class LearnDes {
public static void main(String[] args) {
try {
System.out.println(encrypt("liubiao", "12345678"));
System.out.println(decrypt("26d086be3a3a62fc", "12345678"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encrypt(String message, String key) throws Exception {
//Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
Cipher cipher = Cipher.getInstance("DES/ECB/NOPADDING");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
//cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey );
return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
}
public static String decrypt(String message, String key) throws Exception {
byte[] bytesrc = convertHexString(message);
//Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
Cipher cipher = Cipher.getInstance("DES/ECB/NOPADDING");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
//cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey );
byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte);
}
public static byte[] convertHexString(String ss) {
byte digest[] = new byte[ss.length() / 2];
for (int i = 0; i < digest.length; i++) {
String byteString = ss.substring(2 * i, 2 * i + 2);
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte) byteValue;
}
return digest;
}
public static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;
hexString.append(plainText);
}
return hexString.toString();
}
}
Ⅵ Des加密解密方法 用java C#和C++三種方式實現
Solaris下的系統,有一個用C做的加密工具,調用Sunwcry的des(1)對文件進行加密,然後在java中對文件進行解密。java中用的是標準的DES/CBC/NoPadding演算法,可是解密後發現開頭有8byte的數據出錯了,請高人指點一下。
cbc_encrypt.c : 加密用的C程序
cbc_decrypt.c:解密用的C程序
TestDescbc.java:解密用的java程序
Test01.dat原始文件
Test03.dat cbc_encrypt加密後的文件
Test05.dat cbc_decrypt解密後的文件
Test06.dat TestDescbc解密後的文件
Ⅶ 如何使用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 和 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);
}
}
}
Ⅸ DES加密解密問題 java與C 通訊
經測試應該是如下問題:
1.注意取字元串bytes是編碼保持一致,c的和java的保存一直,問一下c開發用的是那個。
2.key和Iv保持一致
3.加密模式和填充方式保持一致----------------------------這點的可能性比較大
比如C#里
algo.Mode=CipherMode.ECB;
algo.Padding=PaddingMode.None;
則java里對應的為
final Cipher algo=Cipher.getInstance("DES/ECB/NoPadding");
import java.io.IOException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DesUtil {
private final static String DES = "DES";
public static void main(String[] args) throws Exception {
String data = "fff";//原字元
String key = "80825cf7fedff723";//加密key
System.err.println(encrypt(data, key));
System.err.println(decrypt("FAQXWvLnsSA=", key));//進行解密「FAQXWvLnsSA=」
}
/**
* Description 根據鍵值進行加密
* @param data
* @param key 加密鍵byte數組
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
byte[] bt = encrypt(data.getBytes(), key.getBytes());
String strs = new BASE64Encoder().encode(bt);
return strs;
}
/**
* Description 根據鍵值進行解密
* @param data
* @param key 加密鍵byte數組
* @return
* @throws IOException
* @throws Exception
*/
public static String decrypt(String data, String key) throws IOException,
Exception {
if (data == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf,key.getBytes());
return new String(bt);
}
/**
* Description 根據鍵值進行加密
* @param data
* @param key 加密鍵byte數組
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
// 從原始密鑰數據創建DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);
// 創建一個密鑰工廠,然後用它把DESKeySpec轉換成SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher對象實際完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密鑰初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
/**
* Description 根據鍵值進行解密
* @param data
* @param key 加密鍵byte數組
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
// 生成一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
// 從原始密鑰數據創建DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);
// 創建一個密鑰工廠,然後用它把DESKeySpec轉換成SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密鑰初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
}
Ⅹ java與C# DES 字元串加解密,求c#的加解密方法
你先把java的一個字元比如12345,用已知的key加密,然後同樣在C#里用同樣的數據加密,比較一下加密的結果是否一樣,如果一樣再說解密的事。