开发十年,就只剩下这套架构体系了! >>>
第6篇 Java安全与Applet应用篇
第20章 Java安全
20.1 Java对称加密
实例531 使用BASE64加密
public static String encryptBASE64(byte[] data) {
//加密数据
return (new BASE64Encoder()).encodeBuffer(data);
}
/**
* 解密
*
* @param data
* @return
* @throws IOException
*/
public static byte[] decryptBASE64(String data) throws IOException {
//解密数据
return (new BASE64Decoder()).decodeBuffer(data);
}
public static void main(String[] avg) throws IOException {
String data = "明日科技";
System.out.println("加密前:" + data);
String data1 = BothBase64.encryptBASE64(data.getBytes());
System.out.println("加密后:" + data1);
byte[] data2 = BothBase64.decryptBASE64(data1);
System.out.println("解密后:" + new String(data2));
}
实例532 使用BASE64解密
public static String encryptBASE64(byte[] data) {
//加密数据
return (new BASE64Encoder()).encodeBuffer(data);
}
/**
* 解密
*
* @param data
* @return
* @throws IOException
*/
public static byte[] decryptBASE64(String data) throws IOException {
//解密数据
return (new BASE64Decoder()).decodeBuffer(data);
}
public static void main(String[] avg) throws IOException {
String data = "明日科技";
System.out.println("加密前:" + data);
String data1 = BothBase64.encryptBASE64(data.getBytes());
System.out.println("加密后:" + data1);
byte[] data2 = BothBase64.decryptBASE64(data1);
System.out.println("解密后:" + new String(data2));
}
实例533 生成DES的密钥
String algorithm = "DES";
// key保存的文件名称
String keyFile = "keyData.dat";
// 数据保存的文件名称
String dataFile = "fileData.dat";
public BothDESFile() {
try {
initKey();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 生成密钥数据,保存到文件中
*
* @throws NoSuchAlgorithmException
*/
private void initKey() throws NoSuchAlgorithmException {
// 产生一个随机数源
SecureRandom secureRandom = new SecureRandom();
// 为DES算法生成一个KeyGenerator
KeyGenerator generator = KeyGenerator.getInstance(algorithm);
generator.init(secureRandom);
SecretKey key = generator.generateKey();
//生成密钥数据,保存到文件中
writeFile(key.getEncoded(), keyFile);
}
/**
* 转化密钥成Key进行加密解密
*
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private Key toKey() throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException {
byte[] key = readFile(keyFile);
DESKeySpec keySpec = new DESKeySpec(key);
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = factory.generateSecret(keySpec);
return secretKey;
}
/**
* 加密,把加密数据保存在文件中
*
* @param data
* @param key
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public void encrypt(byte[] data) throws InvalidKeyException,
NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey();
// 使用Cipher实际完成加密操作
Cipher cipher = Cipher.getInstance(algorithm);
// 使用密钥初始化Cipher
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] f = cipher.doFinal(data);
writeFile(f, dataFile);
}
/**
* 解密把数据从文件中取出来在解密
*
* @param data
* @param key
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public String decrypt() throws InvalidKeyException,
NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey();
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] f = readFile(dataFile);
return new String(cipher.doFinal(f));
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
BothDESFile bothDESFile = new BothDESFile();
String data = "明日科技";
// 数据加密
System.out.println("加密前:" + data);
bothDESFile.encrypt(data.getBytes());
// 数据解密
String b = bothDESFile.decrypt();
System.out.println("解密后:" + b);
}
实例534 使用DES加密
String algorithm = "DES";
// key保存的文件名称
String keyFile = "keyData.dat";
// 数据保存的文件名称
String dataFile = "fileData.dat";
public BothDESFile() {
try {
initKey();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 生成密钥数据,保存到文件中
*
* @throws NoSuchAlgorithmException
*/
private void initKey() throws NoSuchAlgorithmException {
// 产生一个随机数源
SecureRandom secureRandom = new SecureRandom();
// 为DES算法生成一个KeyGenerator
KeyGenerator generator = KeyGenerator.getInstance(algorithm);
generator.init(secureRandom);
SecretKey key = generator.generateKey();
//生成密钥数据,保存到文件中
writeFile(key.getEncoded(), keyFile);
}
/**
* 转化密钥成Key进行加密解密
*
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private Key toKey() throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException {
byte[] key = readFile(keyFile);
DESKeySpec keySpec = new DESKeySpec(key);
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = factory.generateSecret(keySpec);
return secretKey;
}
/**
* 加密,把加密数据保存在文件中
*
* @param data
* @param key
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public void encrypt(byte[] data) throws InvalidKeyException,
NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey();
// 使用Cipher实际完成加密操作
Cipher cipher = Cipher.getInstance(algorithm);
// 使用密钥初始化Cipher
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] f = cipher.doFinal(data);
writeFile(f, dataFile);
}
/**
* 解密把数据从文件中取出来在解密
*
* @param data
* @param key
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public String decrypt() throws InvalidKeyException,
NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey();
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] f = readFile(dataFile);
return new String(cipher.doFinal(f));
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
BothDESFile bothDESFile = new BothDESFile();
String data = "明日科技";
// 数据加密
System.out.println("加密前:" + data);
bothDESFile.encrypt(data.getBytes());
// 数据解密
String b = bothDESFile.decrypt();
System.out.println("解密后:" + b);
}
实例535 使用DES解密
String algorithm = "DES";
// key保存的文件名称
String keyFile = "keyData.dat";
// 数据保存的文件名称
String dataFile = "fileData.dat";
public BothDESFile() {
try {
initKey();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 生成密钥数据,保存到文件中
*
* @throws NoSuchAlgorithmException
*/
private void initKey() throws NoSuchAlgorithmException {
// 产生一个随机数源
SecureRandom secureRandom = new SecureRandom();
// 为DES算法生成一个KeyGenerator
KeyGenerator generator = KeyGenerator.getInstance(algorithm);
generator.init(secureRandom);
SecretKey key = generator.generateKey();
//生成密钥数据,保存到文件中
writeFile(key.getEncoded(), keyFile);
}
/**
* 转化密钥成Key进行加密解密
*
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private Key toKey() throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException {
byte[] key = readFile(keyFile);
DESKeySpec keySpec = new DESKeySpec(key);
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = factory.generateSecret(keySpec);
return secretKey;
}
/**
* 加密,把加密数据保存在文件中
*
* @param data
* @param key
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public void encrypt(byte[] data) throws InvalidKeyException,
NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey();
// 使用Cipher实际完成加密操作
Cipher cipher = Cipher.getInstance(algorithm);
// 使用密钥初始化Cipher
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] f = cipher.doFinal(data);
writeFile(f, dataFile);
}
/**
* 解密把数据从文件中取出来在解密
*
* @param data
* @param key
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public String decrypt() throws InvalidKeyException,
NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey();
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] f = readFile(dataFile);
return new String(cipher.doFinal(f));
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
BothDESFile bothDESFile = new BothDESFile();
String data = "明日科技";
// 数据加密
System.out.println("加密前:" + data);
bothDESFile.encrypt(data.getBytes());
// 数据解密
String b = bothDESFile.decrypt();
System.out.println("解密后:" + b);
}
实例536 PBE的盐值
String algorithm = "PBEWithMD5AndDES";
String saltFile = "saltData.dat";
String dataFile = "fileData.dat";
/**
* 获取盐值
*
* @return
* @throws Exception
*/
public void initSalt() {
byte[] salt = new byte[8];
Random random = new Random();
//生成随机数
random.nextBytes(salt);
//保存盐值
writeFile(salt, saltFile);
}
/**
* 获取钥匙
*
* @param password
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private Key toKey(String password) throws NoSuchAlgorithmException,
InvalidKeySpecException {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = keyFactory.generateSecret(keySpec);
return secretKey;
}
/**
* 加密
*
* @param data
* @param password
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public void encrypt(byte[] data, String password)
throws NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey(password);
byte[] salt = readFile(saltFile);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
writeFile(cipher.doFinal(data), dataFile);
}
/**
* 解密
*
* @param data
* @param password
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public String decrypt(String password) throws NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
Key key = toKey(password);
byte[] salt = readFile(saltFile);
byte[] data = readFile(dataFile);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
return new String(cipher.doFinal(data));
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) {
BothPBEFile bothPBEFile = new BothPBEFile();
String data = "明日科技";
String password = "123456";
System.out.println("加密前:" + data);
try {
bothPBEFile.initSalt();
bothPBEFile.encrypt(data.getBytes(), password);
String tdata = bothPBEFile.decrypt(password);
System.out.println("解密后:" + tdata);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
实例537 生成PBE的密钥
String algorithm = "PBEWithMD5AndDES";
String saltFile = "saltData.dat";
String dataFile = "fileData.dat";
/**
* 获取盐值
*
* @return
* @throws Exception
*/
public void initSalt() {
byte[] salt = new byte[8];
Random random = new Random();
//生成随机数
random.nextBytes(salt);
//保存盐值
writeFile(salt, saltFile);
}
/**
* 获取钥匙
*
* @param password
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private Key toKey(String password) throws NoSuchAlgorithmException,
InvalidKeySpecException {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = keyFactory.generateSecret(keySpec);
return secretKey;
}
/**
* 加密
*
* @param data
* @param password
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public void encrypt(byte[] data, String password)
throws NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey(password);
byte[] salt = readFile(saltFile);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
writeFile(cipher.doFinal(data), dataFile);
}
/**
* 解密
*
* @param data
* @param password
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public String decrypt(String password) throws NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
Key key = toKey(password);
byte[] salt = readFile(saltFile);
byte[] data = readFile(dataFile);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
return new String(cipher.doFinal(data));
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) {
BothPBEFile bothPBEFile = new BothPBEFile();
String data = "明日科技";
String password = "123456";
System.out.println("加密前:" + data);
try {
bothPBEFile.initSalt();
bothPBEFile.encrypt(data.getBytes(), password);
String tdata = bothPBEFile.decrypt(password);
System.out.println("解密后:" + tdata);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
实例538 使用PBE加密
String algorithm = "PBEWithMD5AndDES";
String saltFile = "saltData.dat";
String dataFile = "fileData.dat";
/**
* 获取盐值
*
* @return
* @throws Exception
*/
public void initSalt() {
byte[] salt = new byte[8];
Random random = new Random();
//生成随机数
random.nextBytes(salt);
//保存盐值
writeFile(salt, saltFile);
}
/**
* 获取钥匙
*
* @param password
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private Key toKey(String password) throws NoSuchAlgorithmException,
InvalidKeySpecException {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = keyFactory.generateSecret(keySpec);
return secretKey;
}
/**
* 加密
*
* @param data
* @param password
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public void encrypt(byte[] data, String password)
throws NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey(password);
byte[] salt = readFile(saltFile);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
writeFile(cipher.doFinal(data), dataFile);
}
/**
* 解密
*
* @param data
* @param password
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public String decrypt(String password) throws NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
Key key = toKey(password);
byte[] salt = readFile(saltFile);
byte[] data = readFile(dataFile);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
return new String(cipher.doFinal(data));
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) {
BothPBEFile bothPBEFile = new BothPBEFile();
String data = "明日科技";
String password = "123456";
System.out.println("加密前:" + data);
try {
bothPBEFile.initSalt();
bothPBEFile.encrypt(data.getBytes(), password);
String tdata = bothPBEFile.decrypt(password);
System.out.println("解密后:" + tdata);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
实例539 使用PBE解密
String algorithm = "PBEWithMD5AndDES";
String saltFile = "saltData.dat";
String dataFile = "fileData.dat";
/**
* 获取盐值
*
* @return
* @throws Exception
*/
public void initSalt() {
byte[] salt = new byte[8];
Random random = new Random();
//生成随机数
random.nextBytes(salt);
//保存盐值
writeFile(salt, saltFile);
}
/**
* 获取钥匙
*
* @param password
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private Key toKey(String password) throws NoSuchAlgorithmException,
InvalidKeySpecException {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = keyFactory.generateSecret(keySpec);
return secretKey;
}
/**
* 加密
*
* @param data
* @param password
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public void encrypt(byte[] data, String password)
throws NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
Key key = toKey(password);
byte[] salt = readFile(saltFile);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
writeFile(cipher.doFinal(data), dataFile);
}
/**
* 解密
*
* @param data
* @param password
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public String decrypt(String password) throws NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
Key key = toKey(password);
byte[] salt = readFile(saltFile);
byte[] data = readFile(dataFile);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
return new String(cipher.doFinal(data));
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) {
BothPBEFile bothPBEFile = new BothPBEFile();
String data = "明日科技";
String password = "123456";
System.out.println("加密前:" + data);
try {
bothPBEFile.initSalt();
bothPBEFile.encrypt(data.getBytes(), password);
String tdata = bothPBEFile.decrypt(password);
System.out.println("解密后:" + tdata);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
20.2 Java非对称加密
实例540 生成RSA密钥对
BothRSAClientFile.java
private String keyAlgorithm = "RSA";
private String singAlgorithm = "MD5withRSA";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 签名文件
private String signdataFile = "fileSignData.dat";
// 公钥文件
private String publickeyFile = "keyPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 校验数字签名
*
* @return 校验成功返回true 失败返回false
*/
public boolean verifySign() {
byte[] data = readFile(serverdataFile);
byte[] publicKey = readFile(publickeyFile);
byte[] sign = readFile(signdataFile);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = null;
PublicKey pubKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
pubKey = keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 验证签名是否正常
Signature signature = Signature.getInstance(singAlgorithm);
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(sign);
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
* 用公钥解密
*
* @return
*/
public byte[] decryptByPublicKey() {
byte[] data = readFile(serverdataFile);
byte[] key = readFile(publickeyFile);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key publicKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据解密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 用公钥加密
*/
public void encryptByPublicKey(byte[] data) {
byte[] key = readFile(publickeyFile);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key publicKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据加密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
writeFile(cipher.doFinal(data), clientdataFile);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchPaddingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] arg) {
BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
String cdata = "服务端你好,这里是客户端";
bothRSAClientFile.encryptByPublicKey(cdata.getBytes());
byte [] cdata1 = bothRSAServerFile.decryptByPrivateKey();
System.out.println("Client原始数据:"+cdata);
System.out.println("Servet解密数据:"+new String (cdata1));
}
BothRSAServerFile.java
private String keyAlgorithm = "RSA";
private String singAlgorithm = "MD5withRSA";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 签名文件
private String signdataFile = "fileSignData.dat";
// 私钥文件
private String privatekeyFile = "keyPrivateData.dat";
// 公钥文件
private String publickeyFile = "keyPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成密钥对
*/
public void generateKeyFile() {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = keyPair.getPublic();
writeFile(publicKey.getEncoded(), publickeyFile);
// 私钥
PrivateKey privateKey = keyPair.getPrivate();
writeFile(privateKey.getEncoded(), privatekeyFile);
}
/**
* 用私钥加密
*
* @param data
* @return
*/
public void encryptByPrivateKey(byte[] data) {
// 取得私钥
byte[] key = readFile(privatekeyFile);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key privateKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据加密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
writeFile(cipher.doFinal(data), serverdataFile);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用私钥对信息生成数字签名
*
* @param data
* 加密数据
* @param privateKey
* 私钥
*
* @return
* @throws Exception
*/
public void generateSign() {
byte[] privateKey = readFile(privatekeyFile);
byte[] serverData = readFile(serverdataFile);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = null;
PrivateKey priKey = null;
try {
//生成私钥
keyFactory = KeyFactory.getInstance(keyAlgorithm);
priKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//生成数字签名
Signature signature = Signature.getInstance(singAlgorithm);
signature.initSign(priKey);
signature.update(serverData);
writeFile(signature.sign(), signdataFile);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public byte[] decryptByPrivateKey() {
byte[] data = readFile(clientdataFile);
byte[] key = readFile(privatekeyFile);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key privateKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] arg) {
String data = "客户端你好,我是服务端";
// 服务端操作
BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
// 生成密钥对
bothRSAServerFile.generateKeyFile();
// 加密明文
bothRSAServerFile.encryptByPrivateKey(data.getBytes());
// 生成签名
bothRSAServerFile.generateSign();
// 客户端操作
BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
byte[] data1 =null;
if(bothRSAClientFile.verifySign()){
data1= bothRSAClientFile.decryptByPublicKey();
}
System.out.println("Servet原始数据:"+data);
System.out.println("Client解密数据:"+new String (data1));
}
实例541 使用RSA的签名
BothRSAClientFile.java
private String keyAlgorithm = "RSA";
private String singAlgorithm = "MD5withRSA";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 签名文件
private String signdataFile = "fileSignData.dat";
// 公钥文件
private String publickeyFile = "keyPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 校验数字签名
*
* @return 校验成功返回true 失败返回false
*/
public boolean verifySign() {
byte[] data = readFile(serverdataFile);
byte[] publicKey = readFile(publickeyFile);
byte[] sign = readFile(signdataFile);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = null;
PublicKey pubKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
pubKey = keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 验证签名是否正常
Signature signature = Signature.getInstance(singAlgorithm);
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(sign);
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
* 用公钥解密
*
* @return
*/
public byte[] decryptByPublicKey() {
byte[] data = readFile(serverdataFile);
byte[] key = readFile(publickeyFile);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key publicKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据解密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 用公钥加密
*/
public void encryptByPublicKey(byte[] data) {
byte[] key = readFile(publickeyFile);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key publicKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据加密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
writeFile(cipher.doFinal(data), clientdataFile);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchPaddingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] arg) {
BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
String cdata = "服务端你好,这里是客户端";
bothRSAClientFile.encryptByPublicKey(cdata.getBytes());
byte [] cdata1 = bothRSAServerFile.decryptByPrivateKey();
System.out.println("Client原始数据:"+cdata);
System.out.println("Servet解密数据:"+new String (cdata1));
}
BothRSAServerFile.java
private String keyAlgorithm = "RSA";
private String singAlgorithm = "MD5withRSA";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 签名文件
private String signdataFile = "fileSignData.dat";
// 私钥文件
private String privatekeyFile = "keyPrivateData.dat";
// 公钥文件
private String publickeyFile = "keyPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成密钥对
*/
public void generateKeyFile() {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = keyPair.getPublic();
writeFile(publicKey.getEncoded(), publickeyFile);
// 私钥
PrivateKey privateKey = keyPair.getPrivate();
writeFile(privateKey.getEncoded(), privatekeyFile);
}
/**
* 用私钥加密
*
* @param data
* @return
*/
public void encryptByPrivateKey(byte[] data) {
// 取得私钥
byte[] key = readFile(privatekeyFile);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key privateKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据加密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
writeFile(cipher.doFinal(data), serverdataFile);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用私钥对信息生成数字签名
*
* @param data
* 加密数据
* @param privateKey
* 私钥
*
* @return
* @throws Exception
*/
public void generateSign() {
byte[] privateKey = readFile(privatekeyFile);
byte[] serverData = readFile(serverdataFile);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = null;
PrivateKey priKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
priKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Signature signature = Signature.getInstance(singAlgorithm);
signature.initSign(priKey);
signature.update(serverData);
writeFile(signature.sign(), signdataFile);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public byte[] decryptByPrivateKey() {
byte[] data = readFile(clientdataFile);
byte[] key = readFile(privatekeyFile);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key privateKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] arg) {
String data = "客户端你好,我是服务端";
// 服务端操作
BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
// 生成密钥对
bothRSAServerFile.generateKeyFile();
// 加密明文
bothRSAServerFile.encryptByPrivateKey(data.getBytes());
// 生成签名
bothRSAServerFile.generateSign();
// 客户端操作
BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
byte[] data1 =null;
if(bothRSAClientFile.verifySign()){
data1= bothRSAClientFile.decryptByPublicKey();
}
System.out.println("Servet原始数据:"+data);
System.out.println("Client解密数据:"+new String (data1));
}
实例542 RSA服务端加密
BothRSAClientFile.java
private String keyAlgorithm = "RSA";
private String singAlgorithm = "MD5withRSA";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 签名文件
private String signdataFile = "fileSignData.dat";
// 公钥文件
private String publickeyFile = "keyPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 校验数字签名
*
* @return 校验成功返回true 失败返回false
*/
public boolean verifySign() {
byte[] data = readFile(serverdataFile);
byte[] publicKey = readFile(publickeyFile);
byte[] sign = readFile(signdataFile);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = null;
PublicKey pubKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
pubKey = keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 验证签名是否正常
Signature signature = Signature.getInstance(singAlgorithm);
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(sign);
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
* 用公钥解密
*
* @return
*/
public byte[] decryptByPublicKey() {
byte[] data = readFile(serverdataFile);
byte[] key = readFile(publickeyFile);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key publicKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据解密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 用公钥加密
*/
public void encryptByPublicKey(byte[] data) {
byte[] key = readFile(publickeyFile);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key publicKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据加密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
writeFile(cipher.doFinal(data), clientdataFile);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchPaddingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] arg) {
BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
String cdata = "服务端你好,这里是客户端";
bothRSAClientFile.encryptByPublicKey(cdata.getBytes());
byte [] cdata1 = bothRSAServerFile.decryptByPrivateKey();
System.out.println("Client原始数据:"+cdata);
System.out.println("Servet解密数据:"+new String (cdata1));
}
BothRSAServerFile.java
private String keyAlgorithm = "RSA";
private String singAlgorithm = "MD5withRSA";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 签名文件
private String signdataFile = "fileSignData.dat";
// 私钥文件
private String privatekeyFile = "keyPrivateData.dat";
// 公钥文件
private String publickeyFile = "keyPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成密钥对
*/
public void generateKeyFile() {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = keyPair.getPublic();
writeFile(publicKey.getEncoded(), publickeyFile);
// 私钥
PrivateKey privateKey = keyPair.getPrivate();
writeFile(privateKey.getEncoded(), privatekeyFile);
}
/**
* 用私钥加密
*
* @param data
* @return
*/
public void encryptByPrivateKey(byte[] data) {
// 取得私钥
byte[] key = readFile(privatekeyFile);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key privateKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据加密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
writeFile(cipher.doFinal(data), serverdataFile);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用私钥对信息生成数字签名
*
* @param data
* 加密数据
* @param privateKey
* 私钥
*
* @return
* @throws Exception
*/
public void generateSign() {
byte[] privateKey = readFile(privatekeyFile);
byte[] serverData = readFile(serverdataFile);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = null;
PrivateKey priKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
priKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Signature signature = Signature.getInstance(singAlgorithm);
signature.initSign(priKey);
signature.update(serverData);
writeFile(signature.sign(), signdataFile);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public byte[] decryptByPrivateKey() {
byte[] data = readFile(clientdataFile);
byte[] key = readFile(privatekeyFile);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key privateKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] arg) {
String data = "客户端你好,我是服务端";
// 服务端操作
BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
// 生成密钥对
bothRSAServerFile.generateKeyFile();
// 加密明文
bothRSAServerFile.encryptByPrivateKey(data.getBytes());
// 生成签名
bothRSAServerFile.generateSign();
// 客户端操作
BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
byte[] data1 =null;
if(bothRSAClientFile.verifySign()){
data1= bothRSAClientFile.decryptByPublicKey();
}
System.out.println("Servet原始数据:"+data);
System.out.println("Client解密数据:"+new String (data1));
}
实例543 RSA客户端加密
BothRSAClientFile.java
private String keyAlgorithm = "RSA";
private String singAlgorithm = "MD5withRSA";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 签名文件
private String signdataFile = "fileSignData.dat";
// 公钥文件
private String publickeyFile = "keyPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 校验数字签名
*
* @return 校验成功返回true 失败返回false
*/
public boolean verifySign() {
byte[] data = readFile(serverdataFile);
byte[] publicKey = readFile(publickeyFile);
byte[] sign = readFile(signdataFile);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = null;
PublicKey pubKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
pubKey = keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 验证签名是否正常
Signature signature = Signature.getInstance(singAlgorithm);
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(sign);
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
* 用公钥解密
*
* @return
*/
public byte[] decryptByPublicKey() {
byte[] data = readFile(serverdataFile);
byte[] key = readFile(publickeyFile);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key publicKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据解密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 用公钥加密
*/
public void encryptByPublicKey(byte[] data) {
byte[] key = readFile(publickeyFile);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key publicKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据加密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
writeFile(cipher.doFinal(data), clientdataFile);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchPaddingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] arg) {
BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
String cdata = "服务端你好,这里是客户端";
bothRSAClientFile.encryptByPublicKey(cdata.getBytes());
byte [] cdata1 = bothRSAServerFile.decryptByPrivateKey();
System.out.println("Client原始数据:"+cdata);
System.out.println("Servet解密数据:"+new String (cdata1));
}
BothRSAServerFile.java
private String keyAlgorithm = "RSA";
private String singAlgorithm = "MD5withRSA";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 签名文件
private String signdataFile = "fileSignData.dat";
// 私钥文件
private String privatekeyFile = "keyPrivateData.dat";
// 公钥文件
private String publickeyFile = "keyPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成密钥对
*/
public void generateKeyFile() {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = keyPair.getPublic();
writeFile(publicKey.getEncoded(), publickeyFile);
// 私钥
PrivateKey privateKey = keyPair.getPrivate();
writeFile(privateKey.getEncoded(), privatekeyFile);
}
/**
* 用私钥加密
*
* @param data
* @return
*/
public void encryptByPrivateKey(byte[] data) {
// 取得私钥
byte[] key = readFile(privatekeyFile);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key privateKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 对数据加密
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
writeFile(cipher.doFinal(data), serverdataFile);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用私钥对信息生成数字签名
*
* @param data
* 加密数据
* @param privateKey
* 私钥
*
* @return
* @throws Exception
*/
public void generateSign() {
byte[] privateKey = readFile(privatekeyFile);
byte[] serverData = readFile(serverdataFile);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = null;
PrivateKey priKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
priKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Signature signature = Signature.getInstance(singAlgorithm);
signature.initSign(priKey);
signature.update(serverData);
writeFile(signature.sign(), signdataFile);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public byte[] decryptByPrivateKey() {
byte[] data = readFile(clientdataFile);
byte[] key = readFile(privatekeyFile);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = null;
Key privateKey = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] arg) {
String data = "客户端你好,我是服务端";
// 服务端操作
BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
// 生成密钥对
bothRSAServerFile.generateKeyFile();
// 加密明文
bothRSAServerFile.encryptByPrivateKey(data.getBytes());
// 生成签名
bothRSAServerFile.generateSign();
// 客户端操作
BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
byte[] data1 =null;
if(bothRSAClientFile.verifySign()){
data1= bothRSAClientFile.decryptByPublicKey();
}
System.out.println("Servet原始数据:"+data);
System.out.println("Client解密数据:"+new String (data1));
}
实例544 DH服务端加密
BothDHClientFile.java
private String keyAlgorithm = "DH";
private String secretAlgorithm = "DES";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 服务端公钥文件
private String publicServerkeyFile = "keyServerPublicData.dat";
// 客户端公钥文件
private String publicClientkeyFile = "keyClientPublicData.dat";
// 客户端私钥文件
private String privateClientkeyFile = "keyClientPrivateData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成客户端密钥对
*/
public void generateClientKeyFile() {
KeyPairGenerator keyPairGen = null;
try {
byte[] publicServerkey = readFile(publicServerkeyFile);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publicServerkey);
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
DHParameterSpec dhParameterSpec = ((DHPublicKey) publicKey)
.getParams();
keyPairGen = KeyPairGenerator
.getInstance(keyFactory.getAlgorithm());
keyPairGen.initialize(dhParameterSpec);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = keyPair.getPublic();
writeFile(publicKey.getEncoded(), publicClientkeyFile);
// 私钥
PrivateKey privateKey = keyPair.getPrivate();
writeFile(privateKey.getEncoded(), privateClientkeyFile);
}
/**
* 生成客户端机密密钥
*
* @return
*/
private SecretKey getClientSecretKey() {
byte[] privateClientKey = readFile(privateClientkeyFile);
byte[] publicServerKey = readFile(publicServerkeyFile);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicServerKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
privateClientKey);
PublicKey publicKey = null;
KeyFactory keyFactory = null;
Key privateKey = null;
KeyAgreement keyAgree = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
// privateKey = keyFactory.generatePrivate(x509KeySpec);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 创建密钥协议
keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
keyAgree.init(privateKey);
keyAgree.doPhase(publicKey, true);
return keyAgree.generateSecret(secretAlgorithm);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 客户端数据解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public byte[] decryptForClient() {
SecretKey secretKey = getClientSecretKey();
try {
byte[] data = readFile(serverdataFile);
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 客户端数据加密
*
* @param data
*/
public void encryptForClient(byte[] data) {
SecretKey secretKey = getClientSecretKey();
try {
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
writeFile(cipher.doFinal(data), clientdataFile);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] arg) {
String data = "服务端你好,我是客户端";
BothDHServerFile bothDHServerFile = new BothDHServerFile();
BothDHClientFile bothDHClientFile = new BothDHClientFile();
// 生成服务端密钥对
bothDHServerFile.generateServerKeyFile();
// 生成客户端密钥对
bothDHClientFile.generateClientKeyFile();
// 客户端加密
bothDHClientFile.encryptForClient(data.getBytes());
// 服务端解密
byte[] data1 = bothDHServerFile.decryptForServer();
System.out.println("Client原始数据:" + data);
System.out.println("Servet解密数据:" + new String(data1));
}
BothDHServerFile.java
private String keyAlgorithm = "DH";
private String secretAlgorithm = "DES";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 服务端私钥文件
private String privateServerkeyFile = "keyServerPrivateData.dat";
// 服务端公钥文件
private String publicServerkeyFile = "keyServerPublicData.dat";
// 客户端公钥文件
private String publicClientkeyFile = "keyClientPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成服务端密钥对
*/
public void generateServerKeyFile() {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = keyPair.getPublic();
writeFile(publicKey.getEncoded(), publicServerkeyFile);
// 私钥
PrivateKey privateKey = keyPair.getPrivate();
writeFile(privateKey.getEncoded(), privateServerkeyFile);
}
/**
* 生成服务端机密密钥
*
* @return
*/
private SecretKey getServerSecretKey() {
byte[] privateServerKey = readFile(privateServerkeyFile);
byte[] publicClientKey = readFile(publicClientkeyFile);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicClientKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
privateServerKey);
Key publicKey = null;
KeyFactory keyFactory = null;
Key privateKey = null;
KeyAgreement keyAgree = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 创建密钥协议
keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
//初始化密钥
keyAgree.init(privateKey);
keyAgree.doPhase(publicKey, true);
return keyAgree.generateSecret(secretAlgorithm);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 服务端数据加密
*
* @param data
*/
public void encryptForServer(byte[] data) {
SecretKey secretKey = getServerSecretKey();
try {
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
writeFile(cipher.doFinal(data), serverdataFile);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 服务端数据解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public byte[] decryptForServer() {
SecretKey secretKey = getServerSecretKey();
try {
byte[] data = readFile(clientdataFile);
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] arg) {
String data = "客户端你好,我是服务端";
BothDHServerFile bothDHServerFile = new BothDHServerFile();
BothDHClientFile bothDHClientFile = new BothDHClientFile();
// 生成服务端密钥对
bothDHServerFile.generateServerKeyFile();
// 生成客户端密钥对
bothDHClientFile.generateClientKeyFile();
// 服务端加密
bothDHServerFile.encryptForServer(data.getBytes());
// 客户端解密
byte[] data1 = bothDHClientFile.decryptForClient();
System.out.println("Servet原始数据:" + data);
System.out.println("Client解密数据:" + new String(data1));
}
实例545 DH客户端加密
BothDHClientFile.java
private String keyAlgorithm = "DH";
private String secretAlgorithm = "DES";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 服务端公钥文件
private String publicServerkeyFile = "keyServerPublicData.dat";
// 客户端公钥文件
private String publicClientkeyFile = "keyClientPublicData.dat";
// 客户端私钥文件
private String privateClientkeyFile = "keyClientPrivateData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成客户端密钥对
*/
public void generateClientKeyFile() {
KeyPairGenerator keyPairGen = null;
try {
byte[] publicServerkey = readFile(publicServerkeyFile);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publicServerkey);
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
DHParameterSpec dhParameterSpec = ((DHPublicKey) publicKey)
.getParams();
keyPairGen = KeyPairGenerator
.getInstance(keyFactory.getAlgorithm());
keyPairGen.initialize(dhParameterSpec);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = keyPair.getPublic();
writeFile(publicKey.getEncoded(), publicClientkeyFile);
// 私钥
PrivateKey privateKey = keyPair.getPrivate();
writeFile(privateKey.getEncoded(), privateClientkeyFile);
}
/**
* 生成客户端机密密钥
*
* @return
*/
private SecretKey getClientSecretKey() {
byte[] privateClientKey = readFile(privateClientkeyFile);
byte[] publicServerKey = readFile(publicServerkeyFile);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicServerKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
privateClientKey);
PublicKey publicKey = null;
KeyFactory keyFactory = null;
Key privateKey = null;
KeyAgreement keyAgree = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
// privateKey = keyFactory.generatePrivate(x509KeySpec);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 创建密钥协议
keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
keyAgree.init(privateKey);
keyAgree.doPhase(publicKey, true);
return keyAgree.generateSecret(secretAlgorithm);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 客户端数据解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public byte[] decryptForClient() {
SecretKey secretKey = getClientSecretKey();
try {
byte[] data = readFile(serverdataFile);
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 客户端数据加密
*
* @param data
*/
public void encryptForClient(byte[] data) {
SecretKey secretKey = getClientSecretKey();
try {
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
writeFile(cipher.doFinal(data), clientdataFile);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] arg) {
String data = "服务端你好,我是客户端";
BothDHServerFile bothDHServerFile = new BothDHServerFile();
BothDHClientFile bothDHClientFile = new BothDHClientFile();
// 生成服务端密钥对
bothDHServerFile.generateServerKeyFile();
// 生成客户端密钥对
bothDHClientFile.generateClientKeyFile();
// 客户端加密
bothDHClientFile.encryptForClient(data.getBytes());
// 服务端解密
byte[] data1 = bothDHServerFile.decryptForServer();
System.out.println("Client原始数据:" + data);
System.out.println("Servet解密数据:" + new String(data1));
}
BothDHServerFile.java
private String keyAlgorithm = "DH";
private String secretAlgorithm = "DES";
// 服务端数据文件
private String serverdataFile = "fileServerData.dat";
// 客户端数据文件
private String clientdataFile = "fileClientData.dat";
// 服务端私钥文件
private String privateServerkeyFile = "keyServerPrivateData.dat";
// 服务端公钥文件
private String publicServerkeyFile = "keyServerPublicData.dat";
// 客户端公钥文件
private String publicClientkeyFile = "keyClientPublicData.dat";
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成服务端密钥对
*/
public void generateServerKeyFile() {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = keyPair.getPublic();
writeFile(publicKey.getEncoded(), publicServerkeyFile);
// 私钥
PrivateKey privateKey = keyPair.getPrivate();
writeFile(privateKey.getEncoded(), privateServerkeyFile);
}
/**
* 生成服务端机密密钥
*
* @return
*/
private SecretKey getServerSecretKey() {
byte[] privateServerKey = readFile(privateServerkeyFile);
byte[] publicClientKey = readFile(publicClientkeyFile);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicClientKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
privateServerKey);
Key publicKey = null;
KeyFactory keyFactory = null;
Key privateKey = null;
KeyAgreement keyAgree = null;
try {
keyFactory = KeyFactory.getInstance(keyAlgorithm);
publicKey = keyFactory.generatePublic(x509KeySpec);
privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 创建密钥协议
keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
keyAgree.init(privateKey);
keyAgree.doPhase(publicKey, true);
return keyAgree.generateSecret(secretAlgorithm);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 服务端数据加密
*
* @param data
*/
public void encryptForServer(byte[] data) {
SecretKey secretKey = getServerSecretKey();
try {
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
writeFile(cipher.doFinal(data), serverdataFile);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 服务端数据解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public byte[] decryptForServer() {
SecretKey secretKey = getServerSecretKey();
try {
byte[] data = readFile(clientdataFile);
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] arg) {
String data = "客户端你好,我是服务端";
BothDHServerFile bothDHServerFile = new BothDHServerFile();
BothDHClientFile bothDHClientFile = new BothDHClientFile();
// 生成服务端密钥对
bothDHServerFile.generateServerKeyFile();
// 生成客户端密钥对
bothDHClientFile.generateClientKeyFile();
// 服务端加密
bothDHServerFile.encryptForServer(data.getBytes());
// 客户端解密
byte[] data1 = bothDHClientFile.decryptForClient();
System.out.println("Servet原始数据:" + data);
System.out.println("Client解密数据:" + new String(data1));
}
20.3 Java单项加密
实例546 使用MD5加密
static String algorithm = "MD5";
/**
* MD5加密,返回byte[]类型
*
* @param data
* @return
* @throws NoSuchAlgorithmException
*/
public static byte[] encryptMD5(byte[] data)
throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(data);
return digest.digest();
}
/**
* 把MD5加密数据转换String类型
*
* @param data
* @return
* @throws NoSuchAlgorithmException
*/
public static String encryptMD5toString(byte[] data)
throws NoSuchAlgorithmException {
String str = "";
String str16;
System.out.println(data.length);
for (int i = 0; i < data.length; i++) {
str16 = Integer.toHexString(0xFF & data[i]);
if (str16.length() == 1) {
str = str + "0" + str16;
} else {
str = str + str16;
}
}
return str;
}
public static void main(String[] avg) {
String data = "明日科技";
System.out.println("加密前:" + data);
byte[] data1 = null;
String str = null;
try {
data1 = SingleMD5.encryptMD5(data.getBytes());
str = SingleMD5.encryptMD5toString(data1);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("加密后byte[]类型:" + new String(data1));
System.out.println("加密后String类型:" + str);
}
实例547 使用Hmac加密
BothBase64.java
public static String encryptBASE64(byte[] data) {
return (new BASE64Encoder()).encodeBuffer(data);
}
/**
* 解密
*
* @param data
* @return
* @throws IOException
*/
public static byte[] decryptBASE64(String data) throws IOException {
return (new BASE64Decoder()).decodeBuffer(data);
}
public static void main(String[] avg) {
String data = "明日科技";
System.out.println("加密前:" + data);
String data1 = BothBase64.encryptBASE64(data.getBytes());
System.out.println("加密后:" + data1);
byte[] data2 = null;
try {
data2 = BothBase64.decryptBASE64(data1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("解密后:" + new String(data2));
}
SingleHmacClientFile.java
static String algorithm = "HmacMD5";
static String keyFile = "keyData.dat";
static String dataFile = "fileData.dat";
/**
* HMAC加密
*
* @param data
* @param key
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public byte[] encryptHMAC(byte[] data) throws NoSuchAlgorithmException,
InvalidKeyException {
byte key[] = readFile(keyFile);
SecretKey secretKey = new SecretKeySpec(key, algorithm);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
return mac.doFinal();
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
SingleHmacServerFile.java
static String algorithm = "HmacMD5";
static String keyFile = "keyData.dat";
/**
* 生成密钥
*
* @return
* @throws NoSuchAlgorithmException
*/
public void initMacKey() throws NoSuchAlgorithmException {
KeyGenerator generator = KeyGenerator.getInstance(algorithm);
SecretKey key = generator.generateKey();
writeFile(key.getEncoded(), keyFile);
}
/**
* HMAC加密
*
* @param data
* @param key
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public byte[] encryptHMAC(byte[] data) throws NoSuchAlgorithmException,
InvalidKeyException {
byte key[] = readFile(keyFile);
SecretKey secretKey = new SecretKeySpec(key, algorithm);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
return mac.doFinal();
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) throws NoSuchAlgorithmException, InvalidKeyException {
SingleHmacServerFile singleHmacServerFile = new SingleHmacServerFile();
SingleHmacClientFile singleHmacClientFile = new SingleHmacClientFile();
String data = "明日科技";
System.out.println("加密前:" + data);
String strData = null;
String strDataClient = null;
singleHmacServerFile.initMacKey();
strData = BothBase64.encryptBASE64(singleHmacServerFile.encryptHMAC(data.getBytes()));
strDataClient = BothBase64.encryptBASE64(singleHmacClientFile.encryptHMAC(data.getBytes()));
System.out.println("服务端加密后:" + strData);
System.out.println("客户端加密后:" + strDataClient);
if (strData.equals(strDataClient)) {
System.out.println("验证通过");
} else {
System.out.println("验证不通过");
}
}
实例548 使用DSA加密
SingleDSAClientFile.java
static String algorithm = "DSA";
static String signdataFile = "fileSignData.dat";
static String publickeyFile = "keyPublicData.dat";
/**
* 用数字签名进行验证
*
* @param data
* @return
*/
public boolean verifySign(byte[] data) {
byte[] key = readFile(publickeyFile);
byte[] sign = readFile(signdataFile);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = null;
PublicKey publicKey = null;
try {
// 获取公钥匙
keyFactory = KeyFactory.getInstance(algorithm);
publicKey = keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 验证数字签名
Signature signature = Signature.getInstance(keyFactory
.getAlgorithm());
signature.initVerify(publicKey);
signature.update(data);
return signature.verify(sign);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
SingleDSAServerFile.java
static String algorithm = "DSA";
static String signdataFile = "fileSignData.dat";
static String privatekeyFile = "keyPrivateData.dat";
static String publickeyFile = "keyPublicData.dat";
/**
* 生成密钥对
*
* @return
* @throws NoSuchAlgorithmException
*/
public void generatorKey() {
KeyPairGenerator generator = null;
try {
generator = KeyPairGenerator.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyPair keyPair = generator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
writeFile(publicKey.getEncoded(), publickeyFile);
writeFile(privateKey.getEncoded(), privatekeyFile);
}
/**
* 生成签名
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
* @throws SignatureException
*/
public void generatorSign(byte[] data) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
byte[] privateKey = readFile(privatekeyFile);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
// algorithm 指定的加密算法
KeyFactory keyFactory = null;
PrivateKey priKey = null;
keyFactory = KeyFactory.getInstance(algorithm);
priKey = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(keyFactory.getAlgorithm());
signature.initSign(priKey);
signature.update(data);
writeFile(signature.sign(), signdataFile);
}
/**
* 把数据写到指定的文件上
*
* @param data
* 数据
* @param fileName
* 文件名称
*/
public void writeFile(byte[] data, String fileName) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(data);
fileOutputStream.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 根据fileName读取数据文件
*
* @param fileName
* @return
*/
public byte[] readFile(String fileName) {
// 读取
try {
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
return data;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] avg) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
SingleDSAServerFile singleDSAServerFile = new SingleDSAServerFile();
SingleDSAClientFile singleDSAClientFile = new SingleDSAClientFile();
String data = "明日科技";
System.out.println("传输数据:" + data);
boolean flag = false;
singleDSAServerFile.generatorKey();
singleDSAServerFile.generatorSign(data.getBytes());
flag = singleDSAClientFile.verifySign(data.getBytes());
if (flag) {
System.out.println("验证通过,数据传输过程没有经过修改");
} else {
System.out.println("验证不过通,数据传输过程经过修改");
}
}