幽蓝色暗房·LoFoTo

追崇单身自由的行摄IT男
一个人,一个背包,一部单反,走起旅行去~


新浪微博:@哥是夕阳控


IT 摄影 旅行 风光摄影 羽毛球 软件工程师


器材:Canon 600D,EF-S 18-135mm,EF 50mm

【交流学习】JAVA安全机制下,实现AES算法和RSA算法对文件进行加密



package SendMailClient;


/**

 * AES加密算法和RSA加密算法的实现已在Java标准库中,客户端程序员不需要再次实现

 * Java SE 1.4的安全机制中添加了javax。crypto。Cipher类,为加密解密提供密码功能

 * javax.crypto.spec.SecretKeySpec类,则在Cipher类下创建密钥对象

 * 详情可参考1.4及以上版本的API

 */


import java.io.*;

import java.security.*;


import javax.crypto.*;


import java.awt.*;

import java.awt.event.*;


import javax.swing.*;


public class FileCipher {

private final static int TEXT_SIZE = 1024;

private final static int TEXT_COLUMNS = 32;

static JFrame frame;

private JFileChooser chooser;

private String filepath = "";

private String cipherfilepath = "";

private String intr = "AES";

public FileCipher() {

frame = new JFrame("附件加密"); //创建加密文件的窗口

frame.setVisible(true);  //窗口可视化

//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口并结束程序

frame.setLocationRelativeTo(null); //窗口居中与屏幕

frame.setLayout(new GridLayout(5,1));

frame.setSize(500,275);

frame.setResizable(false); // 不允许用户控制窗口大小

chooser = new JFileChooser(new File("C:\\")); //文件对话框,用于加载明文件或者密钥文件

JPanel panel_1 = new JPanel();

panel_1.setLayout(new FlowLayout(FlowLayout.LEFT));

JLabel jl_1 = new JLabel("明文件:");

final JTextField jtf_1 = new JTextField(TEXT_SIZE);jtf_1.setColumns(TEXT_COLUMNS); //明文件的路径

jtf_1.setEditable(false); //不允许用户编辑

final JButton look = new JButton("浏览"); // 打开文件对话框,加载明文件

panel_1.add(jl_1);panel_1.add(jtf_1);panel_1.add(look);

frame.add(panel_1,SwingConstants.CENTER);

JPanel panel_2 = new JPanel();

panel_2.setLayout(new FlowLayout(FlowLayout.LEFT));

JLabel jl_2 = new JLabel("密文件:    ");

final JTextField jtf_2 = new JTextField(TEXT_SIZE);jtf_2.setColumns(TEXT_COLUMNS); //加密文件的路径

jtf_2.setEditable(false);

panel_2.add(jl_2);panel_2.add(jtf_2);

frame.add(panel_2);

JPanel panel_3 = new JPanel();

JLabel Introduction = new JLabel("加密算法",SwingConstants.CENTER);

final JRadioButton aes = new JRadioButton("AES"); //单选项AES

final JRadioButton rsa = new JRadioButton("RSA"); //单选项RSA

ButtonGroup group = new ButtonGroup(); 

group.add(aes);group.add(rsa);

panel_3.setLayout(new GridLayout(1,3,5,5));

panel_3.add(Introduction);panel_3.add(aes);panel_3.add(rsa);

frame.add(panel_3);

JPanel panel_4 = new JPanel();

panel_4.setLayout(new FlowLayout(FlowLayout.LEFT));

JLabel jl_3 = new JLabel("密钥:        ");

final JTextField jtf_3 = new JTextField(TEXT_SIZE);jtf_3.setColumns(TEXT_COLUMNS); //密钥文件的路径

jtf_3.setEditable(false);

panel_4.add(jl_3);panel_4.add(jtf_3);

frame.add(panel_4);

JPanel panel_5 = new JPanel();

panel_5.setLayout(new FlowLayout());

final JButton cipher = new JButton("加密");

final JButton cancel = new JButton("取消");

panel_5.add(cipher);panel_5.add(cancel);

frame.add(panel_5);

//文件加密窗口的菜单栏

JMenuBar menu = new JMenuBar();

frame.setJMenuBar(menu);

JMenu key_menu = new JMenu("密钥"); //菜单选项“密钥”

final JMenuItem newkey = new JMenuItem("新建"); //新建密钥文件

final JMenuItem openkey = new JMenuItem("打开"); //打开密钥文件

key_menu.add(newkey);key_menu.add(openkey);

menu.add(key_menu);

/**

 * 打开新建密钥文件窗口

 */

newkey.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

new NewKey();// TODO Auto-generated method stub

}

});

/**

 * 打开密钥文件

 */

openkey.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

open();

jtf_3.setText(filepath);// TODO Auto-generated method stub

}

});

look.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

open();

jtf_1.setText(filepath);

jtf_2.setText(cipherfilepath);// TODO Auto-generated method stub

}

});

/**

 * 加密文件

 */

cipher.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

try {

//用AES加密算法,给文件加密

if(intr.equals("AES")) {

//输入密钥文件

ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(jtf_3.getText()));

Key key = (Key) keyIn.readObject();

keyIn.close();

//输入明文件流

InputStream in = new FileInputStream(jtf_1.getText());

//输出加密文件流

OutputStream out = new FileOutputStream(jtf_2.getText());

//获取AES加密算法的Cipher对象

Cipher cipher = Cipher.getInstance(intr);

//获取cipher的工作模式,ENCRYPT_MODE为加密模式,DECRYPT_MODE为解密模式。

cipher.init(Cipher.ENCRYPT_MODE, key); //加密

//cipher.init(Cipher.DECRYPT_MODE,key) //解密

//加密处理

crypt(in, out, cipher);

//关闭明文件和加密文件

in.close();out.close();

}

//用RSA加密算法,给文件加密

else {

//过程同上,区别在于用AES算法包装RSA算法的公共密钥

KeyGenerator keygen = KeyGenerator.getInstance("AES");

SecureRandom random = new SecureRandom();

keygen.init(random);

SecretKey key = keygen.generateKey();

//打开公开密钥文件

ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(jtf_3.getText()));

Key publicKey = (Key)keyIn.readObject(); //获取公开密钥对象

keyIn.close(); //关闭公开密钥文件

Cipher cipher = Cipher.getInstance(intr);

//获取cipher的工作模式,WRAP_MODE为加密模式,UNWRAP_MODE为解密模式。

cipher.init(Cipher.WRAP_MODE, publicKey);

byte[] wrappedKey = cipher.wrap(key);

DataOutputStream out = new DataOutputStream(new FileOutputStream(jtf_2.getText()));

out.writeInt(wrappedKey.length);

out.write(wrappedKey);

InputStream in = new FileInputStream(jtf_1.getText());

cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, key);

crypt(in, out, cipher);

in.close();out.close();

}

} catch (FileNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (ClassNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (NoSuchAlgorithmException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (NoSuchPaddingException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (InvalidKeyException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}// TODO Auto-generated method stub

catch (IllegalBlockSizeException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

});

cancel.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

frame.dispose();// TODO Auto-generated method stub

}

});

aes.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

intr = "AES";// TODO Auto-generated method stub

}

});

rsa.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

intr = "RSA";// TODO Auto-generated method stub

}

});

}

/*

 * 选择明文件或加密密钥

 */

private void open() {


if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {

File file = chooser.getSelectedFile();

filepath = file.getPath();

cipherfilepath = (file.getParent() + "\\" + "cipher_" + file.getName()).replace("\\\\", "\\");

}

}

/**

 * 文件加密解密过程,AES和RSA共用

 * @param in

 * @param out

 * @param cipher

 */

private void crypt(InputStream in,OutputStream out,Cipher cipher) {

int blockSize = cipher.getBlockSize();

int outputSize = cipher.getOutputSize(blockSize);

byte[] inByte = new byte[blockSize];

byte[] outByte = new byte[outputSize];

int inLenght = 0;

boolean more = true;

while(more) {

try {

inLenght = in.read(inByte);

if(inLenght == blockSize) {

int outLenght = cipher.update(inByte, 0, blockSize, outByte);

out.write(outByte, 0, outLenght);

}

else

more = false;

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ShortBufferException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

try {

if(inLenght > 0)

outByte = cipher.doFinal(inByte, 0, inLenght);

else

outByte = cipher.doFinal();

out.write(outByte);

} catch (IllegalBlockSizeException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (BadPaddingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}

private class NewKey {

private JFrame frame_newKey;

private String name = "AES";

private final static int KEY_SIZE = 512;

NewKey() {

frame_newKey = new JFrame("创建密钥");

frame_newKey.setLocationRelativeTo(null);

frame_newKey.setVisible(true);

frame_newKey.setSize(300, 200);

JPanel panel_u = new JPanel(new FlowLayout(FlowLayout.LEFT));

JComboBox jcbo = new JComboBox("AES RSA".split(" "));

panel_u.add(jcbo);frame_newKey.add(panel_u,BorderLayout.NORTH);

JPanel panel_1 = new JPanel(new FlowLayout());

JLabel keyname = new JLabel("密钥文件名:");

final JTextField name_text = new JTextField(32);name_text.setColumns(16);

panel_1.add(keyname);panel_1.add(name_text);

JPanel panel_2 = new JPanel(new FlowLayout());

JLabel publickey = new JLabel("公共密钥:");

final JTextField publictext = new JTextField(32);publictext.setColumns(16);

JLabel privatekey = new JLabel("私有密钥:");

final JTextField privatetext = new JTextField(32);privatetext.setColumns(16);

panel_2.add(publickey);panel_2.add(publictext);

panel_2.add(privatekey);panel_2.add(privatetext);

final CardLayout cardLayout = new CardLayout();

final JPanel panel_c = new JPanel(cardLayout);

panel_c.add(panel_1,"AES");panel_c.add(panel_2,"RSA");

frame_newKey.add(panel_c,BorderLayout.CENTER);

JPanel panel_d = new JPanel(new FlowLayout());

JButton yes = new JButton("确定");

JButton cancel = new JButton("取消");

panel_d.add(yes);panel_d.add(cancel);

frame_newKey.add(panel_d,BorderLayout.SOUTH);

jcbo.addItemListener(new ItemListener() {

@Override

public void itemStateChanged(ItemEvent e) {

name = (String)e.getItem();

cardLayout.show(panel_c,name);// TODO Auto-generated method stub

}

});

yes.addActionListener(new ActionListener() {


@Override

public void actionPerformed(ActionEvent e) {

try {

//创建AES加密算法的加密解密密钥

if(name.equals("AES")) {

KeyGenerator keygen = KeyGenerator.getInstance(name);

SecureRandom random = new SecureRandom();

keygen.init(random);

SecretKey key = keygen.generateKey();

//储存密钥文件到C盘根目录

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\" + name_text.getText() + ".key"));

out.writeObject(key);

out.close();

frame_newKey.dispose();

}

//创建RSA加密算法的公共密钥和私有密钥

else {

KeyPairGenerator pairgen = KeyPairGenerator.getInstance(name);

SecureRandom random = new SecureRandom();

pairgen.initialize(KEY_SIZE, random);

KeyPair keypair = pairgen.generateKeyPair();

//储存密钥文件到C盘根目录

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\" + publictext.getText() + ".key"));

out.writeObject(keypair.getPublic());

out.close();

out = new ObjectOutputStream(new FileOutputStream("C:\\" + privatetext.getText() + ".key"));

out.writeObject(keypair.getPrivate());

out.close();

frame_newKey.dispose();

}

} catch (NoSuchAlgorithmException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}// TODO Auto-generated method stub

catch (FileNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

});

cancel.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

frame_newKey.dispose();// TODO Auto-generated method stub

}

});

}

}


}


评论 ( 2 )
热度 ( 6 )
  1. ddddf幽蓝色暗房·LoFoTo 转载了此文字
TOP