Java中3DES加密解密示例

合集下载

如何在Java中进行数据的加密和解密

如何在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实现

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加密解密

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算法密钥例子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加密-解密

本文由我司收集整编,推荐下载,如有疑问,请与我司联系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加密解密

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加解密软件功能:用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加密程序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加解密

北邮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加密)

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

Java 加密解密之对称加密算法DESede

Java 加密解密之对称加密算法DESede

Java 加密解密之对称加密算法DESede本文转自网络DESede即三重DES加密算法,也被称为3DES或者Triple DES。

使用三(或两)个不同的密钥对数据块进行三次(或两次)DES加密(加密一次要比进行普通加密的三次要快)。

三重DES的强度大约和112-bit的密钥强度相当。

通过迭代次数的提高了安全性,但同时也造成了加密效率低的问题。

正因DESede算法效率问题,AES算法诞生了。

(详见:Java 加密解密之对称加密算法AES)到目前为止,还没有人给出攻击三重DES的有效方法。

对其密钥空间中密钥进行蛮干搜索,那么由于空间太大,这实际上是不可行的。

若用差分攻击的方法,相对于单一DES来说复杂性以指数形式增长。

三重DES有四种模型(a)DES-EEE3,使用三个不同密钥,顺序进行三次加密变换。

(b)DES-EDE3,使用三个不同密钥,依次进行加密-解密-加密变换。

(c)DES-EEE2,其中密钥K1=K3,顺序进行三次加密变换。

(d)DES-EDE2,其中密钥K1=K3,依次进行加密-解密-加密变换。

JDK对DESede算法的支持密钥长度:112位/168位工作模式:ECB/CBC/PCBC/CTR/CTS/CFB/CFB8 to CFB128/OFB/OBF8 to OFB128填充方式:Nopadding/PKCS5Padding/ISO10126Padding/工作模式和填充方式请参考:JAVA加密解密基础十六进制工具类Hex.java,见:java byte数组与十六进制字符串互转DESede加密解密的java实现:DESede.javaJava代码1.import java.security.Key;2.3.import javax.crypto.Cipher;4.import javax.crypto.KeyGenerator;。

关于java3DES加密解密偏移量代码示例

关于java3DES加密解密偏移量代码示例

关于java3DES加密解密偏移量代码⽰例// 3DES加密public static String getEnc3DES(String data, String key, String iv) throws Exception {Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("gb2312"));IvParameterSpec ivs = new IvParameterSpec(iv.getBytes("gb2312"));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");SecretKey securekey = keyFactory.generateSecret(dks);cipher.init(Cipher.ENCRYPT_MODE, securekey, ivs);BASE64Encoder base64Encoder = new BASE64Encoder();return base64Encoder.encode(cipher.doFinal(data.getBytes("GB2312")));}// 3DES解密public static String getDes3DES(String data, String key, String iv) throws Exception {BASE64Decoder base64Decoder = new BASE64Decoder();byte[] databyte = base64Decoder.decodeBuffer(data);Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("gb2312"));IvParameterSpec ivs = new IvParameterSpec(iv.getBytes("gb2312"));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");SecretKey securekey = keyFactory.generateSecret(dks);cipher.init(Cipher.DECRYPT_MODE, securekey, ivs);return new String(cipher.doFinal(databyte), "GB2312");} 说明:KEY值根据⾃⼰需求⽣成。

java加密解密desutil、tripledesutil

java加密解密desutil、tripledesutil

Java加密解密DESUtil、TripleDESUtil* 注:1、DES使用56位密钥,以现代计算能力,24小时内即可被破解;* 2、3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES 指定为过渡的加密标准)。

使用3条56位的密钥对数据进行三次加密。

* 3、DES算法的加密密钥是根据用户输入的密码生成的,该算法把64位密码中的第8位、第16位、第24位、第32位、第40位、第48位、第56位、第64位作为奇偶校验位,在计算密钥时要忽略这8位.* 在generateKey()生成的随机密钥为8位(64bit)public static final String ALGORITHM = “DES”;public static final String TRANSFORMA TION = “DES/ECB/PKCS5Padding”;* 生成随机密钥* @return* @throws Exceptionpublic static Key generateKey() throws Exception {KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);keyGenerator.init(new SecureRandom());Key key = keyGenerator.generateKey();return key;* 生成固定密钥* @param seed* @return* @throws Exceptionpublic static Key generateKey(byte[] seed) throws Exception {KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);keyGenerator.init(new SecureRandom(seed));Key key = keyGenerator.generateKey();return key;* 生成固定密钥* @param password* @return* @throws Exceptionpublic static Key generateKey(String password) throws Exception {return generateKey(password.getBytes());* 执行加密* @param content* @param key 长度必须为8位,即64bit* @return* @throws Exceptionpublic static byte[] encrypt(byte[] content, byte[] key) throws Exception {Cipher cipher = Cipher.getInstance(TRANSFORMA TION);cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, ALGORITHM)); byte[] output = cipher.doFinal(content);return output;* 执行加密* @param content* @param password* @return* @throws Exceptionpublic static byte[] encrypt(byte[] content, String password) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMA TION);cipher.init(Cipher.ENCRYPT_MODE, generateKey(password));byte[] output = cipher.doFinal(content);return output;* 执行解密* @param content* @param key 长度必须为8位,即64bit* @return* @throws Exceptionpublic static byte[] decrypt(byte[] content, byte[] key) throws Exception {Cipher cipher = Cipher.getInstance(TRANSFORMA TION);cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, ALGORITHM)); byte[] output = cipher.doFinal(content);return output;* 执行解密* @param content* @param password* @return* @throws Exceptionpublic static byte[] decrypt(byte[] content, String password) throws Exception {Cipher cipher = Cipher.getInstance(TRANSFORMA TION);cipher.init(Cipher.DECRYPT_MODE, generateKey(password));byte[] output = cipher.doFinal(content);return output;public static void main(String[] args) throws Exception {System.out.println(Arrays.toString(encrypt(“DES使用56位密钥,以现代计算能力”.getBytes(), “012345”)));System.out.println(new String(decrypt(encrypt(“DES使用56位密钥,以现代计算能力”.getBytes(), “012345”), “012345”)));System.out.println(Arrays.toString(encrypt(“DES使用56位密钥,以现代计算能力”.getBytes(), “01234567”.getBytes())));System.out.println(new String(decrypt(encrypt(“DES使用56位密钥,以现代计算能力”.getBytes(), “01234567”.getBytes()), “01234567”.getBytes())));* 控制台输出:* [117, -109, -80, -75, 51, -86, -57, -109, -94, 58, 38, 94, 39, -107, -60, 65, -122, -7, -124, 2, -23, -30, -98, -64, 90, 26, 15, 82, 84, 102, -108, -3, -68, -4, 110, -86, -106, 19, -65, -110, 2, 15, 49, -79, -98, 38, -39, 6]* DES使用56位密钥,以现代计算能力* [-6, 63, -15, 73, -28, 85, 125, 64, 6, 55, -63, 99, 114, 21, 108, -49, 19, 11, -15, -126, 36, -92, 62, 112, -40, 64, -102, 127, -94, -53, -89, 33, 72, -20, -126, -90, 105, -37, -68, -46, -61, -36, 5, -103, 27, 32, 84, 28]* DES使用56位密钥,以现代计算能力[Java]代码import java.security.Key;import java.security.SecureRandom;import java.util.Arrays;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.spec.SecretKeySpec;public sta tic final String ALGORITHM = “DESede”;public static final String TRANSFORMA TION = “DESede/ECB/PKCS5Padding”; * 生成随机密钥* @return* @throws Exceptionpublic static Key generateKey() throws Exception {KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);keyGenerator.init(new SecureRandom());Key key = keyGenerator.generateKey();return key;* 生成固定密钥* @param seed* @return* @throws Exceptionpublic static Key generateKey(byte[] seed) throws Exception {KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);keyGenerator.init(new SecureRandom(seed));Key key = keyGenerator.generateKey();return key;* 生成固定密钥* @param password* @return* @throws Exceptionpublic static Key generateKey(String password) throws Exception {return generateKey(password.getBytes());* 执行加密* @param content* @param key 长度必须为8位,即64bit* @return* @throws Exceptionpublic static byte[] encrypt(byte[] content, byte[] key) throws Exception {Cipher cipher = Cipher.getInstance(TRANSFORMA TION);cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, ALGORITHM)); byte[] output = cipher.doFinal(content);return output;* 执行加密* @param content* @param password* @return* @throws Exceptionpublic static byte[] encrypt(byte[] content, String password) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMA TION);cipher.init(Cipher.ENCRYPT_MODE, generateKey(password));byte[] output = cipher.doFinal(content);return output;* 执行解密* @param content* @param key 长度必须为8位,即64bit* @return* @throws Exceptionpublic static byte[] decrypt(byte[] content, byte[] key) throws Exception {Cipher cipher = Cipher.getInstance(TRANSFORMA TION);cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, ALGORITHM)); byte[] output = cipher.doFinal(content);return output;* 执行解密* @param content* @param password* @return* @throws Exceptionpublic static byte[] decrypt(byte[] content, String password) throws Exception {Cipher cipher = Cipher.getInstance(TRANSFORMA TION);cipher.init(Cipher.DECRYPT_MODE, generateKey(password));byte[] output = cipher.doFinal(content);return output;public static void main(String[] args) throws Exception {System.out.println(Arrays.toString(encrypt(“使用3条56位的密钥对数据进行三次加密。

3des算法密钥例子

3des算法密钥例子

3des算法密钥例子3DES 是一种对称密钥加密算法,也称为 Triple Data Encryption Algorithm。

它是 DES(Data Encryption Standard)的改进版本,使用三个不同的密钥对数据进行三次加密。

每个密钥长度为 56 位,总长度为168 位。

3DES 在数据加密的过程中,分别执行加密-解密-加密三个步骤,因此也被称为 EDE(Encryption-Decryption-Encryption)。

3DES 算法的安全性较高,目前仍被广泛应用于金融、网络和电子商务等领域。

下面将为您举一个3DES算法密钥的例子,以帮助您更好地理解该算法。

假设 Alice 和 Bob 是一对通信的双方,他们之间希望使用 3DES 算法进行加密通信。

首先,我们需要生成三个密钥。

第一个密钥K1:第二个密钥K2:第三个密钥K3:在加密通信过程中,Alice 首先将明文分为较小的数据块进行加密,然后将加密后的密文发送给 Bob。

Bob 收到密文后,使用 K2 密钥进行解密,得到解密后的数据。

解密完成后,Bob 再次将数据进行加密,并使用K3 密钥进行加密。

加密完成后,Bob 将其发送给 Alice,Alice 使用 K1 密钥进行解密,最终得到正确的明文。

3DES的加密过程如下:1. Alice 使用 K1 密钥对明文进行加密,得到第一次加密结果 E12. Bob 接收到 E1,使用 K2 密钥对其进行解密,得到解密结果 D13. Bob 再次使用 K3 密钥对 D1 进行加密,得到第二次加密结果 E24. Alice 接收到 E2,使用 K1 密钥对其进行解密,得到解密结果D23DES的解密过程如下:1. Alice 使用 K1 密钥对密文进行解密,得到第一次解密结果 D22. Bob 接收到 D2,使用 K2 密钥对其进行加密,得到第二次加密结果 E23. Bob 再次使用 K3 密钥对 E2 进行解密,得到解密结果 D14. Alice 接收到 D1,得到最终的明文。

3DES加解密代码

3DES加解密代码

3DES加解密代码package com.albedo.security;import javax.crypto.Cipher;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import javax.crypto.spec.DESedeKeySpec;import javax.crypto.spec.IvParameterSpec;import java.security.Key;import java.security.SecureRandom;import java.util.Base64;/*** des 加解密实现*/public class DES3Util {//字符编码public static final String CHARSET_UTF8 = "UTF-8";//加密算法DESpublic static final String DES3 = "desede";//电话本模式public static final String DES3_ECB = "DESEDE/ECB/PKCS5Padding";//加密块链模式--推荐public static final String DES3_CBC = "DESEDE/CBC/PKCS5Padding";/*** ⽣成key** @param password* @return* @throws Exception*/private static Key generateKey(String password) throws Exception {//由于DES3密码不能⼩于24位,因此,任意长度密码经过Md5转化后,变为定长32位执⾏加解密处理DESedeKeySpec dks = new DESedeKeySpec(Md5Utils.encrypt(password).getBytes(CHARSET_UTF8));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES3);return keyFactory.generateSecret(dks);}/*** 3DES加密字符串--ECB格式** @param password 加密密码,长度不能够⼩于8位* @param data 待加密字符串* @return加密后内容*/public static String encryptECB(String password, String data) throws Exception{Key secretKey = generateKey(password);Cipher cipher = Cipher.getInstance(DES3_ECB);cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom());byte[] bytes = cipher.doFinal(data.getBytes(CHARSET_UTF8));//JDK1.8及以上可直接使⽤Base64,JDK1.7及以下可以使⽤BASE64Encoderreturn new String(Base64.getEncoder().encode(bytes));}/*** 3DES解密字符串--ECB格式** @param password 解密密码,长度不能够⼩于8位* @param data 待解密字符串* @return解密后内容*/public static String decryptECB(String password, String data) throws Exception {Key secretKey = generateKey(password);Cipher cipher = Cipher.getInstance(DES3_ECB);cipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom());return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET_UTF8))), CHARSET_UTF8); }/*** 3DES加密字符串-CBC加密格式** @param password 加密密码,长度不能够⼩于8位* @param data 待加密字符串* @return加密后内容*/public static String encryptCBC(String password, String data) throws Exception{Key secretKey = generateKey(password);Cipher cipher = Cipher.getInstance(DES3_CBC);IvParameterSpec spec=new IvParameterSpec("12345678".getBytes(CHARSET_UTF8));cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec);byte[] bytes = cipher.doFinal(data.getBytes(CHARSET_UTF8));//JDK1.8及以上可直接使⽤Base64,JDK1.7及以下可以使⽤BASE64Encoderreturn new String(Base64.getEncoder().encode(bytes));}/*** 3DES解密字符串--CBC格式** @param password 解密密码,长度不能够⼩于8位* @param data 待解密字符串* @return解密后内容*/public static String decryptCBC(String password, String data) throws Exception {Key secretKey = generateKey(password);Cipher cipher = Cipher.getInstance(DES3_CBC);IvParameterSpec spec=new IvParameterSpec("12345679".getBytes(CHARSET_UTF8));cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET_UTF8))), CHARSET_UTF8); }}。

java中的3DES加密

java中的3DES加密

java中的3DES加密java中的3DES加密,上代码:package com.picc.custportrait.utils.decode;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;/*** Base64编码⼯具类*/public class Base64Utils {private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); public static String encode(byte[] data) {int start = 0;int len = data.length;StringBuffer buf = new StringBuffer(data.length * 3 / 2);int end = len - 3;int i = start;int n = 0;while (i <= end) {int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff);buf.append(legalChars[(d >> 18) & 63]);buf.append(legalChars[(d >> 12) & 63]);buf.append(legalChars[(d >> 6) & 63]);buf.append(legalChars[d & 63]);i += 3;if (n++ >= 14) {n = 0;buf.append(" ");}}if (i == start + len - 2) {int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8);buf.append(legalChars[(d >> 18) & 63]);buf.append(legalChars[(d >> 12) & 63]);buf.append(legalChars[(d >> 6) & 63]);buf.append("=");} else if (i == start + len - 1) {int d = (((int) data[i]) & 0x0ff) << 16;buf.append(legalChars[(d >> 18) & 63]);buf.append(legalChars[(d >> 12) & 63]);buf.append("==");}return buf.toString();}private static int decode(char c) {if (c >= 'A' && c <= 'Z') {return ((int) c) - 65;} else if (c >= 'a' && c <= 'z') {return ((int) c) - 97 + 26;} else if (c >= '0' && c <= '9') {return ((int) c) - 48 + 26 + 26;} else {switch (c) {case '+':return 62;case '/':return 63;case '=':return 0;default:throw new RuntimeException("unexpected code: " + c);}}}/*** Decodes the given Base64 encoded String to a new byte array. The byte array holding the decoded data is returned.*/public static byte[] decode(String s) {ByteArrayOutputStream bos = new ByteArrayOutputStream();try {decode(s, bos);} catch (IOException e) {throw new RuntimeException();}byte[] decodedBytes = bos.toByteArray();try {bos.close();bos = null;} catch (IOException ex) {System.err.println("Error while decoding BASE64: " + ex.toString());}return decodedBytes;}private static void decode(String s, OutputStream os) throws IOException {int i = 0;int len = s.length();while (true) {while (i < len && s.charAt(i) <= ' ') {i++;}if (i == len) {break;}int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3))); os.write((tri >> 16) & 255);if (s.charAt(i + 2) == '=') {break;}os.write((tri >> 8) & 255);if (s.charAt(i + 3) == '=') {break;}os.write(tri & 255);i += 4;}}}package com.picc.custportrait.utils.decode;import javax.crypto.Cipher;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESedeKeySpec;import javax.crypto.spec.IvParameterSpec;import java.security.InvalidKeyException;import java.security.Key;* 3DES加密⼯具类*/public class SecretUtils {// 定义加密算法,有DES、DESede(即3DES)、Blowfishprivate static final String DES_ALGORITHM = "DESede";// 密钥// ⽣产环境// private static final String secretKey = "2019PiccACRMCustPortrait"; // 测试环境private static final String secretKey = "2019ABCDACPortraitRMCust"; // 向量// ⽣产环境// private final static String iv = "ac1rm9cp";// 测试环境private final static String iv = "012acrm3";// 加解密统⼀使⽤的编码⽅式private final static String encoding = "utf-8";/*** 3DES加密** @param plainText 普通⽂本* @return* @throws Exception* @throws Exception*/public static String encode(String plainText) throws Exception {Key deskey = null;DESedeKeySpec spec;spec = new DESedeKeySpec(secretKey.getBytes()); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(DES_ALGORITHM);deskey = keyfactory.generateSecret(spec);Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding)); return Base64Utils.encode(encryptData);}/*** 3DES解密** @param encryptText 加密⽂本* @return* @throws InvalidKeyException* @throws Exception*/public static String decode(String encryptText) throws Exception { Key deskey = null;DESedeKeySpec spec;byte[] decryptData = null;spec = new DESedeKeySpec(secretKey.getBytes()); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(DES_ALGORITHM);deskey = keyfactory.generateSecret(spec);Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, deskey, ips);decryptData = cipher.doFinal(Base64Utils.decode(encryptText)); return new String(decryptData, encoding);}// public static void main(String[] agrs) {// String asaa = null;// asaa = encode("0000京LZ5827");// System.out.println("加密后:" + asaa);//// System.out.println("加密前:" + decode(asaa)); //// asaa = encode("ACRM08521963");//// System.out.println("加密后:" + asaa);//// System.out.println("加密前:" + decode(asaa)); // } catch (Exception e) {// // TODO Auto-generated catch block// e.printStackTrace();// }//// }}。

java实现AES加密解密--数据加解密

java实现AES加密解密--数据加解密

java实现AES加密解密--数据加解密密码学中的⾼级加密标准(Advanced Encryption Standard,AES),⼜称Rijndael加密法,是美国联邦政府采⽤的⼀种区块加密标准。

这个标准⽤来替代原先的DES,已经被多⽅分析且⼴为全世界所使⽤。

AES的基本要求是,采⽤对称分组密码体制,密钥长度的最少⽀持为128、192、256,分组长度128位,算法应易于各种硬件和软件实现。

1998年NIST开始AES第⼀轮分析、测试和征集,共产⽣了15个候选算法。

1999年3⽉完成了第⼆轮AES2的分析、测试。

2000年10⽉2⽇美国政府正式宣布选中⽐利时密码学家Joan Daemen 和Vincent Rijmen 提出的⼀种密码算法RIJNDAEL 作为 AES. 在应⽤⽅⾯,尽管DES在安全上是脆弱的,但由于快速DES芯⽚的⼤量⽣产,使得DES仍能暂时继续使⽤,为提⾼安全强度,通常使⽤独⽴密钥的三级DES。

但是DES迟早要被AES代替。

流密码体制较之分组密码在理论上成熟且安全,但未被列⼊下⼀代加密标准。

AES加密数据块和密钥长度可以是128⽐特、192⽐特、256⽐特中的任意⼀个。

AES加密有很多轮的重复和变换。

⼤致步骤如下:1、密钥扩展(KeyExpansion),2、初始轮(Initial Round),3、重复轮(Rounds),每⼀轮⼜包括:SubBytes、ShiftRows、MixColumns、AddRoundKey,4、最终轮(Final Round),最终轮没有MixColumns。

JDK对DESede算法的⽀持密钥长度:128位⼯作模式:ECB/CBC/PCBC/CTR/CTS/CFB/CFB8 to CFB128/OFB/OBF8 to OFB128填充⽅式:Nopadding/PKCS5Padding/ISO10126Padding/AES加密解密的java实现:package com.kongxincai.encanddec;import java.security.Key;import java.security.NoSuchAlgorithmException;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;public class AESCoder {private static final String KEY_ALGORITHM = "AES";private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法public static byte[] initSecretKey() {//返回⽣成指定算法密钥⽣成器的 KeyGenerator 对象KeyGenerator kg = null;try {kg = KeyGenerator.getInstance(KEY_ALGORITHM);} catch (NoSuchAlgorithmException e) {e.printStackTrace();return new byte[0];}//初始化此密钥⽣成器,使其具有确定的密钥⼤⼩//AES 要求密钥长度为 128kg.init(128);//⽣成⼀个密钥SecretKey secretKey = kg.generateKey();return secretKey.getEncoded();}private static Key toKey(byte[] key){//⽣成密钥return new SecretKeySpec(key, KEY_ALGORITHM);}public static byte[] encrypt(byte[] data,Key key) throws Exception{return encrypt(data, key,DEFAULT_CIPHER_ALGORITHM);}public static byte[] encrypt(byte[] data,byte[] key) throws Exception{return encrypt(data, key,DEFAULT_CIPHER_ALGORITHM);}public static byte[] encrypt(byte[] data,byte[] key,String cipherAlgorithm) throws Exception{//还原密钥Key k = toKey(key);return encrypt(data, k, cipherAlgorithm);}public static byte[] encrypt(byte[] data,Key key,String cipherAlgorithm) throws Exception{ //实例化Cipher cipher = Cipher.getInstance(cipherAlgorithm);//使⽤密钥初始化,设置为加密模式cipher.init(Cipher.ENCRYPT_MODE, key);//执⾏操作return cipher.doFinal(data);}public static byte[] decrypt(byte[] data,byte[] key) throws Exception{return decrypt(data, key,DEFAULT_CIPHER_ALGORITHM);}public static byte[] decrypt(byte[] data,Key key) throws Exception{return decrypt(data, key,DEFAULT_CIPHER_ALGORITHM);}public static byte[] decrypt(byte[] data,byte[] key,String cipherAlgorithm) throws Exception{ //还原密钥Key k = toKey(key);return decrypt(data, k, cipherAlgorithm);}public static byte[] decrypt(byte[] data,Key key,String cipherAlgorithm) throws Exception{ //实例化Cipher cipher = Cipher.getInstance(cipherAlgorithm);//使⽤密钥初始化,设置为解密模式cipher.init(Cipher.DECRYPT_MODE, key);//执⾏操作return cipher.doFinal(data);}private static String showByteArray(byte[] data){if(null == data){return null;}StringBuilder sb = new StringBuilder("{");for(byte b:data){sb.append(b).append(",");}sb.deleteCharAt(sb.length()-1);sb.append("}");return sb.toString();}public static void main(String[] args) throws Exception {byte[] key = initSecretKey();System.out.println("key:"+showByteArray(key));Key k = toKey(key); //⽣成秘钥String data ="AES数据";System.out.println("加密前数据: string:"+data);System.out.println("加密前数据: byte[]:"+showByteArray(data.getBytes()));System.out.println();byte[] encryptData = encrypt(data.getBytes(), k);//数据加密System.out.println("加密后数据: byte[]:"+showByteArray(encryptData));// System.out.println("加密后数据: hexStr:"+Hex.encodeHexStr(encryptData));System.out.println();byte[] decryptData = decrypt(encryptData, k);//数据解密System.out.println("解密后数据: byte[]:"+showByteArray(decryptData));System.out.println("解密后数据: string:"+new String(decryptData));}}。

3DES双倍长加密

3DES双倍长加密

3DES双倍长加密import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;//结果与DES算法⼯具⼀致public class DES{public static void main(String[] args) {String key = "F2C04AD9F598EE61C424C9C7D39BA75F";String data = "06321643FF8B67EB";String des = encryptECB3Des(key,data);System.out.println(des);}public static String encryptECB3Des(String key, String src) {System.out.println("encryptECB3Des->" + "key:" + key);System.out.println("encryptECB3Des->" + "src:" + src);int len = key.length();if (key == null || src == null) {return null;}if (src.length() % 16 != 0) {return null;}if (len == 32) {String outData = "";String str = "";for (int i = 0; i < src.length() / 16; i++) {str = src.substring(i * 16, (i + 1) * 16);outData += encECB3Des(key, str);}return outData;}return null;}public static String encECB3Des(String key, String src) {byte[] temp = null;byte[] temp1 = null;temp1 = encryptDes(hexStringToBytes(key.substring(0, 16)), hexStringToBytes(src));temp = decryptDes(hexStringToBytes(key.substring(16, 32)), temp1);temp1 = encryptDes(hexStringToBytes(key.substring(0, 16)), temp);return bytesToHexString(temp1);}public static String decECB3Des(String key, String src) {byte[] temp2 = decryptDes(hexStringToBytes(key.substring(0, 16)), hexStringToBytes(src));byte[] temp1 = encryptDes(hexStringToBytes(key.substring(16, 32)), temp2);byte[] dest = decryptDes(hexStringToBytes(key.substring(0, 16)), temp1);return bytesToHexString(dest);}public static String bytesToHexString(byte[] src) {StringBuilder stringBuilder = new StringBuilder("");if (src == null || src.length <= 0) {return null;}for (int i = 0; i < src.length; i++) {int v = src[i] & 0xFF;String hv = Integer.toHexString(v);if (hv.length() < 2) {stringBuilder.append(0);}stringBuilder.append(hv);}return stringBuilder.toString();}public static byte[] hexStringToBytes(String hexString) {if (hexString == null || hexString.equals("")) {return null;}hexString = hexString.toUpperCase();int length = hexString.length() / 2;char[] hexChars = hexString.toCharArray();byte[] d = new byte[length];for (int i = 0; i < length; i++) {int pos = i * 2;d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));}return d;}private static byte charToByte(char c) {return (byte) "0123456789ABCDEF".indexOf(c);}/*** 3DES(双倍长) 解密** @param keybyte* @param src* @return*/public static String decryptECB3Des(String key, String src) {if (key == null || src == null) {return null;}if (src.length() % 16 != 0) {return null;}if (key.length() == 32) {String outData = "";String str = "";for (int i = 0; i < src.length() / 16; i++) {str = src.substring(i * 16, (i + 1) * 16);outData += decECB3Des(key, str);}return outData;}return null;}/*** DES加密**/public static byte[] encryptDes(byte[] key, byte[] src) {try {// 创建⼀个DESKeySpec对象DESKeySpec desKey = new DESKeySpec(key);// 创建⼀个密匙⼯⼚SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 将DESKeySpec对象转换成SecretKey对象SecretKey secretKey = keyFactory.generateSecret(desKey);// Cipher对象实际完成解密操作Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");// ⽤密匙初始化Cipher对象cipher.init(Cipher.ENCRYPT_MODE, secretKey);// 现在,获取数据并加密// 正式执⾏加密操作return cipher.doFinal(src);} catch (Exception e) {e.printStackTrace();}return null;}/*** des解密** @param key* @param src* @return*/public static byte[] decryptDes(byte[] key, byte[] src) {try {// DES算法要求有⼀个可信任的随机数源SecureRandom random = new SecureRandom();// 创建⼀个DESKeySpec对象DESKeySpec desKey = new DESKeySpec(key);// 创建⼀个密匙⼯⼚SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 将DESKeySpec对象转换成SecretKey对象SecretKey secretKey = keyFactory.generateSecret(desKey);// Cipher对象实际完成解密操作Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");// ⽤密匙初始化Cipher对象cipher.init(Cipher.DECRYPT_MODE, secretKey, random);// 现在,获取数据并加密// 正式执⾏加密操作return cipher.doFinal(src);} catch (Exception e) {e.printStackTrace(); }return null;}}。

Java中3DES加密解密示例

Java中3DES加密解密示例

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){ tring 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))); } }。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

在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)));
} }。

相关文档
最新文档