DES 대칭 암호 화 알고리즘 의 간단 한 실현
17542 단어 자바 서버
환경.
코드
소스 코드 가 Gitee 에 올 라 왔어요.
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
/**
* DES
*/
public class DES {
/**
* iv
*/
private static final byte[] DESIV = { (byte) 0xCE, (byte) 0x35, (byte) 0x5,
(byte) 0xD, (byte) 0x98, (byte) 0x91, (byte) 0x8, (byte) 0xA };
/**
* AlgorithmParameterSpec
*/
private static AlgorithmParameterSpec IV = null;
/**
*
*/
private static final int ENCRYPT_MODE = 1;
/**
*
*/
private static final int DECRYPT_MODE = 2;
/**
*
*/
private Key key;
public DES(String str) {
getKey(str);
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
/**
* key
* @param secretKey
*/
public void getKey(String secretKey) {
try {
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(secretKey.getBytes());
KeyGenerator generator = null;
try {
generator = KeyGenerator.getInstance("DES");
} catch (NoSuchAlgorithmException e) {
}
generator.init(secureRandom);
IV = new IvParameterSpec(DESIV);
this.key = generator.generateKey();
generator = null;
} catch (Exception e) {
throw new RuntimeException("Error in getKey(String secretKey), Cause: " + e);
}
}
/**
* des
* @param data
* @return
* @throws Exception
*/
public byte[] encrypt(byte[] data) throws Exception {
Cipher cipher = getPattern(ENCRYPT_MODE);
return cipher.doFinal(data);
}
/**
* des
* @param data
* @return
* @throws Exception
*/
public byte[] decrypt(byte[] data) throws Exception {
Cipher cipher = getPattern(DECRYPT_MODE);
return cipher.doFinal(data);
}
/**
* cipher
* @param cipherMode cipher 1: ; 2:
* @return cipher
* @throws Exception
*/
private Cipher getPattern(int cipherMode) throws Exception {
Cipher cipher;
cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(cipherMode, key, IV);
return cipher;
}
public static void main(String[] args) throws Exception {
String testString = "I am YiMi";
DES des = new DES("blockchain"); //
String stringMi = Base64.getEncoder().encodeToString(des.encrypt(testString.getBytes()));
System.out.println(" :" + stringMi);
byte[] stringMing = des.decrypt(Base64.getDecoder().decode(stringMi));
System.out.println(" :" + new String(stringMing));
}
}