DES加密解密Java代码

fileName = jfc.getSelectedFile().getPath();
}
//如果没有选择目录,则退出
if (fileName == null) {
return;
}
//判断目录是否存在,如果不存在,则创建
File file = new File(fileName);
if (!file.exists())
//创建DES加密器
Cipher cipher = Cipher.getInstance("DES");//设 Nhomakorabea解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
//生成原文,存放在cipherText字节数组中
byte[] plainText = cipher.doFinal(cipherText);
JScrollPane jsp = new JScrollPane(jta, v, h);
//菜单
JMenuBar menuBar = new JMenuBar();
JMenu mainMenu = new JMenu("DES加密");
JMenuItem generateItem = new JMenuItem("生成密钥");
jfc.setDialogTitle("保存密钥");
//该文件选择对话框只能打开文件目录
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//如果选中,则获取选择的目录名称
if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
byte[] cipherText = cipher.doFinal(jta.getText().getBytes(
"UTF-8"));
//设置文件选择对话框
jfc = new JFileChooser();
jfc.setDialogTitle("保存加密文本内容");
//如果选中,则获取选择的文件的完整路径
if (fileName == null)
return;
//读取密文
FileInputStream fis = new FileInputStream(fileName);
byte[] cipherText = new byte[fis.available()];
fis.read(cipherText);
//DES加密:(1)生成密钥文件(2)利用密钥,加密文件(3)根据密钥,对加密的文件解密
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
e1.printStackTrace();
}
} else if (e.getSource() == decryptItem) {
try {
//读取密钥文件的完整路径
String fileName = null;
//设置文件选择对话框
JFileChooser jfc = new JFileChooser();
mainMenu.add(generateItem);
mainMenu.addSeparator();
mainMenu.add(encryptItem);
mainMenu.add(decryptItem);
menuBar.add(mainMenu);
setJMenuBar(menuBar);
//添加文本区
fileName = jfc.getSelectedFile().getPath();
}
//如果没有选择文件,则退出
if (fileName == null) {
return;
}
//读取密钥文件
ObjectInputStream in = new ObjectInputStream(
new FileInputStream(fileName));
add(jsp);
//添加事件监听
generateItem.addActionListener(this);
encryptItem.addActionListener(this);
decryptItem.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == generateItem) {
try {
//保存密钥文件的目录路径(主要用来设置密钥的保存路径)
String fileName = null;
//设置文件选择对话框
JFileChooser jfc = new JFileChooser();
import javax.crypto.KeyGenerator;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
public class DES {
public static void main(String args[]) {
JTextArea jta = new JTextArea();
//设置文本区的滚动条
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
Key key = (Key) in.readObject();
//创建DES加密器
Cipher cipher = Cipher.getInstance("DES");
//设置加密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
//生成密文,存放在cipherText字节数组中
if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
fileName = jfc.getSelectedFile().getPath();
}
//如果没有选择文件,则退出
if (fileName == null)
return;
//将密文存储到指定文件中
fis.close();
//设置文件选择对话框
jfc = new JFileChooser();
jfc.setDialogTitle("导入密钥文件");
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
fileName = jfc.getSelectedFile().getPath();
file.mkdir();
//创建DES密钥生成器
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
//采用56位DES密钥
keyGen.init(56);
//生成DES密钥
Key key = keyGen.generateKey();
System.out.println(key);
//设置文件选择对话框
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("导入密钥文件");
//如果选中,则获取选择文件的完整路径
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
.getScreenSize().height / 3);
dw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dw.setVisible(true);
}
}
class DemoWindow1 extends JFrame implements ActionListener {
DemoWindow1 dw = new DemoWindow1("DES加密程序");
dw.setBounds(dw.getToolkit().getScreenSize().width / 3, dw.getToolkit()
合集下载

JavaDES解密代码

JavaDES解密代码

JavaDES解密代码import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import javax.crypto.Cipher;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import javax.crypto.spec.IvParameterSpec;import java.security.Key;public class DESUtils {/*** 密钥算法*/private static final String ALGORITHM = "DES";/*** 加密/解密算法-⼯作模式-填充模式*/private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";/*** 默认编码*/private static final String CHARSET = "utf-8";public static void main(String[] args) {//偏移变量,固定占8位字节String iv = "54a6cc76";//密码String password = "54a6cc76-e700-a1b2-fa3d-fb966efb7578";//加密String data = "1234567890";String encrypt = encrypt(password, iv, data);System.out.println(encrypt);//解密String decrypt = decrypt(password, iv, encrypt);System.out.println(decrypt);}/*** ⽣成key** @param password* @return* @throws Exception*/private static Key generateKey(String password) throws Exception {DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);return keyFactory.generateSecret(dks);}/*** DES加密字符串** @param password 加密密码,长度不能够⼩于8位* @param data 待加密字符串* @param ivParam 偏移向量* @return 加密后内容*/public static String encrypt(String password, String ivParam, String data) {if (password== null || password.length() < 8) {throw new RuntimeException("加密失败,key不能⼩于8位");}if (data == null){return null;}try {Key secretKey = generateKey(password);Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);IvParameterSpec iv = new IvParameterSpec(ivParam.getBytes(CHARSET));cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));BASE64Encoder encoder = new BASE64Encoder();return new String(encoder.encode(bytes));} catch (Exception e) {e.printStackTrace();return data;}}/*** DES解密字符串** @param password 解密密码,长度不能够⼩于8位* @param ivParam 偏移向量* @param data 待解密字符串* @return 解密后内容*/public static String decrypt(String password, String ivParam, String data) {if (password== null || password.length() < 8) {throw new RuntimeException("加密失败,key不能⼩于8位");}if (data == null){return null;}try {Key secretKey = generateKey(password);Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);IvParameterSpec iv = new IvParameterSpec(ivParam.getBytes(CHARSET)); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);BASE64Decoder decoder = new BASE64Decoder();return new String(cipher.doFinal(decoder.decodeBuffer(data)), CHARSET); } catch (Exception e) {e.printStackTrace();return data;}}}。

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

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

Java 加密解密之对称加密算法DES本文转自网络数据加密算法(Data Encryption Algorithm,DEA)是一种对称加密算法,很可能是使用最广泛的密钥系统,特别是在保护金融数据的安全中,最初开发的DEA 是嵌入硬件中的。

通常,自动取款机(Automated Teller Machine,ATM)都使用DEA。

它出自IBM的研究工作,IBM也曾对它拥有几年的专利权,但是在1983年已到期后,处于公有范围中,允许在特定条件下可以免除专利使用费而使用。

1977年被美国政府正式采纳。

1998年后实用化DES破译机的出现彻底宣告DES算法已不具备安全性,1999年NIST颁布新标准,规定DES算法只能用于遗留加密系统,但不限制使用DESede算法。

当今DES算法正是推出历史舞台,AES算法称为他的替代者。

(详见:Java 加密解密之对称加密算法AES)加密原理DES 使用一个56 位的密钥以及附加的8 位奇偶校验位,产生最大64 位的分组大小。

这是一个迭代的分组密码,使用称为Feistel 的技术,其中将加密的文本块分成两半。

使用子密钥对其中一半应用循环功能,然后将输出与另一半进行“异或”运算;接着交换这两半,这一过程会继续下去,但最后一个循环不交换。

DES 使用16 个循环,使用异或,置换,代换,移位操作四种基本运算。

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

JAVA 实现 DES 可视化界面程序

JAVA 实现 DES 可视化界面程序

JAVA 实现 DES的加密解密运行结果如图:具体代码如下:package DES;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;public class mydes implements ActionListener{static boolean a=false;static String key =null;public static JFrame fr=new JFrame();public static JTextField output=new JTextField("");public static JTextField Input=new JTextField("请输入要加密或者解密的明文,加密文件请浏览文件路径");public static JTextField Result=new JTextField("请输入密钥,软件将自动调节密码的有效位");public static JButton open=new JButton("浏览文件");public static JButton change=new JButton("加密文件");public static JButton change1=new JButton("加密字符串");public static JButton encrypt=new JButton("加密");public static JButton encrypt1=new JButton("加密");public static JButton deciphering=new JButton("解密");public static JButton deciphering1=new JButton("解密");byte[] bytekey;public mydes() {fr.setTitle("DES加密解密");int w = (Toolkit.getDefaultToolkit().getScreenSize().width - 345) / 2;int h = (Toolkit.getDefaultToolkit().getScreenSize().height - 630) / 2;fr.setLocation(w, h);fr.setLayout(null);fr.setResizable(false);fr.setSize(565, 330);open.setBounds(320, 80, 100,40);change.setBounds(440, 20, 100,40);change1.setBounds(440, 20, 100,40);deciphering.setBounds(440, 140, 100,40);encrypt.setBounds(440, 80, 100,40);deciphering1.setBounds(260, 220, 100,40);encrypt1.setBounds(80, 220, 100,40);Input.setBounds(18, 20,410,40);Result.setBounds(18, 80, 410,40);output.setBounds(18, 140, 410,40);fr.add(open);fr.add(change);fr.add(change1);fr.add(encrypt);fr.add(encrypt1);fr.add(Input);fr.add(output);fr.add(deciphering);fr.add(deciphering1);fr.add(Result);change1.setVisible(false);open.setVisible(false);encrypt1.setVisible(false);deciphering1.setVisible(false);open.addActionListener(this);change.addActionListener(this);change1.addActionListener(this);deciphering.addActionListener(this);encrypt.addActionListener(this);deciphering1.addActionListener(this);encrypt1.addActionListener(this);fr.setVisible(true);fr.addWindowListener(new WindowAdapter(){public void windowClosing( WindowEvent e ){System.exit(0);}});key=Result.getText();this.bytekey =key.getBytes();}// 声明常量字节数组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 }; // 64private static final int[] IP_1 = { 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 }; // 64private static final int[] PC_1 = { 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 }; // 56private static final int[] PC_2 = { 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 }; // 48private 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 }; // 48 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 }; // 32private static final int[][][] S_Box = {//S-盒{// S_Box[1]{ 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 } },{ // S_Box[2]{ 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 } },{ // S_Box[3]{ 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 } },{ // S_Box[4]{ 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 } },{ // S_Box[5]{ 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 } },{ // S_Box[6]{ 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 } },{ // S_Box[7]{ 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 } },{ // S_Box[8]{ 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 final int[] LeftMove = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,2, 2, 2, 1 }; // 左移位置列表private byte[] mydes(byte[] des_key, byte[] des_data, int flag) {if ((des_key.length != 8) || (des_data.length != 8)|| ((flag != 1) && (flag != 0))) JOptionPane.showMessageDialog(null, "数据错误");int flags = flag;int[] keydata = new int[64];int[] encryptdata = new int[64];byte[] EncryptCode = new byte[8];int[][] KeyArray = new int[16][48];keydata = tobebinary(des_key);encryptdata = tobebinary(des_data);keybytechange(keydata, KeyArray);EncryptCode = Encrypt(encryptdata, flags, KeyArray);return EncryptCode;}private void keybytechange(int[] key, int[][] keyarray) {int i;int j;int[] K0 = new int[56];for (i = 0; i < 56; i++) {K0[i] = key[PC_1[i] - 1];}for (i = 0; i < 16; i++) {LeftBitMove(K0, LeftMove[i]);for (j = 0; j < 48; j++) {keyarray[i][j] = K0[PC_2[j] - 1];}}private byte[] Encrypt(int[] timeData, int flag, int[][] keyarray) { int i;byte[] encrypt = new byte[8];int flags = flag;int[] M = new int[64];int[] MIP_1 = new int[64];for (i = 0; i < 64; i++) {M[i] = timeData[IP[i] - 1];}if (flags == 1) { //1表示加密文件for (i = 0; i < 16; i++) {everychange(M, i, flags, keyarray);}} else if (flags == 0) { // 0表示文件解密for (i = 15; i > -1; i--) {everychange(M, i, flags, keyarray);}}for (i = 0; i < 64; i++) {MIP_1[i] = M[IP_1[i] - 1];}GetEncryptResultOfByteArray(MIP_1, encrypt);return encrypt;}private int[] tobebinary(byte[] intdata) {int i;int j;int[] IntDa = new int[8];for (i = 0; i < 8; i++) {IntDa[i] = intdata[i];if (IntDa[i] < 0) {IntDa[i] += 256;IntDa[i] %= 256;}}int[] IntVa = new int[64];for (i = 0; i < 8; i++) {for (j = 0; j < 8; j++) {IntVa[((i * 8) + 7) - j] = IntDa[i] % 2;IntDa[i] = IntDa[i] / 2;}}return IntVa;}private void LeftBitMove(int[] k, int offset) { int i;int[] c0 = new int[28];int[] d0 = new int[28];int[] c1 = new int[28];int[] d1 = new int[28];for (i = 0; i < 28; i++) {c0[i] = k[i];d0[i] = k[i + 28];}if (offset == 1) {for (i = 0; i < 27; i++) {c1[i] = c0[i + 1];d1[i] = d0[i + 1];}c1[27] = c0[0];d1[27] = d0[0];} else if (offset == 2) {for (i = 0; i < 26; i++) {c1[i] = c0[i + 2];d1[i] = d0[i + 2];}c1[26] = c0[0];d1[26] = d0[0];c1[27] = c0[1];d1[27] = d0[1];}for (i = 0; i < 28; i++) {k[i] = c1[i];k[i + 28] = d1[i];}}private void everychange(int[] M, int times, int flag, int[][] keyarray) { int i;int j;int[] L0 = new int[32];int[] R0 = new int[32];int[] L1 = new int[32];int[] R1 = new int[32];int[] RE = new int[48];int[][] S = new int[8][6];int[] sBoxData = new int[8];int[] sValue = new int[32];int[] RP = new int[32];for (i = 0; i < 32; i++) {L0[i] = M[i];R0[i] = M[i + 32];}for (i = 0; i < 48; i++) {RE[i] = R0[E[i] - 1]; // 经过E变换扩充,由32位变为48位RE[i] = RE[i] + keyarray[times][i];if (RE[i] == 2) {RE[i] = 0;}}for (i = 0; i < 8; i++) { // 48位分成8组for (j = 0; j < 6; j++) {S[i][j] = RE[(i * 6) + j];}// 下面经过S盒,得到8个数sBoxData[i] = S_Box[i][(S[i][0] << 1) + S[i][5]][(S[i][1] << 3) + (S[i][2] << 2) + (S[i][3] << 1) + S[i][4]];// 8个数变换输出二进制for (j = 0; j < 4; j++) {sValue[((i * 4) + 3) - j] = sBoxData[i] % 2;sBoxData[i] = sBoxData[i] / 2;}}for (i = 0; i < 32; i++) {RP[i] = sValue[P[i] - 1]; // 经过P变换L1[i] = R0[i];R1[i] = L0[i] + RP[i];if (R1[i] == 2) {R1[i] = 0;}if (((flag == 0) && (times == 0)) || ((flag == 1) && (times == 15))) { M[i] = R1[i];M[i + 32] = L1[i];}else {M[i] = L1[i];M[i + 32] = R1[i];}}}private void GetEncryptResultOfByteArray(int[] data, byte[] value) {int i;int j;for (i = 0; i < 8; i++) {for (j = 0; j < 8; j++) {value[i] += (data[(i << 3) + j] << (7 - j));}}for (i = 0; i < 8; i++) {value[i] %= 256;if (value[i] > 128) {value[i] -= 255;}}}private byte[] ByteDataFormat(byte[] data) {int len = data.length;int padlen = 8 - (len % 8);int newlen = len + padlen;byte[] newdata = new byte[newlen];System.arraycopy(data, 0, newdata, 0, len);for (int i = len; i < newlen; i++)newdata[i] = (byte) padlen;return newdata;}public byte[] finalEncrypt(byte[] des_data, int flag) {byte[] format_key = ByteDataFormat(bytekey);byte[] format_data = ByteDataFormat(des_data); int datalen = format_data.length;int unitcount = datalen / 8;byte[] result_data = new byte[datalen];for (int i = 0; i < unitcount; i++) {byte[] tmpkey = new byte[8];byte[] tmpdata = new byte[8];System.arraycopy(format_key, 0, tmpkey, 0, 8);System.arraycopy(format_data, i * 8, tmpdata, 0, 8);byte[] tmpresult = mydes(tmpkey, tmpdata, flag);System.arraycopy(tmpresult, 0, result_data, i * 8, 8);} // 当前为解密过程,去掉加密时产生的填充位byte[] decryptbytearray = null;if (flag == 0) {int total_len = datalen;int delete_len = result_data[total_len - 8 - 1];delete_len = ((delete_len >= 1) && (delete_len <= 8)) ? delete_len : 0;decryptbytearray = new byte[total_len - delete_len - 8];boolean del_flag = true;for (int k = 0; k < delete_len; k++) {if (delete_len != result_data[total_len - 8 - (k + 1)])del_flag = false;}if (del_flag == true) {System.arraycopy(result_data, 0, decryptbytearray, 0, total_len- delete_len - 8); }}return (flag == 1) ? result_data : decryptbytearray;}public static void main(String[] args) {DesUtil des = new DesUtil();}static byte[] result;public void actionPerformed(ActionEvent e) {if(e.getSource()==encrypt){String data = Input.getText();key=Result.getText();this.bytekey =key.getBytes();if (Result.getText().length()<=3){JOptionPane.showMessageDialog(null, "密钥太短","错误", JOptionPane.ERROR_MESSAGE);return;}result = finalEncrypt(data.getBytes(), 1);output.setText(new String(result));}if(e.getSource()==deciphering){output.setText(new String(finalEncrypt(result, 0)));}if(output.getText().length()==0&&e.getSource()==deciphering){String data = Input.getText();key=Result.getText();if (Result.getText().length()<=3){JOptionPane.showMessageDialog(null, "密钥太短","错误", JOptionPane.ERROR_MESSAGE);return;}this.bytekey =key.getBytes();result = finalEncrypt(data.getBytes(), 0);output.setText(new String(result));System.err.println("解密后明文:"+ new String(finalEncrypt(result, 0)));}if(e.getSource()==change){output.setText("请输入密钥");Input.setEditable(a);encrypt1.setVisible(!a);deciphering1.setVisible(!a);encrypt.setVisible(a);deciphering.setVisible(a);open.setVisible(!a);change.setVisible(a);change1.setVisible(!a);Result.setVisible(a);a=!a;}if(e.getSource()==change1){output.setText("");Input.setEditable(a);encrypt1.setVisible(!a);deciphering1.setVisible(!a);encrypt.setVisible(a);deciphering.setVisible(a);open.setVisible(!a);change.setVisible(a);change1.setVisible(!a);Result.setVisible(a);a=!a;}if(e.getSource()==open){JFileChooser chooser=new JFileChooser();int intRetVal = chooser.showOpenDialog(fr);if( intRetVal == JFileChooser.APPROVE_OPTION){ Input.setText(chooser.getSelectedFile().getPath());try{File file = chooser.getSelectedFile();final FileInputStream fis = new FileInputStream(file);final byte[] bytIn = new byte[(int)file.length()];for(int i = 0;i<file.length();i++){bytIn[i] = (byte)fis.read();}result=bytIn;} catch(Exception el){JOptionPane.showMessageDialog(null, "失败");}}}if(e.getSource()==encrypt1){try{key=output.getText();if(output.getText().length()<=3){JOptionPane.showMessageDialog(null, "密钥太短");return;}this.bytekey =key.getBytes();final byte[] bytOut = finalEncrypt(result, 1);final String fileOut = Input.getText();final FileOutputStream fos = new FileOutputStream(fileOut);for(int i = 0;i<bytOut.length;i++){fos.write((int)bytOut[i]);}fos.close();JOptionPane.showMessageDialog(null, "加密成功!已经覆盖源文件"); }catch(Exception el){JOptionPane.showMessageDialog(null, "加密失败!");}}if(e.getSource()==deciphering1){try{key=output.getText();if(output.getText().length()<=3){JOptionPane.showMessageDialog(null, "密钥太短");return;}this.bytekey =key.getBytes();JOptionPane.showMessageDialog(null, "请选择解密文件存储位置和文件名");final JFileChooser chooser = new JFileChooser();chooser.setCurrentDirectory(new File("."));File file = new File(Input.getText());final int ret = chooser.showSaveDialog(fr);if(ret==JFileChooser.APPROVE_OPTION){final FileInputStream fis = new FileInputStream(file);final byte[] bytIn = new byte[(int)file.length()];for(int i = 0;i<file.length();i++){bytIn[i] = (byte)fis.read();}final byte[] bytOut = finalEncrypt(bytIn, 0);final File fileOut = chooser.getSelectedFile();fileOut.createNewFile();final FileOutputStream fos = new FileOutputStream(fileOut);for(int i = 0;i<bytOut.length;i++){fos.write((int)bytOut[i]);}fos.close();}JOptionPane.showMessageDialog(null, "解密密成功!文件已生成");}catch(Exception el){JOptionPane.showMessageDialog(null, "解密失败");}}}}。

DES加密解密Java代码

DES加密解密Java代码
mainMenu.add(generateItem);
mainMenu.addSeparator();
mainMenu.add(encryptItem);
mainMenu.add(decryptItem);
menuBar.add(mainMenu);
setJMenuBar(menuBar);
//添加文本区
if (fileName == null)
return;
//读取密文
FileInputStream fis = new FileInputStream(fileName);
byte[] cipherText = new byte[fis.available()];
fis.read(cipherText);
jfc.setDialogTitle("打开加密文本内容");
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
fileName = jfc.getSelectedFile().getPath();
}
//如果没有选择文件,就退出
e1.printStackTrace();
}
} else if (e.getSource() == decryptItem) {
try {
//读取密钥文件的完整路径
String fileName = null;
//设置文件选择对话框
JFileChooser jfc = new JFileChooser();
add(jsp);
//添加事件监听
generateItem.addActionListener(this);

java中DES加密解密

java中DES加密解密

java中DES加密解密废话不多说,直接奉上代码:代码⼀package com.eabax.plugin.yundada.utils;import java.io.IOException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.security.spec.InvalidKeySpecException;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import mons.codec.binary.Base64;import sun.misc.BASE64Decoder;public class DESEncryptHelper {private final static String DES = "DES";/*** ⽣成密钥* @param employeeCode*/public static String getDESKey(String encryptStr){if (!CacheManager.getCache().containsKey("encryptKey_"+encryptStr)) {CacheManager.getCache().put("encryptKey_"+encryptStr, encryptStr+"tablemiyaokey");}String key = (String) CacheManager.getCache().get("encryptKey_"+encryptStr);return key;}/*** Description 根据键值进⾏解密* @param data* @param key 加密键byte数组* @return* @throws IOException* @throws Exception*/public static String decrypt(String data, String key) throws IOException,Exception {if (data == null)return null;BASE64Decoder decoder = new BASE64Decoder();byte[] buf = decoder.decodeBuffer(data);byte[] bt = decrypt(buf,key.getBytes());return new String(bt);}/*** 对字符串加密* @param str* @return* @throws InvalidKeyException* @throws IllegalBlockSizeException* @throws BadPaddingException* @throws InvalidKeySpecException* @throws NoSuchAlgorithmException* @throws NoSuchPaddingException*/public static String getEncryptStr(String str,String encryptStr) throws InvalidKeyException,IllegalBlockSizeException, BadPaddingException,InvalidKeySpecException, NoSuchAlgorithmException,NoSuchPaddingException {//获取keyString key = getDESKey(encryptStr);//获取密钥SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");DESKeySpec keyspec = new DESKeySpec(key.getBytes());SecretKey deskey = factory.generateSecret(keyspec);// Cipher负责完成加密或解密⼯作Cipher c = Cipher.getInstance("DES");// 根据密钥,对Cipher对象进⾏初始化,DECRYPT_MODE表⽰加密模式 c.init(Cipher.ENCRYPT_MODE, deskey);byte[] src = str.getBytes();// 该字节数组负责保存加密的结果byte[] cipherByte = c.doFinal(src);String enstr = new String(Base64.encodeBase64(cipherByte));return enstr;}/*** Description 根据键值进⾏解密* @param data* @param key 加密键byte数组* @return* @throws Exception*/private static byte[] decrypt(byte[] data, byte[] key) throws Exception { // ⽣成⼀个可信任的随机数源SecureRandom sr = new SecureRandom();// 从原始密钥数据创建DESKeySpec对象DESKeySpec dks = new DESKeySpec(key);// 创建⼀个密钥⼯⼚,然后⽤它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks);// Cipher对象实际完成解密操作Cipher cipher = Cipher.getInstance(DES);// ⽤密钥初始化Cipher对象cipher.init(Cipher.DECRYPT_MODE, securekey, sr);return cipher.doFinal(data);}}代码⼆package mon;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import sun.misc.BASE64Encoder;public class DES ...{private byte[] desKey;public DES(byte[] desKey) ...{this.desKey = desKey;}public byte[] doEncrypt(byte[] plainText) throws Exception ...{// DES算法要求有⼀个可信任的随机数源SecureRandom sr = new SecureRandom();byte rawKeyData[] = desKey;/**//* ⽤某种⽅法获得密匙数据 */// 从原始密匙数据创建DESKeySpec对象DESKeySpec dks = new DESKeySpec(rawKeyData);// 创建⼀个密匙⼯⼚,然后⽤它把DESKeySpec转换成// ⼀个SecretKey对象SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks);// Cipher对象实际完成加密操作Cipher cipher = Cipher.getInstance("DES");// ⽤密匙初始化Cipher对象cipher.init(Cipher.ENCRYPT_MODE, key, sr);// 现在,获取数据并加密byte data[] = plainText;/**//* ⽤某种⽅法获取数据 */// 正式执⾏加密操作byte encryptedData[] = cipher.doFinal(data);return encryptedData;}public byte[] doDecrypt(byte[] encryptText) throws Exception ...{// DES算法要求有⼀个可信任的随机数源SecureRandom sr = new SecureRandom();byte rawKeyData[] = desKey; /**//* ⽤某种⽅法获取原始密匙数据 */// 从原始密匙数据创建⼀个DESKeySpec对象DESKeySpec dks = new DESKeySpec(rawKeyData);// 创建⼀个密匙⼯⼚,然后⽤它把DESKeySpec对象转换成// ⼀个SecretKey对象SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey key = keyFactory.generateSecret(dks);// Cipher对象实际完成解密操作Cipher cipher = Cipher.getInstance("DES");// ⽤密匙初始化Cipher对象cipher.init(Cipher.DECRYPT_MODE, key, sr);// 现在,获取数据并解密byte encryptedData[] = encryptText;/**//* 获得经过加密的数据 */// 正式执⾏解密操作byte decryptedData[] = cipher.doFinal(encryptedData);return decryptedData;}public static void main(String[] args) throws Exception ...{String key = "FtpXPass";String value = "olympic";BASE64Encoder base64Encoder = new BASE64Encoder();DES desEncrypt = new DES(key.getBytes());byte[] encryptText = desEncrypt.doEncrypt(value.getBytes());//System.out.println("doEncrypt - " + toHexString(encryptText));System.out.println("doEncrypt - "+ base64Encoder.encode(encryptText));byte[] decryptText = desEncrypt.doDecrypt("r9NGYcKAtdo=".getBytes());System.out.println("doDecrypt - " + new String(decryptText));//System.out.println("doDecrypt - " + toHexString(decryptText));}public static String toHexString(byte[] value) ...{String newString = "";for (int i = 0; i < value.length; i++) ...{byte b = value[i];String str = Integer.toHexString(b);if (str.length() > 2) ...{str = str.substring(str.length() - 2);}if (str.length() < 2) ...{str = "0" + str;}newString += str;}return newString.toUpperCase();}}以上就是本⽂关于DES加密解密的代码了,希望对⼤家学习java有所帮助。

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

DES 加解密算法(java和c#版)

/** java 版的* <p>Title: DES 加解密算法</p>* <p>Description: DES 加解密算法</p>* <p>Copyright: Copyright (c) 2004</p>* <p>Company: Aspire Corp</p>* @author zhangji* @version 1.0*/import java.security.*;import javax.crypto.*;public class DES {private static String strDefaultKey = "hnzt";private Cipher encryptCipher = null;private Cipher decryptCipher = null;/*** 将byte数组转换为表示16进制值的字符串,* 如:byte[]{8,18}转换为:0813,* 和public static byte[] hexStr2ByteArr(String strIn)* 互为可逆的转换过程* @param arrB 需要转换的byte数组* @return 转换后的字符串* @throws Exception 本方法不处理任何异常,所有异常全部抛出*/public static String byteArr2HexStr(byte[] arrB)throws Exception{int iLen = arrB.length;//每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍StringBuffer sb = new StringBuffer(iLen * 2);for (int i = 0; i < iLen; i++){int intTmp = arrB[i];//把负数转换为正数while (intTmp < 0){intTmp = intTmp + 256;}//小于0F的数需要在前面补0if (intTmp < 16){sb.append("0");}sb.append(Integer.toString(intTmp, 16));}return sb.toString();}/*** 将表示16进制值的字符串转换为byte数组,* 和public static String byteArr2HexStr(byte[] arrB)* 互为可逆的转换过程* @param strIn 需要转换的字符串* @return 转换后的byte数组* @throws Exception 本方法不处理任何异常,所有异常全部抛出* @author <a href="mailto:zhangji@">ZhangJi</a> */public static byte[] hexStr2ByteArr(String strIn)throws Exception{byte[] arrB = strIn.getBytes();int iLen = arrB.length;//两个字符表示一个字节,所以字节数组长度是字符串长度除以2byte[] arrOut = new byte[iLen / 2];for (int i = 0; i < iLen; i = i + 2){String strTmp = new String(arrB, i, 2);arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);}return arrOut;}/*** 默认构造方法,使用默认密钥* @throws Exception*/public DES()throws Exception{this(strDefaultKey);}/*** 指定密钥构造方法* @param strKey 指定的密钥* @throws Exception*/public DES(String strKey)throws Exception{Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes());encryptCipher = Cipher.getInstance("DES");encryptCipher.init(Cipher.ENCRYPT_MODE, key);decryptCipher = Cipher.getInstance("DES");decryptCipher.init(Cipher.DECRYPT_MODE, key);}/*** 加密字节数组* @param arrB 需加密的字节数组* @return 加密后的字节数组* @throws Exception*/public byte[] encrypt(byte[] arrB)throws Exception{return encryptCipher.doFinal(arrB);}/*** 加密字符串* @param strIn 需加密的字符串* @return 加密后的字符串* @throws Exception*/public String encrypt(String strIn)throws Exception{return byteArr2HexStr(encrypt(strIn.getBytes())); }/*** 解密字节数组* @param arrB 需解密的字节数组* @return 解密后的字节数组* @throws Exception*/public byte[] decrypt(byte[] arrB)throws Exception{return decryptCipher.doFinal(arrB);}/*** 解密字符串* @param strIn 需解密的字符串* @return 解密后的字符串* @throws Exception*/public String decrypt(String strIn)throws Exception{return new String(decrypt(hexStr2ByteArr(strIn)));}/*** 从指定字符串生成密钥,密钥所需的字节数组长度为8位* 不足8位时后面补0,超出8位只取前8位* @param arrBTmp 构成该字符串的字节数组* @return 生成的密钥* @throws ng.Exception*/private Key getKey(byte[] arrBTmp)throws Exception{//创建一个空的8位字节数组(默认值为0)byte[] arrB = new byte[8];//将原始字节数组转换为8位for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {arrB[i] = arrBTmp[i];}//生成密钥Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key;}/*** 单元测试方法* @param args*/public static void main(String[] args){String strOriginal = "1111";String strOp = "-de";// 检查入参个数if (args.length == 2 ){strOp = args[0] ;strOriginal = args[1];}else{System.out.println("Wrong Parameter count , try use \"java DES -de|-en 'the string you want to be Encrypted'\"");System.out.println("Now do Encrypt with \"1111\"");try{DES des = new DES();// 加密测试System.out.println("***** 加密测试 *****") ;des.enTest("1111");// 解密测试System.out.println("***** 解密测试 *****") ;des.deTest("0fc7648b53e54cfb");}catch (Exception ex){ex.printStackTrace();}return ;}try{if ( strOp.equals("-de")) {DES des = new DES();des.deTest(strOriginal);}else if ( strOp.equals("-en")) {DES des = new DES();des.enTest(strOriginal);}else{System.out.println("Wrong operater , try use \"java DES -de|-en 'the string you want to be Encrypted'\"");System.out.println("Now do Encrypt with \"1111\""); }}catch (Exception ex){ex.printStackTrace();}}/*** 单元测试方法,打印对指定字符串加密后的字符串*/private void enTest(String strOriginal){try{System.out.println("Plain String: " + strOriginal);String strEncrypt= encrypt(strOriginal);System.out.println("Encrypted String: " + strEncrypt);}catch (Exception ex){ex.printStackTrace();}}/*** 单元测试方法,打印对指定字符串解密后的字符串*/private void deTest(String strOriginal){try{System.out.println("Encrypted String: " + strOriginal); System.out.println("Encrypted String length = " + strOriginal.length());String strPlain = decrypt(strOriginal);System.out.println("Plain String: " + strPlain);}catch (Exception ex){ex.printStackTrace();}}}===============c#版的================using System;using System.Text;using System.IO;using System.Security.Cryptography;class Class1{static void Main(){Console.WriteLine("Encrypt String...");txtKey = "tkGGRmBErvc=";btnKeyGen();Console.WriteLine("Encrypt Key :{0}",txtKey);txtIV = "Kl7ZgtM1dvQ=";btnIVGen();Console.WriteLine("Encrypt IV :{0}",txtIV);Console.WriteLine();string txtEncrypted = EncryptString("1111");Console.WriteLine("Encrypt String : {0}",txtEncrypted);string txtOriginal = DecryptString(txtEncrypted);Console.WriteLine("Decrypt String : {0}",txtOriginal);}private static SymmetricAlgorithm mCSP;private static string txtKey;private static string txtIV;private static void btnKeyGen(){mCSP = SetEnc();byte[] byt2 = Convert.FromBase64String(txtKey);mCSP.Key = byt2;}private static void btnIVGen(){byte[] byt2 = Convert.FromBase64String(txtIV);mCSP.IV = byt2;}private static string EncryptString(string Value){ICryptoTransform ct;MemoryStream ms;CryptoStream cs;byte[] byt;ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);byt = Encoding.UTF8.GetBytes(Value);ms = new MemoryStream();cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length);cs.FlushFinalBlock();cs.Close();return Convert.ToBase64String(ms.ToArray());}private static string DecryptString(string Value){ICryptoTransform ct;MemoryStream ms;CryptoStream cs;byte[] byt;ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);byt = Convert.FromBase64String(Value);ms = new MemoryStream();cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length);cs.FlushFinalBlock();cs.Close();return Encoding.UTF8.GetString(ms.ToArray());}private static SymmetricAlgorithm SetEnc() {return new DESCryptoServiceProvider(); }}。

一个java的DES加解密类转换成C#

一个java的DES加解密类转换成C#一个java的des加密解密代码如下://package com.visionsky.util;import java.security.*;//import java.util.regex.Pattern;//import java.util.Hashtable;import javax.crypto.*;import javax.crypto.spec.*;import sun.misc.*;/*** des加密解密*/public class DESPlus {private static String strDefaultKey = "PLFP"; //默认密钥private static final byte[] iv = {0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef};//des 向量private static BASE64Encoder enc = new BASE64Encoder();//将byte[]转换成Stringprivate static BASE64Decoder dec = new BASE64Decoder(); //将String 转换成byte[]/*** 加密字节数组** @param arrB* 需加密的字节数组* @param key* 密钥* @return 加密后的字节数组* @throws Exception*/public static byte[] encrypt(byte[] arrB, String key) throws Exception {DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey secretKey = keyFactory.generateSecret(desKeySpec);IvParameterSpec ivp = new IvParameterSpec(DESPlus.iv);Cipher encryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivp);return encryptCipher.doFinal(arrB);}/*** 加密字符串** @param xml* 需加密的字符串* @param key* 密钥* @return 加密后的字符串*/public static String encrypt(String xml, String key) throws Exception {//return DESPlus.enc.encode(encrypt(xml.getBytes(), key));return new String(encrypt(xml.getBytes(), key));}/*** 使用默认公钥加密字符串* @param xml 需加密的字符串* @return 加密后的字符串* @throws Exception*/public static String encrypt(String xml) throws Exception {return encrypt(xml, strDefaultKey);}/*** 解密字节数组** @param arrB* 需解密的字节数组* @param key* 密钥* @return 解密后的字节数组*/public static byte[] decrypt(byte[] arrB, String key) throws Exception {DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey secretKey = keyFactory.generateSecret(desKeySpec);IvParameterSpec ivp = new IvParameterSpec(DESPlus.iv);Cipher decryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");decryptCipher.init(Cipher.DECRYPT_MODE, secretKey, ivp);return decryptCipher.doFinal(arrB);}/*** 解密字符串** @param xml* 需解密的字符串* @param key* 密钥* @return 解密后的字符串* @throws Exception*/public static String decrypt(String xml, String key) throws Exception {return new String(decrypt(DESPlus.dec.decodeBuffer(xml), key));}/*** 使用默认公钥解密字符串* @param xml 需解密的字符串* @return 解密后的字符串* @throws Exception*/public static String decrypt(String xml) throws Exception {return decrypt(xml, strDefaultKey);}/*** 从指定字符串生成密钥,密钥所需的字节数组长度为8位不足8位时后面补0,超出8位只取前8位** @param arrBTmp* 构成该字符串的字节数组* @return 生成的密钥* @throws ng.Exception*/private Key getKey(byte[] arrBTmp) throws Exception {// 创建一个空的8位字节数组(默认值为0)byte[] arrB = new byte[8];// 将原始字节数组转换为8位for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {arrB[i] = arrBTmp[i];}// 生成密钥Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");return key;}/*** 获取默认密钥* @return*/public static String getDesKey() {return DESPlus.strDefaultKey;}public static void main(String[] args) {try {//测试密匙String key = "BOC_PLFP";//004交易案例String xml = "<?xml version=\"1.0\"encoding=\"UTF-8\"?><ROOT><HEADER><TRANNO>004</TRANNO><BNKNO>17850</B NKNO><COMNO>COM01</COMNO><SN>1109141222222660161</SN></HEADER><BODY>< TRANLOG><APPNO>0000000123</APPNO><NOTATION>客户信息不完整,请补充资料。

C#JavaDES加密解密

C#JavaDES加密解密先来个C#版的:public class DESHelper{/// <summary>/// DES加密算法/// </summary>/// <param name="encryptString">要加密的字符串</param>/// <param name="sKey">加密码Key</param>/// <returns>正确返回加密后的结果,错误返回源字符串</returns>public static string ToDESEncrypt(string encryptString, string sKey){try{byte[] keyBytes = Encoding.UTF8.GetBytes(sKey);byte[] keyIV = keyBytes;byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();// java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这⾥我们默认使⽤ECB⽅式desProvider.Mode = CipherMode.ECB;MemoryStream memStream = new MemoryStream();CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write); crypStream.Write(inputByteArray, 0, inputByteArray.Length);crypStream.FlushFinalBlock();return Convert.ToBase64String(memStream.ToArray());}catch{return encryptString;}}/// <summary>/// DES解密算法/// </summary>/// <param name="decryptString">要解密的字符串</param>/// <param name="sKey">加密Key</param>/// <returns>正确返回加密后的结果,错误返回源字符串</returns>public static string ToDESDecrypt(string decryptString, string sKey){byte[] keyBytes = Encoding.UTF8.GetBytes(sKey);byte[] keyIV = keyBytes;byte[] inputByteArray = Convert.FromBase64String(decryptString);DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();// java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这⾥我们默认使⽤ECB⽅式desProvider.Mode = CipherMode.ECB;MemoryStream memStream = new MemoryStream();CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write); crypStream.Write(inputByteArray, 0, inputByteArray.Length);crypStream.FlushFinalBlock();return Encoding.Default.GetString(memStream.ToArray());}}再来个Java版的public class DESHelper {private byte[] desKey;public DES(String desKey) {this.desKey = desKey.getBytes();}public byte[] desEncrypt(byte[] plainText) throws Exception {SecureRandom sr = new SecureRandom();byte rawKeyData[] = desKey;DESKeySpec dks = new DESKeySpec(rawKeyData);SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks);Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, key, sr);byte data[] = plainText;byte encryptedData[] = cipher.doFinal(data);return encryptedData;}public byte[] desDecrypt(byte[] encryptText) throws Exception {SecureRandom sr = new SecureRandom();byte rawKeyData[] = desKey;DESKeySpec dks = new DESKeySpec(rawKeyData);SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks);Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.DECRYPT_MODE, key, sr);byte encryptedData[] = encryptText;byte decryptedData[] = cipher.doFinal(encryptedData);return decryptedData;}public String encrypt(String input) throws Exception {return base64Encode(desEncrypt(input.getBytes()));}public String decrypt(String input) throws Exception {byte[] result = base64Decode(input);return new String(desDecrypt(result));}public static String base64Encode(byte[] s) {if (s == null)return null;BASE64Encoder b = new sun.misc.BASE64Encoder();return b.encode(s);}public static byte[] base64Decode(String s) throws IOException {if (s == null)return null;BASE64Decoder decoder = new BASE64Decoder();byte[] b = decoder.decodeBuffer(s);return b;}}。

JAVA加密解密DES对称加密算法

JAVA加密解密DES对称加密算法1下⾯⽤DES对称加密算法(设定⼀个密钥,然后对所有的数据进⾏加密)来简单举个例⼦。

23⾸先,⽣成⼀个密钥KEY。

4我把它保存到key.txt中。

这个⽂件就象是⼀把钥匙。

谁拥有它,谁就能解开我们的类⽂件。

代码参考如下:5package com.neusoft.jiami;6import Java.io.File;7import java.io.FileOutputStream;8import java.security.SecureRandom;9import javax.crypto.KeyGenerator;10import javax.crypto.SecretKey;11class Key {12private String keyName;13public Key(String keyName) {14this.keyName = keyName;15 }16public void createKey(String keyName) throws Exception {17// 创建⼀个可信任的随机数源,DES算法需要18 SecureRandom sr = new SecureRandom();19// ⽤DES算法创建⼀个KeyGenerator对象20 KeyGenerator kg = KeyGenerator.getInstance("DES");21// 初始化此密钥⽣成器,使其具有确定的密钥长度22 kg.init(sr);23// ⽣成密匙24 SecretKey key = kg.generateKey();25// 获取密钥数据26byte rawKeyData[] = key.getEncoded();27// 将获取到密钥数据保存到⽂件中,待解密时使⽤28 FileOutputStream fo = new FileOutputStream(new File(keyName));29 fo.write(rawKeyData);30 }31public static void main(String args[]) {32try {33new Key("key.txt");34 } catch (Exception e) {35 e.printStackTrace();36 }37 }38 }39第⼆步,对我们所要进⾏加密的类⽂件进⾏加密。

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