Java crypto DES AES 복호화
49602 단어 JavaEE
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* DES AES
*/
public class CryptUtil {
public static final String type_DES = "DES";
public static final String type_AES = "AES";
public static final String code_utf8 = "utf-8";
private String type;
private String code;
public CryptUtil(String type, String code) {
this.type = type;
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public static String byteToHexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] hexStrToByte(String hexStr) {
if (hexStr == null || hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
private Key createKey(String key) throws Exception {
if (type_DES.equals(type)) {
DESKeySpec dks = new DESKeySpec(key.getBytes(code));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(type);
SecretKey securekey = keyFactory.generateSecret(dks);
return securekey;
} else if (type_AES.equals(type)) {
KeyGenerator keyGen = KeyGenerator.getInstance(type);
keyGen.init(128, new SecureRandom(key.getBytes(code)));
SecretKey secretKey = keyGen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, type);
return keySpec;
}
return null;
}
private Cipher createEncryptCipher(String key) throws Exception {
Cipher cipher = Cipher.getInstance(type);
cipher.init(Cipher.ENCRYPT_MODE, createKey(key), new SecureRandom());
return cipher;
}
public byte[] encrypt(byte[] data, String key) throws Exception {
Cipher cipher = createEncryptCipher(key);
return cipher.doFinal(data);
}
public void encryptFileToFile(File src, File des, String key) throws Exception {
Cipher cipher = createEncryptCipher(key);
try (FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(des); CipherInputStream cipIn = new CipherInputStream(in, cipher)) {
byte[] buffer = new byte[1024];
for (int len = cipIn.read(buffer); len > 0; len = cipIn.read(buffer)) {
out.write(buffer, 0, len);
out.flush();
}
} catch (Exception e) {
throw e;
}
}
public byte[] encryptStr(String data, String key) throws Exception {
Cipher cipher = createEncryptCipher(key);
return cipher.doFinal(data.getBytes(code));
}
public String encryptStrToHexStr(String data, String key) throws Exception {
byte[] encryptStr = encryptStr(data, key);
return CryptUtil.byteToHexStr(encryptStr);
}
private Cipher createDecryptCipher(String key) throws Exception {
Cipher cipher = Cipher.getInstance(type);
cipher.init(Cipher.DECRYPT_MODE, createKey(key), new SecureRandom());
return cipher;
}
public byte[] decrypt(byte[] data, String key) throws Exception {
Cipher cipher = createDecryptCipher(key);
return cipher.doFinal(data);
}
public void decryptFileToFile(File src, File des, String key) throws Exception {
Cipher cipher = createDecryptCipher(key);
try (FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(des); CipherOutputStream cipOut = new CipherOutputStream(out, cipher)) {
byte[] buffer = new byte[4096];//
for (int len = in.read(buffer); len > 0; len = in.read(buffer)) {
cipOut.write(buffer, 0, len);
}
} catch (Exception e) {
throw e;
}
}
public String decryptToStr(byte[] data, String key) throws Exception {
Cipher cipher = createDecryptCipher(key);
byte[] result = cipher.doFinal(data);
return new String(result, code);
}
public String decryptHexStrToStr(String data, String key) throws Exception {
byte[] decryptFrom = CryptUtil.hexStrToByte(data);
return decryptToStr(decryptFrom, key);
}
public static void main(String[] args) throws Exception {
desTest(args);
aesTest(args);
aesFileTest(args);
}
public static void desTest(String[] args) throws Exception {
CryptUtil cryptUtil=new CryptUtil(CryptUtil.type_DES, CryptUtil.code_utf8);
String data = "abcefghijklmnopqrstuvwxyz *_-+=()0123456789";
String key = " 0001111";
long time = System.currentTimeMillis();
System.out.println(" :" + data);
byte[] encrypt = cryptUtil.encryptStr(data, key);
System.out.println(" :" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
String decrypt = cryptUtil.decryptToStr(encrypt, key);
System.out.println(" :" + (System.currentTimeMillis() - time));
System.out.println(" :" + decrypt);
}
public static void aesTest(String[] args) throws Exception {
CryptUtil cryptUtil = new CryptUtil(CryptUtil.type_AES, CryptUtil.code_utf8);
String data = "abcefghijklmnopqrstuvwxyz *_-+=()0123456789";
String key = " 0001111";
long time = System.currentTimeMillis();
System.out.println(" :" + data);
byte[] encrypt = cryptUtil.encryptStr(data, key);
System.out.println(" :" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
String decrypt = cryptUtil.decryptToStr(encrypt, key);
System.out.println(" :" + (System.currentTimeMillis() - time));
System.out.println(" :" + decrypt);
}
public static void aesFileTest(String[] args) throws Exception {
CryptUtil cryptUtil = new CryptUtil(CryptUtil.type_AES, CryptUtil.code_utf8);
String key = " 0001111";
long time = System.currentTimeMillis();
cryptUtil.encryptFileToFile(new File("D:\\ \\zwyl.zip"), new File("C:\\Users\\tangzhichao\\Desktop\\ .zip"), key);
System.out.println(" :" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
cryptUtil.decryptFileToFile(new File("C:\\Users\\tangzhichao\\Desktop\\ .zip"), new File("C:\\Users\\tangzhichao\\Desktop\\ .zip"), key);
System.out.println(" :" + (System.currentTimeMillis() - time));
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【intra-mart】Java 클래스 파일 등이 Import 할 수 없게되었을 때의 대처법오늘은, intra-mart로 Java의 클래스 파일등이 Import 할 수 없게 되었을 때의 대처법을 기재합니다. JavaEE 개발을 할 때 자신도 같은 상황이 되었습니다. 비망을 위해 기사로하고 있습니다. 【전제...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.