자바 보안 - 비대 칭 암호 화 / 복호화 (소스 코드 구현)
코드 데모:
package com.naxsu.security;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
/**
* /
*/
public class SecretKeyTest {
public static void main(String[] args) throws Exception {
// secretEncrypt();
// secretDecrypt();
// secretEncryptByPass();
// secretDecryptByPass();
publicEncrypt();
privateDecrypt();
}
/**
* ,
* @throws Exception
*/
private static void secretEncrypt() throws Exception {
// Cipher:
Cipher cipher = Cipher.getInstance("AES");
//
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
/*
* : key , , ObjectOutputStream.writeObject()
* , Serializable ,Object--> -->Object
*/
// secret.key
saveKey(key, "secret.key");
// cipher
cipher.init(Cipher.ENCRYPT_MODE, key);
// cipher.update("aaa".getBytes());
// cipher.update("aaa".getBytes());
// byte[] results = cipher.doFinal();
// aaa
byte[] results = cipher.doFinal("aaa".getBytes());
System.out.println(new String(results));
// data.txt
saveData(results, "data.txt");
}
/**
* , ,
* @throws Exception
*/
private static void secretDecrypt() throws Exception {
Cipher cipher = Cipher.getInstance("AES");
// secret.key
Key key = readKey("secret.key");
// cipher
cipher.init(Cipher.DECRYPT_MODE, key);
// data.txt ,
byte[] src = readData("data.txt");
//
byte[] result = cipher.doFinal(src);
System.out.println(new String(result));
}
/**
*
* @throws Exception
*/
private static void secretEncryptByPass() throws Exception {
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
.generateSecret(new PBEKeySpec("12345678".toCharArray()));
PBEParameterSpec parameterSpec = new PBEParameterSpec(new byte[] { 1,
2, 3, 4, 5, 6, 7, 8 }, 1000);
cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
byte[] results = cipher.doFinal("aaa".getBytes());
System.out.println(new String(results));
saveData(results,"data.txt");
}
/**
*
* @throws Exception
*/
private static void secretDecryptByPass() throws Exception {
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
.generateSecret(new PBEKeySpec("12345678".toCharArray()));
PBEParameterSpec parameterSpec = new PBEParameterSpec(new byte[] { 1,
2, 3, 4, 5, 6, 7, 8 }, 1000);
cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
byte[] src = readData("data.txt");
//
byte[] result = cipher.doFinal(src);
System.out.println(new String(result));
}
/**
*
* @throws Exception
*/
private static void publicEncrypt() throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
KeyPairGenerator kPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = kPairGenerator.generateKeyPair();
Key publicKey = keyPair.getPublic();
Key privateKey = keyPair.getPrivate();
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(" ".getBytes("UTF-8"));
saveKey(privateKey, "secret2.key");
saveData(result, "data2.txt");
}
/**
*
* @throws Exception
*/
private static void privateDecrypt() throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
Key privateKey = readKey("secret2.key");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// 1:
// byte[] src = readData("data2.txt");
// byte[] result=cipher.doFinal(src);
// System.err.println(new String(result,"UTF-8"));
// 2:
// FileInputStream fis = new FileInputStream("data2.txt");
// CipherInputStream cis = new CipherInputStream(fis, cipher);
// //
// byte[] buf = new byte[1024];
// int len = cis.read(buf);
// System.out.println(new String(buf,0,len,"UTF-8"));
// 3:
FileInputStream fis = new FileInputStream("data2.txt");
FileOutputStream fos = new FileOutputStream("result.txt");
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
copyStream(fis, cos);
cos.close();
fos.close();
fis.close();
}
/**
*
* @param is
* @param os
* @throws IOException
*/
private static void copyStream(InputStream is, OutputStream os)
throws IOException {
byte[] buf = new byte[1024];
int len = is.read(buf);
while (len != -1) {
os.write(buf, 0, len);
len = is.read(buf);
}
}
/**
* key
* @param key
* @param fileName
* @throws FileNotFoundException
* @throws IOException
*/
private static void saveKey(Key key, String fileName)
throws FileNotFoundException, IOException {
FileOutputStream fosKey = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fosKey);
oos.writeObject(key);
oos.close();
fosKey.close();
}
/**
*
* @param results
* @param fileName
* @throws FileNotFoundException
* @throws IOException
*/
private static void saveData(byte[] results, String fileName)
throws FileNotFoundException, IOException {
FileOutputStream fosData = new FileOutputStream(fileName);
fosData.write(results);
fosData.close();
}
/**
* key
* @param fileName
* @return
* @throws FileNotFoundException
* @throws IOException
* @throws ClassNotFoundException
*/
private static Key readKey(String fileName) throws FileNotFoundException, IOException,
ClassNotFoundException {
FileInputStream fisKey = new FileInputStream(fileName);
ObjectInputStream oisKey = new ObjectInputStream(fisKey);
Key key = (Key) oisKey.readObject();
oisKey.close();
fisKey.close();
return key;
}
/**
*
* @param fileName
* @return
* @throws FileNotFoundException
* @throws IOException
*/
private static byte[] readData(String fileName) throws FileNotFoundException, IOException {
FileInputStream fisData = new FileInputStream(fileName);
// 1: , byte
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// copyStream(fisData, baos);
// byte[] src = baos.toByteArray();
// 2: available()
// available(): ( ) 。
byte[] src = new byte[fisData.available()];
int len = fisData.read(src);
int total = 0;
while (total < src.length) {
total += len;
len = fisData.read(src, total, src.length - total);
}
fisData.close();
// baos.close();
return src;
}
}
전재 출처 를 밝 혀 주 십시오:http://www.naxsu.com/java-an-quan-fei-dui-cheng-jia-mi-jie-mi/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.