1.AES加密算法:AES加密算法是由于DES和3DES在应用中出现的问题而提出的高级加密标准。AES算法不是Feistel结构,AES的操作轮数在10-14之间。其中当数据块和密钥都为128位时,轮数为10。随着数据块的密钥长度的增加,操作轮数也会增加,最大值为14。AES的每一轮包括以下4部分
字节替换:用一张称为“S盒子”的固定表来执行字节到字节的替换
行移位置换:行与行之间执行简单的替换
列混淆替换:列中的每一个字节替换成该列所有字节的一个函数
轮密钥加:用当前的数据块与扩充密钥的一部分进行简单的XOR运算
字节替换:
private void subBytes(){
for(int i = 0;i<16;i++)
data[i] = (byte) sbox[data[i]&0xff];
}
private void invSubBytes(){
for(int i = 0;i<16;i++)
data[i] = (byte) isbox[data[i]&0xff];
}
行移位置换:
private void shiftRows(){
byte[] tmp = new byte[4];
int n;
for(int i = 0;i<4;i++){
n = i*4;
tmp[0] = data[n];
tmp[1] = data[n+1];
tmp[2] = data[n+2];
tmp[3] = data[n+3];
data[n] = tmp[i%4];
data[n+1] = tmp[(1+i)%4];
data[n+2] = tmp[(2+i)%4];
data[n+3] = tmp[(3+i)%4];
}
}
privatevoid invShiftRows(){
byte[] tmp = new byte[4];
int n;
for(int i = 0;i<4;i++){
n = i*4;
tmp[0] = data[n];
tmp[1] = data[n+1];
tmp[2] = data[n+2];
tmp[3] = data[n+3];
data[n+i%4] = tmp[0];
data[n+(1+i)%4] = tmp[1];
data[n+(2+i)%4] = tmp[2];
data[n+(3+i)%4] = tmp[3];
}
}
列混淆置换:
private void mixColumns(){
byte[] tmp = new byte[4];
for(inti = 0;i< 4;i++){
tmp[0] = data[i];
tmp[1] = data[i+4];
tmp[2] = data[i+8];
tmp[3] = data[i+12];
data[i] = (byte)(gfmulBy02(tmp[0])^gfmulBy03(tmp[1])^gfmulBy01(tmp[2])^gfmulBy01(tmp[3]));
data[i+4] = (byte)(gfmulBy01(tmp[0])^gfmulBy02(tmp[1])^gfmulBy03(tmp[2])^gfmulBy01(tmp[3]));
data[i+8] = (byte)(gfmulBy01(tmp[0])^gfmulBy01(tmp[1])^gfmulBy02(tmp[2])^gfmulBy03(tmp[3]));
data[i+12] = (byte) (gfmulBy03(tmp[0])^gfmulBy01(tmp[1])^gfmulBy01(tmp[2])^gfmulBy02(tmp[3]));
}
}
private void invMixColumns(){
byte[] tmp = new byte[4];
for(int i = 0;i< 4;i++){
tmp[0] = data[i];
tmp[1] = data[i+4];
tmp[2] = data[i+8];
tmp[3] = data[i+12];
data[i+0] = (byte) (gfmulBy0e(tmp[0]) ^ gfmulBy0b(tmp[1]) ^gfmulBy0d(tmp[2]) ^ gfmulBy09(tmp[3]));
data[i+4] = (byte) (gfmulBy09(tmp[0]) ^ gfmulBy0e(tmp[1]) ^gfmulBy0b(tmp[2]) ^ gfmulBy0d(tmp[3]));
data[i+8] = (byte) (gfmulBy0d(tmp[0]) ^ gfmulBy09(tmp[1]) ^gfmulBy0e(tmp[2]) ^ gfmulBy0b(tmp[3]));
data[i+12] = (byte) (gfmulBy0b(tmp[0]) ^ gfmulBy0d(tmp[1]) ^gfmulBy09(tmp[2]) ^ gfmulBy0e(tmp[3]));
}
}
轮密钥加:
private void addRoundKey(int row){
for(int i = 0;i < 4;i++){
//每轮密钥调度,16字节一组
//循环一次处理一个round的密钥, 一行4字节,4次共16字节
// data[i*4] ^= keys[ row*16+i];
// data[i*4+1] ^= keys[ row*16+1*4+i];
// data[i*4+2] ^= keys[ row*16+2*4+i];
// data[i*4+3] ^= keys[ row*16+3*4+i];
data[i*4] ^= keys[ row*16+4*i];
data[i*4+1] ^= keys[ row*16+4*i+1];
data[i*4+2] ^= keys[ row*16+4*i+2];
data[i*4+3] ^= keys[ row*16+4*i+3];
}
}
2. RSA加密算法
非对称加密具有:
1.使用公开密钥加密的数据,只有使用相应的私有密钥才能解密
2.使用私有密钥加密的数据,也只有相应的公钥才能解密。
RSA算法的安全性是基于分解大整数的困难性,到目前为止,无法找到一个有效的算法来分解两个大质数之积。
RSA算法的原理:
1.选择两个互异的大质数p和q
2.计算出n=pq,z=(p-1)(q-1)
3.选择一个比n小且与z互质的数e
4.找出一个d,使得ed-1能够被z整除。其中,ed=1mod(p-1)(q-1)
因为RSA是一种分组密码系统,所以公开密钥=(n,e),私有密钥=(n,d)算法步骤:
生成密钥对:
public String[] createKey(int keylen) {// 输入密钥长度
String[]output = new String[5]; // 用来存储密钥的e n d p q
try{
KeyPairGeneratorkpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(keylen);// 指定密钥的长度,初始化密钥对生成器
KeyPairkp = kpg.generateKeyPair(); // 生成密钥对
RSAPublicKeypuk = (RSAPublicKey) kp.getPublic();
RSAPrivateCrtKeyprk = (RSAPrivateCrtKey) kp.getPrivate();
BigIntegere = puk.getPublicExponent();
BigIntegern = puk.getModulus();
BigIntegerd = prk.getPrivateExponent();
BigIntegerp = prk.getPrimeP();
BigIntegerq = prk.getPrimeQ();
output[0]= e.toString();
output[1]= n.toString();
output[2]= d.toString();
output[3]= p.toString();
output[4]= q.toString();
}catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSA.class.getName()).log(Level.SEVERE,null, ex);
}
return output;
}
加密:
public String encrypt(String clearText, String eStr,String nStr) {
StringsecretText = new String();
try {
clearText= URLEncoder.encode(clearText,"GBK");
bytetext[]=clearText.getBytes("GBK");//将字符串转换成byte类型数组,实质是各个字符的二进制形式
BigIntegermm=new BigInteger(text);//二进制串转换为一个大整数
clearText= mm.toString();
BigIntegere = new BigInteger(eStr);
BigIntegern = new BigInteger(nStr);
byte[]ptext = clearText.getBytes("UTF8"); // 获取明文的大整数
BigIntegerm = new BigInteger(ptext);
BigIntegerc = m.modPow(e, n);
secretText= c.toString();
} catch(UnsupportedEncodingException ex) {
Logger.getLogger(RSA.class.getName()).log(Level.SEVERE,null, ex);
}
returnsecretText;
}
解密:
public String decrypt(String secretText, String dStr,String nStr) {
StringBufferclearTextBuffer = new StringBuffer();
BigIntegerd = new BigInteger(dStr);// 获取私钥的参数d,n
BigIntegern = new BigInteger(nStr);
BigIntegerc = new BigInteger(secretText);
BigIntegerm = c.modPow(d, n);// 解密明文
byte[] mt= m.toByteArray();// 计算明文对应的字符串并输出
for (inti = 0; i < mt.length; i++) {
clearTextBuffer.append((char)mt[i]);
}
Stringtemp = clearTextBuffer.toString();//temp为明文的字符串形式
BigIntegerb = new BigInteger(temp);//b为明文的BigInteger类型
byte[]mt1=b.toByteArray();
try {
StringclearText = (new String(mt1,"GBK"));
clearText=URLDecoder.decode(clearText,"GBK");
returnclearText;
程序实现代码:
DialogDemo:
package tets;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class DialogDemo extends JFrame implements ActionListener {
private Simple_Dialog simple_dialog;// 声明Simple_Dialog类对象
private Simple_Dialog2 simple_dialog2;
private JTextArea area;// 声明JTextArea变量
String lineSeparator; // 文本域中行之间的分隔符
public DialogDemo() {
super("对称加密与非对称加密");// 调用父类的构造方法
area = new JTextArea(5, 30);// 创建一个能显示5行30个字符的文本域。
area.setEditable(false);// 文本域的状态为不可修改
JMenuBar bar = new JMenuBar();// 创建一个空的菜单栏
getContentPane().add("North", bar);// 将菜单栏添加到容器中
getContentPane().add("Center", new JScrollPane(area));// 将带滚动条的文本添加到容器中
JButton button = new JButton("对称加密AES");// 添加一个按钮,单击按钮弹出对话框
button.setActionCommand("b1");// 设置激发操作事件的命令名称为b1
button.addActionListener(this);// 添加单击侦听事件
JButton button2 = new JButton("非对称加密RSA");// 添加一个按钮,单击按钮弹出对话框
button2.setActionCommand("b2");// 设置激发操作事件的命令名称为b1
button2.addActionListener(this);// 添加单击侦听事件
JPanel panel = new JPanel();// 创建一个JPanel对象
// 将按扭添加到面板中
panel.add(button);
panel.add(button2);
getContentPane().add("South", panel);
// 获取文本域中行之间的分隔符。这里调用了系统的属性
lineSeparator = System.getProperty("line.separator");
this.pack(); // 调整窗体布局大小
}
public void actionPerformed(ActionEvent event) {
// 单击按钮时根据不同的命令名称进行不同的操作
File file;// 声明File对象
if (event.getActionCommand().equals("b1")) {// 如果单击添加按扭
if (simple_dialog == null) {// 弹出一个对话框
simple_dialog = new Simple_Dialog(this, "输入对话框");
}
simple_dialog.setLocationRelativeTo(null);
simple_dialog.setVisible(true);// 设置对话框可见
}
if (event.getActionCommand().equals("b2")) {// 如果单击添加按扭
if (simple_dialog2 == null) {// 弹出一个对话框
simple_dialog2 = new Simple_Dialog2(this, "输入对话框");
}
simple_dialog2.setLocationRelativeTo(null);
simple_dialog2.setVisible(true);// 设置对话框可见
}
}
public void setText(String text,String text1,String text2 ) {
area.append("明文:");
area.append(text + lineSeparator);
area.append("密文:");
area.append(text1 + lineSeparator);
area.append("解密后:");
area.append(text2 + lineSeparator);
// 添加内容到文本域的后面,每次都新起一行。
}
public void cleartext()
{
area.setText("");
}
public static void main(String args[]) {
DialogDemo window = new DialogDemo();
window.setSize(400, 300);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
/**
* 自定义对话框 对话框包括一个label、一个文本框和2个按钮。
*/
class Simple_Dialog2 extends JDialog implements ActionListener {
JTextField text; // 文本框,用于输入字符串
DialogDemo p; // 对话框的父窗体。
JButton comfig; // “确定”按钮
/** 构造函数,参数为父窗体和对话框的标题 */
Simple_Dialog2(JFrame prent_Frame, String title) {
// 调用父类的构造函数,
// 第三个参数用false表示允许激活其他窗体。为true表示不能够激活其他窗体
super(prent_Frame, title, false);
p = (DialogDemo) prent_Frame;
// 添加Label和输入文本框
JPanel pl = new JPanel();
JLabel label = new JLabel("请输入待加密的明文:");
pl.add(label);
text = new JTextField(30);
text.addActionListener(this);
pl.add(text);
getContentPane().add("Center", pl);
// 添加确定和取消按钮
JPanel pl1 = new JPanel();
pl1.setLayout(new FlowLayout(FlowLayout.RIGHT));
JButton cancelButton = new JButton("取 消");
cancelButton.addActionListener(this);
comfig = new JButton("确 定");
comfig.addActionListener(this);
pl1.add(comfig);
pl1.add(cancelButton);
getContentPane().add("South", pl1);
pack(); // 调整对话框布局大小
}
/** 事件处理 */
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if ((source == comfig)) {
// 如果确定按钮被按下,则将文本矿的文本添加到父窗体的文本域中
String s,s1,s2;//处理string输出明文和密文
RSA rsa = new RSA();
String[] str = rsa.createKey(1024);
s1=rsa.RSAstring1(text.getText(), str);
s2=rsa.RSAstring2(text.getText(), str);
p.cleartext();
p.setText(text.getText(),s1,s2);
}
text.selectAll();
setVisible(false); // 隐藏对话框
}
}
class Simple_Dialog extends JDialog implements ActionListener {
JTextField text; // 文本框,用于输入字符串
DialogDemo p; // 对话框的父窗体。
JButton comfig; // “确定”按钮
/** 构造函数,参数为父窗体和对话框的标题 */
Simple_Dialog(JFrame prent_Frame, String title) {
// 调用父类的构造函数,
// 第三个参数用false表示允许激活其他窗体。为true表示不能够激活其他窗体
super(prent_Frame, title, false);
p = (DialogDemo) prent_Frame;
// 添加Label和输入文本框
JPanel pl = new JPanel();
JLabel label = new JLabel("请输入待加密的明文:");
pl.add(label);
text = new JTextField(30);
text.addActionListener(this);
pl.add(text);
getContentPane().add("Center", pl);
// 添加确定和取消按钮
JPanel pl1 = new JPanel();
pl1.setLayout(new FlowLayout(FlowLayout.RIGHT));
JButton cancelButton = new JButton("取 消");
cancelButton.addActionListener(this);
comfig = new JButton("确 定");
comfig.addActionListener(this);
pl1.add(comfig);
pl1.add(cancelButton);
getContentPane().add("South", pl1);
pack(); // 调整对话框布局大小
}
/** 事件处理 */
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if ((source == comfig)) {
// 如果确定按钮被按下,则将文本矿的文本添加到父窗体的文本域中
String s,s1,s2;//处理string输出明文和密文
byte[] keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17 };
Aes aes = new Aes(tets.Aes.KeySize.Bits192, keys);
s1=aes.aestring1(text.getText());
s2=aes.aestring2(text.getText());
p.cleartext();
p.setText(text.getText(),s1,s2);
}
text.selectAll();
setVisible(false); // 隐藏对话框
}
}
RSA:
package tets;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RSA {
/**
* 创建密钥对生成器,指定加密和解密算法为RSA
* @param keylen
* @return
*/
public String[] createKey(int keylen) {// 输入密钥长度
String[] output = new String[5]; // 用来存储密钥的e n d p q
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(keylen); // 指定密钥的长度,初始化密钥对生成器
KeyPair kp = kpg.generateKeyPair(); // 生成密钥对
RSAPublicKey puk = (RSAPublicKey) kp.getPublic();
RSAPrivateCrtKey prk = (RSAPrivateCrtKey) kp.getPrivate();
BigInteger e = puk.getPublicExponent();
BigInteger n = puk.getModulus();
BigInteger d = prk.getPrivateExponent();
BigInteger p = prk.getPrimeP();
BigInteger q = prk.getPrimeQ();
output[0] = e.toString();
output[1] = n.toString();
output[2] = d.toString();
output[3] = p.toString();
output[4] = q.toString();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSA.class.getName()).log(Level.SEVERE, null, ex);
}
return output;
}
/**
* 加密在RSA公钥中包含有两个整数信息:e和n。对于明文数字m,计算密文的公式是m的e次方再与n求模。
* @param clearText 明文
* @param eStr 公钥
* @param nStr
* @return
*/
public String encrypt(String clearText, String eStr, String nStr) {
String secretText = new String();
try {
clearText = URLEncoder.encode(clearText,"GBK");
byte text[]=clearText.getBytes("GBK");//将字符串转换成byte类型数组,实质是各个字符的二进制形式
BigInteger mm=new BigInteger(text);//二进制串转换为一个大整数
clearText = mm.toString();
BigInteger e = new BigInteger(eStr);
BigInteger n = new BigInteger(nStr);
byte[] ptext = clearText.getBytes("UTF8"); // 获取明文的大整数
BigInteger m = new BigInteger(ptext);
BigInteger c = m.modPow(e, n);
secretText = c.toString();
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(RSA.class.getName()).log(Level.SEVERE, null, ex);
}
return secretText;
}
/**
* 解密
* @param secretText 密文
* @param dStr 私钥
* @param nStr
* @return
*/
public String decrypt(String secretText, String dStr, String nStr) {
StringBuffer clearTextBuffer = new StringBuffer();
BigInteger d = new BigInteger(dStr);// 获取私钥的参数d,n
BigInteger n = new BigInteger(nStr);
BigInteger c = new BigInteger(secretText);
BigInteger m = c.modPow(d, n);// 解密明文
byte[] mt = m.toByteArray();// 计算明文对应的字符串并输出
for (int i = 0; i < mt.length; i++) {
clearTextBuffer.append((char) mt[i]);
}
String temp = clearTextBuffer.toString();//temp为明文的字符串形式
BigInteger b = new BigInteger(temp);//b为明文的BigInteger类型
byte[] mt1=b.toByteArray();
try {
String clearText = (new String(mt1,"GBK"));
clearText=URLDecoder.decode(clearText,"GBK");
return clearText;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
String RSAstring1(String text,String []str)
{
String secretText = this.encrypt(text, str[0], str[1]);
return secretText;
}
String RSAstring2(String text,String []str)
{
String secretText = this.encrypt(text, str[0], str[1]);
String m=this.decrypt(secretText, str[2], str[1]);
return m;
}
public static void main(String[] args) {
RSA rsa = new RSA();
String[] str = rsa.createKey(1024);
String clearText = "123abc测试";
String secretText = rsa.encrypt(clearText, str[0], str[1]);
System.out.println("明文是:" + clearText);
System.out.println("密文是:" + secretText);
System.out.println("解密后的明文是:" + rsa.decrypt(secretText, str[2], str[1]));
//System.out.println()
}
}
package tets;
public class Aes {
public enum KeySize{
Bits128(4,10),Bits192(6,12),Bits256(8,14);
/**以字为单位的种子密钥长度,16bytes=1word=128bits*/
private int nk;
/**轮密钥的次数*/
private int nr;
private KeySize(int nk,int nr){
this.nk = nk;
this.nr = nr;
}
}
private char[][] rcon ={
{0x00,0x00,0x00,0x00},
{0x01,0x00,0x00,0x00},
{0x02,0x00,0x00,0x00},
{0x04,0x00,0x00,0x00},
{0x08,0x00,0x00,0x00},
{0x10,0x00,0x00,0x00},
{0x20,0x00,0x00,0x00},
{0x40,0x00,0x00,0x00},
{0x80,0x00,0x00,0x00},
{0x1b,0x00,0x00,0x00},
{0x36,0x00,0x00,0x00}
};
char sbox[] =
{
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0x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4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
};
/**以字为单位的种子密钥长度,16bytes=1word=128bits*/
private int nk;
/**轮密钥的次数*/
private int nr;
/**以字节为单位的明文长度,固定值16字节*/
private static final int nb = 16;
/**密钥轮值表数组*/
private byte[] keys;
private byte[] data;
public Aes(KeySize keySize,byte[] keys){
setNkNr(keySize);
keyExpansion(keys);
}
public Aes()
{
byte[] keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17 };
Aes aes = new Aes(KeySize.Bits192, keys);
}
private void setNkNr(KeySize keySize){
nk = keySize.nk;
nr = keySize.nr;
}
/**
* 密钥扩展,创建密钥调度表
* @param keys 种子密钥
*/
private void keyExpansion(byte[] inkeys){
if(inkeys == null ||
(inkeys.length != 16 && inkeys.length != 24 && inkeys.length != 32))
throw new IllegalArgumentException("keys length out of range{16,24,32}");
keys = new byte[nb*(nr+1)];//轮密钥次数nr,再加上轮值之前的1次addRoundKey预处理
System.arraycopy(inkeys, 0, keys, 0, inkeys.length);
int totalRow = nb*(nr+1)/4;
byte[] tmp = new byte[4];
int index = 0;
for(int row = nk;row < totalRow;row++){
//循环一次处理一个round的密钥, 一行4字节
index = 4*(row - 1);
tmp[0] = keys[index];
tmp[1] = keys[index+1];
tmp[2] = keys[index+2];
tmp[3] = keys[index+3];
if(row%nk == 0)
tmp = xorRcon(row, subWord(rotWord(tmp)));
else if(nk == 8 && (row % nk == 4)){
tmp = subWord(tmp);
}
keys[row*4] = (byte) (keys[(row-nk)*4] ^ tmp[0]);
keys[row*4+1] = (byte) (keys[(row-nk)*4+1] ^ tmp[1]);
keys[row*4+2] = (byte) (keys[(row-nk)*4+2] ^ tmp[2]);
keys[row*4+3] = (byte) (keys[(row-nk)*4+3] ^ tmp[3]);
}
}
private void addRoundKey(int row){
for(int i = 0;i < 4;i++){
//每轮密钥调度,16字节一组
//循环一次处理一个round的密钥, 一行4字节,4次共16字节
// data[i*4] ^= keys[ row*16+i];
// data[i*4+1] ^= keys[ row*16+1*4+i];
// data[i*4+2] ^= keys[ row*16+2*4+i];
// data[i*4+3] ^= keys[ row*16+3*4+i];
data[i*4] ^= keys[ row*16+4*i];
data[i*4+1] ^= keys[ row*16+4*i+1];
data[i*4+2] ^= keys[ row*16+4*i+2];
data[i*4+3] ^= keys[ row*16+4*i+3];
}
}
/**
* 进行s-box非线性变换
*/
private void subBytes(){
for(int i = 0;i<16;i++)
data[i] = (byte) sbox[data[i]&0xff];
}
/**
* 进行is-box非线性变换
*/
private void invSubBytes(){
for(int i = 0;i<16;i++)
data[i] = (byte) isbox[data[i]&0xff];
}
/**
* 4x4矩阵(x,y)数组,每行循环左移x个字节
*/
private void shiftRows(){
byte[] tmp = new byte[4];
int n;
for(int i = 0;i<4;i++){
n = i*4;
tmp[0] = data[n];
tmp[1] = data[n+1];
tmp[2] = data[n+2];
tmp[3] = data[n+3];
data[n] = tmp[i%4];
data[n+1] = tmp[(1+i)%4];
data[n+2] = tmp[(2+i)%4];
data[n+3] = tmp[(3+i)%4];
}
}
/**
* 4x4矩阵(x,y)数组,每行循环右移x个字节
*/
private void invShiftRows(){
byte[] tmp = new byte[4];
int n;
for(int i = 0;i<4;i++){
n = i*4;
tmp[0] = data[n];
tmp[1] = data[n+1];
tmp[2] = data[n+2];
tmp[3] = data[n+3];
data[n+i%4] = tmp[0];
data[n+(1+i)%4] = tmp[1];
data[n+(2+i)%4] = tmp[2];
data[n+(3+i)%4] = tmp[3];
}
}
/**
* 按列混合
*/
private void mixColumns(){
byte[] tmp = new byte[4];
for(int i = 0;i< 4;i++){
tmp[0] = data[i];
tmp[1] = data[i+4];
tmp[2] = data[i+8];
tmp[3] = data[i+12];
data[i] = (byte) (gfmulBy02(tmp[0])^gfmulBy03(tmp[1])^gfmulBy01(tmp[2])^gfmulBy01(tmp[3]));
data[i+4] = (byte) (gfmulBy01(tmp[0])^gfmulBy02(tmp[1])^gfmulBy03(tmp[2])^gfmulBy01(tmp[3]));
data[i+8] = (byte) (gfmulBy01(tmp[0])^gfmulBy01(tmp[1])^gfmulBy02(tmp[2])^gfmulBy03(tmp[3]));
data[i+12] = (byte) (gfmulBy03(tmp[0])^gfmulBy01(tmp[1])^gfmulBy01(tmp[2])^gfmulBy02(tmp[3]));
}
}
/**
* 按列逆混合
*/
private void invMixColumns(){
byte[] tmp = new byte[4];
for(int i = 0;i< 4;i++){
tmp[0] = data[i];
tmp[1] = data[i+4];
tmp[2] = data[i+8];
tmp[3] = data[i+12];
data[i+0] = (byte) (gfmulBy0e(tmp[0]) ^ gfmulBy0b(tmp[1]) ^ gfmulBy0d(tmp[2]) ^ gfmulBy09(tmp[3]));
data[i+4] = (byte) (gfmulBy09(tmp[0]) ^ gfmulBy0e(tmp[1]) ^ gfmulBy0b(tmp[2]) ^ gfmulBy0d(tmp[3]));
data[i+8] = (byte) (gfmulBy0d(tmp[0]) ^ gfmulBy09(tmp[1]) ^ gfmulBy0e(tmp[2]) ^ gfmulBy0b(tmp[3]));
data[i+12] = (byte) (gfmulBy0b(tmp[0]) ^ gfmulBy0d(tmp[1]) ^ gfmulBy09(tmp[2]) ^ gfmulBy0e(tmp[3]));
}
}
private byte gfmulBy01(byte value){
return value;
}
private byte gfmulBy02(byte value){
if((int)value > 0x80)
value = (byte)((value<<1)^0x1b);
else
value = (byte)(value<<1);
return value;
}
private byte gfmulBy03(byte value){
return (byte) (gfmulBy01(value)^gfmulBy02(value));
}
private byte gfmulBy09(byte value){
return (byte) (gfmulBy01(value)^gfmulBy02(gfmulBy02(gfmulBy02(value))));
}
private byte gfmulBy0b(byte value){
return (byte) (gfmulBy01(value)^gfmulBy02(value)^gfmulBy02(gfmulBy02(gfmulBy02(value))));
}
private byte gfmulBy0d(byte value){
return (byte) (gfmulBy01(value)^gfmulBy02(gfmulBy02(value))^gfmulBy02(gfmulBy02(gfmulBy02(value))));
}
private byte gfmulBy0e(byte value){
return (byte) (gfmulBy02(value)^gfmulBy02(gfmulBy02(value))^gfmulBy02(gfmulBy02(gfmulBy02(value))));
}
private byte[] rotWord(byte[] word){
return new byte[]{word[1],word[2],word[3],word[0]};
}
private byte[] subWord(byte[] word){
return new byte[]{(byte) sbox[word[0]&0xff],(byte) sbox[word[1]&0xff],
(byte) sbox[word[2]&0xff],(byte) sbox[word[3]&0xff]};
}
private byte[] xorRcon(int row,byte[] word){
byte[] ret = new byte[4];
ret[0] = (byte) (word[0] ^ rcon[row/nk][0]);
ret[1] = (byte) (word[1] ^ rcon[row/nk][1]);
ret[2] = (byte) (word[2] ^ rcon[row/nk][2]);
ret[3] = (byte) (word[3] ^ rcon[row/nk][3]);
return ret;
}
/**
* 加密
* @param plainText
* @return
*/
public byte[] cipher(byte[] plainText){
if(plainText == null || plainText.length == 0)
throw new IllegalArgumentException("plainText can not be null");
data = new byte[16];
System.arraycopy(plainText, 0, data, 0, plainText.length);
addRoundKey(0);//预处理一次
for(int row = 1;row < nr;row++){
subBytes();
shiftRows();
mixColumns();
addRoundKey(row);
}
//最后一轮不需要执行mixColumns
subBytes();
shiftRows();
addRoundKey(nr);
return data;
}
/**
* 解密
* @param cipherText
* @return
*/
public byte[] invCipher(byte[] cipherText){
if(cipherText == null || cipherText.length == 0)
throw new IllegalArgumentException("cipherText can not be null");
data = new byte[16];
System.arraycopy(cipherText, 0, data, 0, cipherText.length);
addRoundKey(nr);//预处理一次
for(int row = nr-1;row > 0;row--){
invShiftRows();
invSubBytes();
addRoundKey(row);
invMixColumns();
}
//最后一轮不需要执行mixColumns
invShiftRows();
invSubBytes();
addRoundKey(0);
// print();
return data;
}
String aestring1(String text)
{
byte[] cipherText = this.cipher(text.getBytes());
String s= new String(cipherText);
return s;
}
String aestring2(String text)
{
byte[] cipherText = this.cipher(text.getBytes());
byte[] ret = this.invCipher(cipherText);
String s= new String(ret);
return s;
}
public static void main(String[] args){
byte[] keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17 };
Aes aes = new Aes(KeySize.Bits192, keys);
//--------加密-------------------------
String plainText = "中文";
byte[] cipherText = aes.cipher(plainText.getBytes());
//String val2 = new String(cipherText);
//System.out.println("cipherText: "+val2);
System.out.println("plainText: "+plainText);
StringBuffer m = new StringBuffer();
for(int i = 0;i< 16;i++){
if((cipherText[i]&0xff) > 0x0f)
m.append(String.format("%x", cipherText[i]));
else
m.append(String.format("0%x", cipherText[i]));
m.append(" ");
}
System.out.println("cipherText:"+m);
//--------解密-------------------------
byte[] ret = aes.invCipher(cipherText);
String val = new String(ret);
System.out.println("invCipher cipherText : "+val);
}
}
运行截图:
AES:
RSA:
相关连接:
非对称加密介绍
对称加密介绍
对称加密算法介绍
非对称加密介绍