Java中3DES加密解密示例
在java中调用sun公司提供的3DES加密解密算法时,需要使用到$JAVA_HOME/jre/lib/目录下如下的4个jar包:
jce.jar
security/US_export_policy.jar
security/local_policy.jar
ext/sunjce_provider.jar
Java运行时会自动加载这些包,因此对于带main函数的应用程序不需要设置到CLASSPATH环境变量中。
对于WEB应用,不需要把这些包加到WEB-INF/lib目录下。
以下是java中调用sun公司提供的3DES加密解密算法的样本代码:
加密解密代码
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/*字符串 DESede(3DES) 加密*/
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(ng.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(ng.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 = (ng.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中进行数据的加密和解密
如何在Java中进行数据的加密和解密在Java中,有多种加密和解密的算法可供选择,如对称加密算法、非对称加密算法和哈希算法等。
下面将介绍几种常见的加密和解密方法。
1.对称加密算法对称加密算法指的是使用相同密钥进行加密和解密的算法,常见的对称加密算法有DES、3DES、AES等。
DES加密算法是一种对称密钥算法,加密解密使用相同的密钥,密钥长度为56位。
以下是使用DES加密和解密的示例代码:```javaimport javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;public class DESExample {public static void main(String[] args) throws Exception { String plainText = "Hello World";String key = "abcdefgh"; //密钥必须是8位长度byte[] encryptedBytes = desEncrypt(plainText.getBytes(), key.getBytes());byte[] decryptedBytes = desDecrypt(encryptedBytes,key.getBytes());String decryptedText = new String(decryptedBytes);System.out.println("解密后的文本:" + decryptedText);}public static byte[] desEncrypt(byte[] plainText, byte[] keyBytes) throws Exception {SecretKey key = new SecretKeySpec(keyBytes, "DES");Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, key);return cipher.doFinal(plainText);}public static byte[] desDecrypt(byte[] cipherText, byte[] keyBytes) throws Exception {SecretKey key = new SecretKeySpec(keyBytes, "DES");Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.DECRYPT_MODE, key);return cipher.doFinal(cipherText);}}```3DES加密算法是DES的一种改进版,使用3个不同的密钥对数据进行3次加密。
AES加解密的JAVA实现
1、深入理解AES加解密算法;2、用JAVA编程完成一个明文分组的加密和解密,其中密钥是十六进制,长度为128比特(32个16进制数),并且进行加密后,能够进行正确的解密。
二、实验条件1、熟悉JA V A开发环境,能熟练运用JA V A进行程序编写;2、掌握AES加解密算法知识,了解其算法原理;3、安装了JA V A环境的计算机。
三、实验背景随着对称密码的发展,3DES用软件实现速度相对较慢,它使用的64位分组长度显得不够高效和安全的缺点使得需要一种新的高级加密标准来替代它。
AES的全称是Advanced Encryption Standard,即高级加密标准。
该项目由美国国家标准技术研究所(NIST)于1997年开始启动并征集算法,在2000年确定采用Rijndael作为其最终算法,并于2001年被美国商务部部长批准为新的联邦信息加密标准(FIPS PUB 197),该标准的正式生效日期是2002年5月26日。
2000年10月2日,NIST对Rijndael做出了最终评估。
AES是一个迭代的、对称密钥分组的密码,它可以使用128、192和256位密钥,并且用128位(16字节)分组加密和解密数据。
与公共密钥密码使用密钥对不同,对称密钥密码使用相同的密钥加密和解密数据。
通过分组密码返回的加密数据的位数与输入数据相同。
迭代加密使用一个循环结构,在该循环中重复置换(permutations)和替换(substitutions)输入数据。
1、AES 加密模块子密钥轮密钥加(AddRoundKey )明文块字节代替(SubBytes )行移位(ShiftRows )列混合(MixColumns )轮密钥加(AddRoundKey )是否最后一轮是否轮密钥加(AddRoundKey )字节代替(SubBytes )行移位(ShiftRows )密文块子密钥子密钥 字节替代:通过一个非线性的替换函数,用查找表的方式把每个字节替换成对应的字节;行移位:将矩阵中的每个横列进行循环式移位;列混合:为了充分混合矩阵中各个直行的操作,这个步骤使用线性转换来混合每行内的四个字节;轮密钥加:矩阵中的每一个自己都与该次循环的子密钥做XOR 逻辑运算;每个子密钥有密钥生成方案产生;最后一个加密循环中省略列混合步骤,而以另一个轮密钥加取代。
3DES加密解密
3DES加密解密C#3DES加密解密,JAVA、PHP可⽤using System;using System.Security.Cryptography;using System.Text;namespace TT.Utilities.Encrypt{public class DES3{///<summary>/// utf-8编码///加密模式ECB,填充类型PKCS7///</summary>///<param name="str_content"></param>///<param name="str_keys">24位key</param>///<returns></returns>public static string DES3_Encrypt(string str_content, string str_keys)#region{Encoding encoding = Encoding.UTF8;byte[] content = encoding.GetBytes(str_content);byte[] keys = encoding.GetBytes(str_keys);TripleDESCryptoServiceProvider tdsc = new TripleDESCryptoServiceProvider();//指定密匙长度,默认为192位tdsc.KeySize = 128;//使⽤指定的key和IV(加密向量)tdsc.Key = keys;//tdsc.IV = IV;//加密模式,偏移tdsc.Mode = CipherMode.ECB;tdsc.Padding = PaddingMode.PKCS7;//进⾏加密转换运算ICryptoTransform ct = tdsc.CreateEncryptor();//8很关键,加密结果是8字节数组byte[] results = ct.TransformFinalBlock(content, 0, content.Length);string base64String = Convert.ToBase64String(results);return base64String;}#endregion///<summary>/// utf-8编码///加密模式ECB,填充类型PKCS7///</summary>///<param name="base64_content"></param>///<param name="str_keys">24位key</param>///<returns></returns>public static string DES3_Decrypt(string base64_content, string str_keys)#region{Encoding encoding = Encoding.UTF8;byte[] content = Convert.FromBase64String(base64_content);byte[] keys = encoding.GetBytes(str_keys);TripleDESCryptoServiceProvider tdsc = new TripleDESCryptoServiceProvider();//指定密匙长度,默认为192位tdsc.KeySize = 128;//使⽤指定的key和IV(加密向量)tdsc.Key = keys;//tdsc.IV = IV;//加密模式,偏移tdsc.Mode = CipherMode.ECB;tdsc.Padding = PaddingMode.PKCS7;//进⾏加密转换运算ICryptoTransform ct = tdsc.CreateDecryptor();//8很关键,加密结果是8字节数组byte[] results = ct.TransformFinalBlock(content, 0, content.Length);string oriString = encoding.GetString(results);return oriString;}#endregion}}。
3des算法密钥例子
3des算法密钥例子3DES(Triple Data Encryption Standard)是一种对称加密算法,通过对数据进行三次加密来提高安全性。
它基于DES算法,使用三个不同的密钥对数据进行加密和解密。
下面举个例子来说明3DES算法的密钥使用方法。
假设我们有如下三个密钥:Key1、Key2、Key3。
这三个密钥可以是任意长度,但必须相同。
接下来,我们将使用这三个密钥来加密一段文本。
首先,我们将明文分为块,每个块的长度为64位(8个字节)。
如果明文不足64位,需要进行填充。
然后,我们将第一个密钥Key1应用到明文块上,使用DES算法进行加密。
加密后的结果作为下一步的输入。
接下来,我们将第二个密钥Key2应用到上一步得到的结果上,再次使用DES算法进行加密。
最后,我们将第三个密钥Key3应用到上一步得到的结果上,再次使用DES算法进行加密。
加密后的结果就是最终的密文。
如果需要解密密文,只需要将上述过程反过来即可:先应用Key3解密,再应用Key2解密,最后应用Key1解密,得到原始的明文。
需要注意的是,密钥的安全性对于3DES算法非常重要。
如果密钥被泄漏,可能导致密文被解密,从而造成数据泄露。
因此,在实际应用中,密钥的生成、管理和存储需要采取严格的措施,以确保系统的安全性。
总结起来,3DES算法通过三次加密来提高数据的安全性,它基于DES算法,使用三个相同长度的密钥进行加密和解密操作。
密钥的安全性是保证系统安全的关键因素。
希望以上例子对你理解3DES算法的密钥使用方法有所帮助。
java的3DES加密-解密
本文由我司收集整编,推荐下载,如有疑问,请与我司联系java 的3DES 加密/解密2012/07/30 6 Java 写的加密解密算法及调用范例1、.JAVA 算法范例package Common.JUtility; import javax.crypto.*;import javax.crypto.spec.SecretKeySpec;import com.sun.apache.xerces.internal.impl.dv.util.Base64; public class EncryptUtils { /// summary /// 3des 解码/// /summary /// param name= value 待解密字符串/param /// param name= key 原始密钥字符串/param /// returns /returns public static String Decrypt3DES(String value, String key) throws Exception { byte[] b = decryptMode(GetKeyBytes(key), Base64.decode(value)); return new String(b); } /// summary /// 3des 加密/// /summary /// param name= value 待加密字符串/param /// param name= strKey 原始密钥字符串/param /// returns /returns public static String Encrypt3DES(String value, String key) throws Exception { String str = byte2Base64(encryptMode(GetKeyBytes(key), value.getBytes())); return str; } //计算24 位长的密码byte 值,首先对原始密钥做MD5 算hash 值,再用前8 位数据对应补全后8 位public static byte[] GetKeyBytes(String strKey) throws Exception { if (null == strKey || strKey.length() 1) throw new Exception( key is null or empty! java.security.MessageDigest alg =java.security.MessageDigest.getInstance( MD5alg.update(strKey.getBytes()); byte[] bkey = alg.digest(); System.out.println( md5key.length= + bkey.length); System.out.println( md5key= + byte2hex(bkey)); int start = bkey.length; byte[] bkey24 = new byte[24]; for (int i = 0; i start; i++) { bkey24[i] = bkey[i]; } for (int i = start; i i++) {//为了与16 位key 兼容bkey24[i] = bkey[i - start]; } System.out.println( byte24key.length= + bkey24.length); System.out.println( byte24key= + byte2hex(bkey24)); return bkey24; } 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);。
JAVA和C#3DES加密解密
JAVA和C#3DES加密解密/// <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 ){//复制于MSDNtry{// Create a MemoryStream.MemoryStream mStream = new MemoryStream();TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();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 );TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();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();TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();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 );TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();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>/// 类<a href="/base/softwaretest"class='replace_word' title="软件测试知识库" target='_blank' style='color:#df3434; font-weight:bold;'>测试</a>/// </summary>public static void T est(){System.Text.Encoding utf8 = System.T ext.Encoding.UTF8;//key为abcdefghijklmnopqrstuvwx的Base64编码byte[] key = Convert.FromBase64String( "YWJjZGVmZ2hpamtsbW5vcHFyc3R 1dnd4" );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.T oBase64String( str1 ) );System.Console.WriteLine( System.Text.Encoding.UTF8.GetSt ring( 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.T oBase64String( str3 ) );System.Console.WriteLine( utf8.GetString( str4 ) );System.Console.WriteLine();}}。
3DES加解密工具说明文档
3DES加/解密工具说明文档武汉大学计算机学院软件名称:3DES加解密软件功能:用3DES算法对文件进行加密,使用密文链接模式及密文挪用技术编程语言:JAVA编程环境:Eclipse发布方式:已打包成jar文件运行方式:在安装jre的机子上可以直接双击jar文件运行,也可以用rar解压后用编译工具运行使用说明:在文件输入框输入文件路径,在密钥输入框输入16个字节的密钥,并点击密钥输入,然后点击加解密模块说明:类名:Myframe:功能:实现界面,并完成密文反馈、短快处理及文件输入输出。
调用其他类:THREE入口参数:通过界面输入文件路径及密钥出口参数:无类名:THREE功能:实现3DES的3圈加密。
调用其他类:DES入口参数:64位明文,128子密钥。
出口参数:64位密文类名:DES功能:实现3DES的一圈加密。
调用其他类:无入口参数:64位明文,64位子密钥。
出口参数:64位密文各个类的源码及详细说明:Myframe 类:: /** Created on 2004-11-13** TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */import java.awt.BorderLayout;import java.awt.Button;import java.awt.Container;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.Panel;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.UnsupportedEncodingException;import java.io.*;import java.util.Date;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;import mydes.DES;import mydes.THREE;/*** @author TINA** TODO To change the template for this generated type comment go to* Window - Preferences - Java - Code Style - Code Templates*/public class myframe extends JFrame implements ActionListener{JButton Enc=new JButton("加密"); //加密按钮JButton Dec=new JButton("解密"); //解密按钮JTextArea taLog=new JTextArea(); //状态显示区JLabel findfile=new JLabel("文件名:");JButton key1=new JButton("密钥"); //密钥输入按钮JTextField filepath=new JTextField(20);//文件路径输入部分JTextField keytext=new JTextField(16);//密钥输入部分byte[] cipherKey1=new byte[8]; //3DES的密钥K1byte[] cipherKey2=new byte[8]; //3DES的密钥K2int[][] subKeys1=new int[16][48]; //用于存放K1产生的子密钥int[][] subKeys2=new int[16][48]; //用于存放K2产生的子密钥byte[]bZ={(byte)0x00,(byte)0x03,(byte)0x45,(byte)0xf3,(byte)0x33,(byte)0x21,(byte)0x75,(byte)0 xed};//初始向量Zbyte key[]=new byte[16];public static void main(String args[]) //生成界面{myframe frame=new myframe();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.show();}public myframe() //界面的构造函数:生成按钮及输入框{setTitle("3DES ");setSize(400,300);JPanel input=new JPanel();input.setLayout(new FlowLayout());input.add(findfile);input.add(filepath);JPanel keyarea=new JPanel();keyarea.setLayout(new FlowLayout());keyarea.add(key1);keyarea.add(keytext);JPanel inputarea=new JPanel();inputarea.setLayout(new BorderLayout());inputarea.add("South",keyarea);inputarea.add("Center",input);JPanel pnButtons=new JPanel();pnButtons.setLayout(new FlowLayout());pnButtons.add(Enc);Enc.addActionListener(this);pnButtons.add(Dec);Dec.addActionListener(this);Container contentPane=getContentPane();contentPane.setLayout(new BorderLayout());contentPane.add("North",inputarea);contentPane.add("Center",taLog);contentPane.add("South",pnButtons);}public void actionPerformed(ActionEvent ae)//事件监听方法{if(ae.getSource()==key1)//获得密钥{for(int i=0;i<16;i++)try{byte[] temp=keytext.getText().getBytes("ASCII");//获得输入框内字符ASCII 码值int len=temp.length/2;for(int j=0;j<len;j++){cipherKey1[j]=temp[j];}for(int j=0;j<len;j++){cipherKey2[j]=temp[j+8];}}catch(UnsupportedEncodingException uee){}hide();}if(ae.getSource()==Enc) //进行加密{String temp=filepath.getText();File fpt=new File(temp); //取得文件路径File fct=new File(temp.concat(".des"));filepath.setText(temp.concat(".des"));//给加密文件自动添上.des的扩展名long begintime=(new Date()).getTime();//记录加密起始时间long len=encrypt(fpt,fct); //加密文件,返回加密文件长度if(len>0){long endtime=(new Date()).getTime();//取得结束时间long time=endtime-begintime;taLog.append("\nPlaintext length: "+len+" bytes\n");//输出各项信息taLog.append("Encryption time: "+time+" milliseconds\n");taLog.append("Encryption speed: "+(len*1000)/(time*1024)+" kB/s\n");}}else if(ae.getSource()==Dec) //进行解密,具体类似加密过程{String temp=filepath.getText();File fct=new File(temp);File fdt=new File(temp.concat(".dec"));filepath.setText("");long begintime=(new Date()).getTime();long len=decrypt(fct,fdt);if(len>0){long endtime=(new Date()).getTime();long time=endtime-begintime;taLog.append("\nCiphertext length: "+len+" bytes\n");taLog.append("Decryption time: "+time+" milliseconds\n");taLog.append("Decryption speed: "+(len*1000)/(time*1024)+" kB/s\n");}}}public byte[] arrayM2Add(byte[] array1,byte[] array2) //两个字节型整数串模2加{int k=array1.length;byte[] array=new byte[k];for(int i=0;i<k;i++){array[i]=(byte)(array1[i]^array2[i]);}return array;}public byte[] arrayM2Add(byte[] array1,byte[] array2,byte[] array3) //三个字节型整数串模2加{int k=array1.length;byte[] array=new byte[k];for(int i=0;i<k;i++){array[i]=(byte)(array1[i]^array2[i]);array[i]=(byte)(array[i]^array3[i]);}return array;}public void arraycopy(byte[] source,byte[] destination) //字节型整数串完全复制{for(int i=0;i<source.length;i++)destination[i]=source[i];}public void arraycopy(byte[] src,int srcPos,byte[] dest,int destPos,int length) //字节型整数串选择性复制{for(int i=0;i<length;i++)dest[destPos+i]=src[srcPos+i];}public long encrypt(File fpt,File fct) //将文件fpt加密成fct{subKeys1=DES.makeSubKeys(cipherKey1);subKeys2=DES.makeSubKeys(cipherKey2);try{if(fct.exists()==true) //判断密文是否存在{fct.delete();fct.createNewFile();}RandomAccessFile pt=new RandomAccessFile(fpt,"r");//建立随机访问流RandomAccessFile ct=new RandomAccessFile(fct,"rw");byte[] bMi=new byte[8]; //M(i)byte[] bMt=new byte[8]; //M(i-1)byte[] bCi=new byte[8]; //C(i)byte[] bCt=new byte[8]; //C(i-1)long i=0;long t=pt.length()/8; //预算标准块个数int k=(int)(pt.length()%8); //记录短块大小ct.write(THREE.encrypt(bZ,subKeys1,subKeys2));//把初始向量Z当作第一个标准块加密,防止文件本身小于8个字节的情况发生while(i<t)//标准块加密{i++;pt.read(bMi);if(i==1)//第一次使用初始向量{bCi=THREE.encrypt(arrayM2Add(bMi,bZ),subKeys1,subKeys2);//使用THREE类进行加密}else{bCi=THREE.encrypt(arrayM2Add(bMi,bCt),subKeys1,subKeys2);ct.write(bCi);}arraycopy(bCi,bCt);arraycopy(bMi,bMt);}if(k>0) //进入短快处理{byte[] bMn=new byte[k]; //短块M(n)pt.read(bMn);byte[] b=new byte[8-k]; //挪用临时数组barraycopy(bCt,k,b,0,8-k); //C(n-1)右k位->bbyte[] temp=new byte[8];arraycopy(b,0,temp,0,8-k);arraycopy(bMn,0,temp,8-k,k); //b和M(n)拼接,存入tempct.seek(ct.getFilePointer()-(8-k)); //文件写入指针变换ct.write(THREE.encrypt(temp,subKeys1,subKeys2));}long length=pt.length();pt.close();ct.close();return length;}catch(FileNotFoundException fnf) //异常处理{taLog.setText("FileNotFoundException\n");return -1;}catch(IOException ioe){taLog.setText("IOException\n");return -1;}}public long decrypt(File fct,File fdt)//解密部分,同加密{subKeys1=DES.makeSubKeys(cipherKey1);subKeys2=DES.makeSubKeys(cipherKey2);try{if(fdt.exists()==true) {fdt.delete();fdt.createNewFile();}RandomAccessFile ct=new RandomAccessFile(fct,"r");RandomAccessFile dt=new RandomAccessFile(fdt,"rw");byte[] bMi=new byte[8];byte[] bMt=new byte[8];byte[] bCi=new byte[8];byte[] bCt=new byte[8];byte[] bCn=new byte[8];byte[] bMn=new byte[8];long i=0;long t=ct.length()/8;int k=(int)(ct.length()%8);while((i<t-1)||((i<t)&&(k==0))){ct.read(bCi);if(i==0) {}else if(i==1){bMi=arrayM2Add(THREE.decrypt(bCi,subKeys1,subKeys2),bZ);dt.write(bMi);}else{bMi=arrayM2Add(THREE.decrypt(bCi,subKeys1,subKeys2),bCt);dt.write(bMi);}arraycopy(bCi,bCt);arraycopy(bMi,bMt);i++;}if(k>0) {ct.seek(ct.getFilePointer()+k);//文件指针移至C(n)ct.read(bCn);bMn=THREE.decrypt(bCn,subKeys1,subKeys2);ct.seek(ct.getFilePointer()-(k+8));ct.read(bCi);byte[] b=new byte[8-k];arraycopy(bMn,0,b,0,8-k);arraycopy(b,0,bCi,k,8-k);if(i==0) {}else if(i==1){bMi=arrayM2Add(THREE.decrypt(bCi,subKeys1,subKeys2),bZ);dt.write(bMi);}else{bMi=arrayM2Add(THREE.decrypt(bCi,subKeys1,subKeys2),bCt);dt.write(bMi);}byte[] temp=new byte[k];arraycopy(bMn,8-k,temp,0,k);dt.write(temp);}long length=ct.length();ct.close();dt.close();return length;//返回密文大小}catch(FileNotFoundException fnf){taLog.setText("FileNotFoundException\n");return -1;}catch(IOException ioe){taLog.setText("IOException\n");return -1;}}}THREEl类:package mydes;/*** @author TINA** TODO To change the template for this generated type comment go to* Window - Preferences - Java - Code Style - Code Templates*/public class THREE //返回密文数组{public static byte[] encrypt(byte[] oword,int[][] SubKeys1,int[][] SubKeys2){byte[] bTemp1=DES.encrypt(oword,SubKeys1);//用子密钥组SubKeys1加密byte[] bTemp2=DES.decrypt(bTemp1,SubKeys2);byte[] bCiphertext=DES.encrypt(bTemp2,SubKeys1);return bCiphertext;}public static byte[] decrypt(byte[] sword,int[][] SubKeys1,int[][] SubKeys2) //返回明文数组{byte[] bTemp1=DES.decrypt(sword,SubKeys1);//用子密钥组SubKeys1解密byte[] bTemp2=DES.encrypt(bTemp1,SubKeys2);byte[] bPlaintext=DES.decrypt(bTemp2,SubKeys1);return bPlaintext;}}DES类:/** Created on 2004-11-13** TODO To change the template for this generated file go to* Window - Preferences - Java - Code Style - Code Templates*/package mydes;/*** @author TINA** TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates*/public class DES{private static final int C0[]={ //各个变换数组57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4};private static final int D0[]={14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32};private static final int Lmovetimes[]={1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1};private static final int IP[]={58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8,57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7};private static final int ANTIIP[]={40,8,48,16,56,24,64,32,39,7,47,15,55,23,63,31,38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29,36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,34,2,42,10,50,18,58,26,33,1,41,9,49,17,57,25};private static final int E[]={32,1,2,3,4,5,4,5,6,7,8,9,8,9,10,11,12,13,12,13,14,15,16,17,16,17,18,19,20,21,20,21,22,23,24,25,24,25,26,27,28,29,28,29,30,31,32,1};private static final int P[]={16,7,20,21,29,12,28,17,1,15,23,26,5,18,31,10,2,8,24,14,32,27,3,9,19,13,30,6,22,11,4,25};private static final int Sbox8[][]={{14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8,4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13},{15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5,0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9},{10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1,13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12},{7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9,10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14},{2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6,4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3},{12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8,9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13},{4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6,1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12},{13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2,7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11}};private static int[] OriginKey=new int[64];//原密钥private static int[] Tempkey=new int[56];//变化用密钥private static int[] Originword64=new int[64];//初始64位明文private static int[] Outword64=new int[64];//输出64位密文private static int[] Tempword=new int[64];//实际变化用的64位private static int[] wordLeft=new int[32];//左32位private static int[] wordRight=new int[32];public static void exchange(int[] Originword,int[] Targetword,int[] model)//置换方法{for(int i=0;i<model.length;i++)Targetword[i]=Originword[model[i]-1];}public static void Bit2int(byte[] originArray,int[] TargetArray) //将字节转换成8个01{for(int i=0;i<TargetArray.length;i++){TargetArray[i]=(int)(originArray[i/8]>>(7-i%8)&0x01);}}public static void Int2bit(byte[] originArray,int[] TargetArray) //将8个01转换成字节{for(int i=0;i<originArray.length;i++){originArray[i]=(byte)TargetArray[8*i];for(int j=1;j<8;j++){originArray[i]=(byte)(originArray[i]<<1);originArray[i]+=(byte)TargetArray[8*i+j];}}}public static void Mod2add(int[] array1,int[] array2) //模2加{for(int i=0;i<array2.length;i++){array1[i]^=array2[i];}}public static void p2pexchange(int[] array1,int[] array2) //两个数组互换{int k=array1.length;int temp[]=new int[k];for(int i=0;i<k;i++){temp[i]=array1[i];array1[i]=array2[i];array2[i]=temp[i];}}public static void Sarray(int[] Sourcearray,int[] left,int[] right) //一个数组等分成两个数组{int k=Sourcearray.length;for(int i=0;i<k/2;i++){left[i]=Sourcearray[i];right[i]=Sourcearray[i+k/2];}}public static void AntiSarray(int[] Sourcearray,int[] left,int[] right) //arrayCut的逆变换{int k=left.length;for(int i=0;i<k;i++){Sourcearray[i]=left[i];Sourcearray[i+k]=right[i];}}private static void Lmove(int[] array) //循环左移{int temp=array[0];for(int i=0;i<27;i++){array[i]=array[i+1];}array[27]=temp;temp=array[28];for(int i=0;i<27;i++){array[28+i]=array[28+i+1];}array[55]=temp;}private static int[][] antiSubKey(int[][] iSubKeys) //16个子密钥倒置{int[][] iInvSubKeys=new int[16][48];for(int i=0;i<16;i++)for(int j=0;j<48;j++)iInvSubKeys[i][j]=iSubKeys[15-i][j];return iInvSubKeys;}private static void Sbox(int[] iInput,int scount1,int[] iOutput,int scount2,int[] iSPM) //S 盒代替{int iRow=iInput[scount1]*2+iInput[scount1+5];intiCol=iInput[scount1+1]*8+iInput[scount1+2]*4+iInput[scount1+3]*2+iInput[scount1+4];int x=iSPM[16*iRow+iCol];iOutput[scount2]=x>>3&0x01;iOutput[scount2+1]=x>>2&0x01;iOutput[scount2+2]=x>>1&0x01;iOutput[scount2+3]=x&0x01;}//加密函数fprivate static int[] encFunc(int[] Input,int[] SubKey){int Temp1[]=new int[48];int Temp2[]=new int[32];int Output[]=new int[32];exchange(Input,Temp1,E);Mod2add(Temp1,SubKey);for(int i=0;i<8;i++)Sbox(Temp1,i*6,Temp2,i*4,Sbox8[i]);exchange(Temp2,Output,P);return Output;}public static int[][] makeSubKeys(byte[] usingkey) //子密钥生成入口64位密钥返回16组48字节子密钥组{int[][] SubKeys=new int[16][48];Bit2int(usingkey,OriginKey);exchange(OriginKey,Tempkey,C0);for(int i=0;i<16;i++){for(int j=0;j<Lmovetimes[i];j++){Lmove(Tempkey);}exchange(Tempkey,SubKeys[i],D0);}return SubKeys;}public static byte[] encrypt(byte[] oword64,int[][] iSubKeys) //加密方法入口64位明文子密钥组返回值经加密之后64位密文{byte sword64[]=new byte[8];Bit2int(oword64,Originword64);//为便于操作,将64位明文扩展到64个整数exchange(Originword64,Tempword,IP);//初始置换Sarray(Tempword,wordLeft,wordRight);for(int i=0;i<16;i++)//16圈循环迭代{Mod2add(wordLeft,encFunc(wordRight,iSubKeys[i]));p2pexchange(wordLeft,wordRight);}p2pexchange(wordLeft,wordRight);AntiSarray(Tempword,wordLeft,wordRight);exchange(Tempword,Outword64,ANTIIP);//逆初始置换Int2bit(sword64,Outword64);//将64个整数密文压缩为64位,并返回return sword64;}public static byte[] decrypt(byte[] bCiphertext,int[][] SubKeys) //解密方法{int[][] antiSubKeys=antiSubKey(SubKeys);//将16组子密钥完全颠倒return encrypt(bCiphertext,antiSubKeys);//以颠倒后子密钥加密,即为解密}}。
java版3des加密程序
java版3des加密程序java版3des加密程序,可与php兼容代码: import java.io.UnsupportedEncodingException; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.Se代码:import java.io.UnsupportedEncodingException;import java.security.Key;import javax.crypto.Cipher;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESedeKeySpec;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;public class DESCoder{private static BASE64Encoder base64 = new BASE64Encoder();private static byte[] myIV = { 50, 51, 52, 53, 54, 55, 56, 57 };//private static String strkey = "W9qPIzjaVGKUp7CKRk/qpCkg/SCMkQRu"; // 字节数必须是8的倍数private static String strkey = "01234567890123456789012345678912";public static String desEncrypt(String input) throws Exception{BASE64Decoder base64d = new BASE64Decoder();DESedeKeySpec p8ksp = null;p8ksp = new DESedeKeySpec(base64d.decodeBuffer(strkey));Key key = null;key = SecretKeyFactory.getInstance("DESede").generateSecret(p8ksp);input = padding(input);byte[] plainBytes = (byte[])null;Cipher cipher = null;byte[] cipherText = (byte[])null;plainBytes = input.getBytes("UTF8");cipher = Cipher.getInstance("DESede/CBC/NoPadding");SecretKeySpec myKey = new SecretKeySpec(key.getEncoded(), "DESede"); IvParameterSpec ivspec = new IvParameterSpec(myIV);cipher.init(1, myKey, ivspec);cipherText = cipher.doFinal(plainBytes);return removeBR(base64.encode(cipherText));}public static String desDecrypt(String cipherText) throws Exception{BASE64Decoder base64d = new BASE64Decoder();DESedeKeySpec p8ksp = null;p8ksp = new DESedeKeySpec(base64d.decodeBuffer(strkey));Key key = null;key = SecretKeyFactory.getInstance("DESede").generateSecret(p8ksp);Cipher cipher = null;byte[] inPut = base64d.decodeBuffer(cipherText);cipher = Cipher.getInstance("DESede/CBC/NoPadding");SecretKeySpec myKey = new SecretKeySpec(key.getEncoded(), "DESede"); IvParameterSpec ivspec = new IvParameterSpec(myIV);cipher.init(2, myKey, ivspec);byte[] output = removePadding(cipher.doFinal(inPut));return new String(output, "UTF8");}private static String removeBR(String str) {StringBuffer sf = new StringBuffer(str);for (int i = 0; i < sf.length(); ++i){if (sf.charAt(i) == '\n'){sf = sf.deleteCharAt(i);}}for (int i = 0; i < sf.length(); ++i)if (sf.charAt(i) == '\r'){sf = sf.deleteCharAt(i);}return sf.toString();}byte[] oldByteArray;try{oldByteArray = str.getBytes("UTF8");int numberToPad = 8 - oldByteArray.length % 8;byte[] newByteArray = new byte[oldByteArray.length + numberToPad]; System.arraycopy(oldByteArray, 0, newByteArray, 0, oldByteArray.length);for (int i = oldByteArray.length; i < newByteArray.length; ++i){newByteArray[i] = 0;}return new String(newByteArray, "UTF8");}catch (UnsupportedEncodingException e){System.out.println("Crypter.padding UnsupportedEncodingException"); }return null;}public static byte[] removePadding(byte[] oldByteArray){int numberPaded = 0;for (int i = oldByteArray.length; i >= 0; --i){if (oldByteArray[(i - 1)] != 0){numberPaded = oldByteArray.length - i;break;}}byte[] newByteArray = new byte[oldByteArray.length - numberPaded];System.arraycopy(oldByteArray, 0, newByteArray, 0, newByteArray.length);return newByteArray;}try {String desstr = DESCoder.desEncrypt("1qaz2ws"); String pstr = DESCoder.desDecrypt(desstr); System.out.println("plainText:1qaz2ws");System.out.println("Encode:"+desstr);System.out.println("Decode:"+pstr);} catch (Exception e) {e.printStackTrace();}}}运⾏结果:plainText:1qaz2wsEncode:0GsXgYA8BuM=Decode:1qaz2ws和PHP的⼀样。
北邮java智能卡实验报告3des加解密
智能卡技术实验报告学院:电子工程学院班级:2011211204姓名:学号:2011210986实验四 Java卡对称加密解密程序一、实验目的:建立Java卡3DES算法的加密解密程序,并进行Java卡程序的编译和调测。
二、实验设备:PC机,智能卡读卡器,Java卡。
三、实验内容:1.建立一个JavaCard工程2.编写3DES算法的加解密应用代码3.使用智能卡模拟器对应用代码进行调试4.使用Java卡对应用代码进行编译测试四、实验报告:1.设计一个3DES算法的加密解密小应用程序2.画出系统结构图和各部分程序流程图3.完成程序的开发,然后再在Java卡上进行验证五、流程图系统结构流程:各部分流程图1)产生随机明文流程图2)3DES加密流程图3)3DES解密流程图六、演示模拟器随机产生8字节的明文:D4AA3503EC117A56,用时:1113us加密,密文:DCC74C5B43340FB7,用时:8445us解密,用时:6338us插卡产生明文:09FED7DA8FC3B90F,用时:83990us加密,产生密文:A447987D6FF5CC2C,用时:682482us解密,用时:641494us可以看出,插卡后比直接用模拟器,加密解密的时间长了很多。
七、实验总结通过本次智能卡实验,我了解了对称加密的一些相关概念与知识,并学会了如何在智能卡上实现对称加解密。
八、源代码package desthree;import javacard.framework.*;import javacard.security.*;import javacardx.crypto.*;public class Desthree extends Applet{byte [] Random;byte [] ciphertext=new byte[256];byte [] translation=new byte[256];private DESKey deskey;Cipher CipherObj;private byte [] keyData1={0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};//密钥private byte [] keyData2={0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18};private byte [] keyData3={0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28};protected Desthree(){register();}public static void install(byte [] bArray, short bOffset, byte bLength){new Desthree();}public void process(APDU apdu)throws ISOException{byte [] buffer = apdu.getBuffer();if((buffer[ISO7816.OFFSET_CLA])==0 && (buffer[ISO7816.OFFSET_INS])==(byte)(0xa4))return;if(buffer[ISO7816.OFFSET_INS]==(byte)0x84){getRandom();//返回生成的8字节随机数Util.arrayCopyNonAtomic(Random, (short)0, buffer, (short)0, (short)8);apdu.setOutgoingAndSend((short)0,(short)8);}if(buffer[ISO7816.OFFSET_INS]==(byte)0x83){apdu.setIncomingAndReceive();encrypt(buffer); //加密Util.arrayCopyNonAtomic(ciphertext, (short)16, buffer, (short)0, (short)8);apdu.setOutgoingAndSend((short)0,(short)8);}if(buffer[ISO7816.OFFSET_INS]==(byte)0x82){apdu.setIncomingAndReceive();doAuthentication(buffer); //解密}}//执行加密过程的代码private void encrypt(byte [] buffer){deskey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES,KeyBuilder.LENGTH_DES,false);deskey.setKey(keyData1, (short)0);CipherObj = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);CipherObj.init(deskey, Cipher.MODE_ENCRYPT);CipherObj.doFinal(buffer, (short)5, (short)8, ciphertext, (short)0);deskey.setKey(keyData2, (short)0);CipherObj = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);CipherObj.init(deskey, Cipher.MODE_DECRYPT);CipherObj.doFinal(ciphertext, (short)0, (short)8, ciphertext, (short)8);deskey.setKey(keyData3, (short)0);CipherObj = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);CipherObj.init(deskey, Cipher.MODE_ENCRYPT);CipherObj.doFinal(ciphertext, (short)8, (short)8, ciphertext, (short)16);}//执行解密过程的代码private void doAuthentication(byte [] buffer){deskey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES,KeyBuilder.LENGTH_DES,false);deskey.setKey(keyData3, (short)0);CipherObj = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);CipherObj.init(deskey, Cipher.MODE_DECRYPT);CipherObj.doFinal(buffer, (short)5, (short)8, translation, (short)0);deskey.setKey(keyData2, (short)0);CipherObj = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);CipherObj.init(deskey, Cipher.MODE_ENCRYPT);CipherObj.doFinal(translation, (short)0, (short)8, translation, (short)8);deskey.setKey(keyData1, (short)0);CipherObj = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);CipherObj.init(deskey, Cipher.MODE_DECRYPT);CipherObj.doFinal(translation, (short)8, (short)8, translation, (short)16);if(Util.arrayCompare(translation, (short)16, Random, (short)0, (short)8)!=0)ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);}//获取随机数private void getRandom(){if(Random==null)Random = JCSystem.makeTransientByteArray((short)8,JCSystem.CLEAR_ON_DESELECT);RandomData ICC = RandomData.getInstance((byte)RandomData.ALG_PSEUDO_RANDOM);ICC.setSeed(Random, (short)0, (short)8);ICC.generateData(Random, (short)0, (short)8);}}。
c#加密,java解密(3DES加密)
22. private static SecretKey deskey;//密钥
23. private static String keyString = "A3F2569DESJEIWBCJOTY45DYQWF68H1Y";//获得密钥的参数
byte数组
24. public byte[] deBase64(String parm) throws IOException {
71. NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
72. InvalidKeyException, IOException {
73. DES des = new DES();
74. des.getKey(keyString);
46.
cipherByte = c.doFinal(buff);
47.
}
48.
catch(java.security.InvalidKeyException ex){
49.
ex.printStackTrace();
50.
}
51.
catch(javax.crypto.BadPaddingException ex){
35.
return dnParm;
36. } /**
37. * 对 Byte 数组进行解密
38. * @param buff 要解密的数据
39. * @return 返回加密后的 String
40. */
41. public static String createDecryptor(byte[] buff) throws
