跳到主要內容

玩玩DES及RSA

最近有個需求,就是希望能把儲存在文字檔中的密碼,增加一些安全機制,想說之前(參考JavaWorld@TW的一些資料)有玩過一下下DES及RSA說不定可以試試看,流程大概先產生一把KEY(DES)或是一對KEY(RSA),使用KEY針對資料進行加密,加過密的文字有可能會是非法字元,所以用BASE64進行encode或是decode,應用程式要使用加個密的資料,需要兩個要素第一個就是key,另外就是API,缺一不可(盡量防止Developer).

DES部分

DESGenerator
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import entiebank.utils.Utils;

public class DESKeyGenerator {

public static void genDESKey(String keyFileName,String alg){
try {
KeyGenerator kpg = KeyGenerator.getInstance(alg);
//TODO Default alg maybe can change
//SecureRandom random = SecureRandom.getInstance("SHA1PRNG","SUN");
//常用的
// random.setSeed(101L);
// kpg.init(56,random);
SecretKey sKey = kpg.generateKey();
System.out.println(sKey.hashCode());
// SecretKeyFactory kfactory = SecretKeyFactory.getInstance(alg);
//DESKeySpec kspec = (DESKeySpec)kfactory.getKeySpec(sKey, DESKeySpec.class);
Utils.writeKeyFile(keyFileName, sKey);
//output File
// FileOutputStream fos = new FileOutputStream(keyFileName);
// ObjectOutputStream oos  = new ObjectOutputStream(fos);
// oos.writeObject(sKey);
// oos.close();
//// fos.write(sKey.getEncoded());
// fos.close();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void main(String[] arg){
DESKeyGenerator.genDESKey("louisz.des", "DES");
}
}

DESUtils

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.DESKeySpec;

import entiebank.utils.Utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESUtils {
private static SecretKey sKey = null; 
public static void loadDESKey(String keyFileName){
sKey = (SecretKey)Utils.readKeyFile(keyFileName);
}
private static void readKey(){
System.out.println(sKey.hashCode());
}
public static SecretKey getDESKey(){
return sKey;
}
public static String encrypt(String clearString){
try {
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE,getDESKey());
//System.out.println("clearStr="+encryptString);
//System.out.println("encrypt=="+new String(desCipher.doFinal(encryptString.getBytes())));
return bytesToBase64Str(desCipher.doFinal(clearString.getBytes()));
} 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 String decrypt(String encryptString){
try {
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.DECRYPT_MODE,getDESKey());
return new String(desCipher.doFinal(base64StrToBytes(encryptString)));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException 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();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String decrypt(String keyFilename,String encryptString){
try {
SecretKey desKey = (SecretKey)Utils.readKeyFile(keyFilename);
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.DECRYPT_MODE,desKey);
return new String(desCipher.doFinal(base64StrToBytes(encryptString)));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException 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();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String bytesToBase64Str(byte[] bytes){
return new BASE64Encoder().encode(bytes);
}
public static byte[] base64StrToBytes(String base64Str){
try {
return new BASE64Decoder().decodeBuffer(base64Str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] arg){
// DESUtils des = new DESUtils();
DESUtils.loadDESKey("Key");
DESUtils.readKey();
//System.out.println(DESUtils.encrypt("hehe it's can works"));
System.out.println(DESUtils.decrypt("l+M1yV2Mf4yaTlSxmPU3GA=="));
}
}


RSA部分

RSAGenerator
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;

import entiebank.utils.Utils;

public class RSAKeyGenerator {
public static void genRSAPairKey(String keyFileName,String alg){
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(alg);
keyGen.initialize(1024);
KeyPair keyPair =keyGen.generateKeyPair();
PublicKey  pubKey = keyPair.getPublic();
System.out.println(pubKey.hashCode());
Utils.writeKeyFile(keyFileName+".pub", pubKey);
PrivateKey priKey= keyPair.getPrivate();
System.out.println(priKey.hashCode());
Utils.writeKeyFile(keyFileName+".pri", priKey);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] arg){
RSAKeyGenerator.genRSAPairKey("louisz","RSA");
}
}


RSAUtils

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

import entiebank.security.des.DESUtils;
import entiebank.utils.Utils;

public class RSAUtils {
private static PublicKey pubKey = null; 
private static PrivateKey priKey = null;
public static void loadRSAPubKey(String keyFileName){
pubKey=(PublicKey)Utils.readKeyFile(keyFileName);
}
public static void loadRSAPriKey(String keyFileName){
priKey=(PrivateKey)Utils.readKeyFile(keyFileName);
}
public static PublicKey getPublicKey(){
return pubKey;
}
public static PrivateKey getPrivateKey(){
return priKey;
}
public static String encrypt(String clearString){
try {
Cipher desCipher = Cipher.getInstance("RSA");
desCipher.init(Cipher.ENCRYPT_MODE,getPublicKey());
//System.out.println("clearStr="+encryptString);
//System.out.println("encrypt=="+new String(desCipher.doFinal(encryptString.getBytes())));
return Utils.bytesToBase64Str(desCipher.doFinal(clearString.getBytes()));
} 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 String decrypt(String encryptString){
try {
Cipher desCipher = Cipher.getInstance("RSA");
desCipher.init(Cipher.DECRYPT_MODE,getPrivateKey());
return new String(desCipher.doFinal(Utils.base64StrToBytes(encryptString)));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException 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();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] arg){
//RSAUtils rsa = new RSAUtils();
RSAUtils.loadRSAPriKey("louisz.pri");
RSAUtils.loadRSAPubKey("louisz.pub");
System.out.println(RSAUtils.encrypt("hehe it's can works"));
//System.out.println(rsa.decrypt("m/krh4KOgSNrDWpUrgUQ0ifVYmBnDAhdYU/B9HFZGiPsHDKOob/oQaJWyQX0a+VrC4igFq2a7zERrqUBjrImGgknMgjlko6NAufOHMu4BP4wblY68pIFPdIb1VZrN38vLgrtUjk1eXok7akn89Lu6NksBrlKoYEy2rOW/BfrCGs="));
}
}


Utils
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.crypto.SecretKey;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Utils {
public static Object readKeyFile(String keyFileName){
Object obj = null;
try {
FileInputStream fin = new FileInputStream(keyFileName);
ObjectInputStream ios = new ObjectInputStream(fin);
// DESKeySpec kSpec = (DESKeySpec)ios.readObject();
// kSpec.getKey();
obj= ios.readObject();
ios.close();
fin.close();
return obj;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void writeKeyFile(String keyFileName,Object sKey){
try {
FileOutputStream fos = new FileOutputStream(keyFileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(sKey);
oos.close();
// fos.write(sKey.getEncoded());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String bytesToBase64Str(byte[] bytes){
return new BASE64Encoder().encode(bytes);
}
public static byte[] base64StrToBytes(String base64Str){
try {
return new BASE64Decoder().decodeBuffer(base64Str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}


留言

這個網誌中的熱門文章

Pentaho kettle取指定目錄下的所有檔案

最近開始玩 BI的東西,而之前專案有使用到Pentaho Open Source這個好物.... Pentaho裡面很多東西,跟 Jasperreport一樣東西很多,我最先接觸到的是kettle ETL的工具,玩了一陣子,開始有空就把它寫下來,以免忘記。 Scan一個目錄下所有檔案,然後塞進去資料庫 1.先拉兩個 Input,一個Get File Names,一個是CSV file input,再拉一個 output 中的 Table output,然後把他連起來。 2.點開 Get File Names,File or directory設定你的指定目錄,Regular Expression則是輸入.*\.*$則是所有檔案,若是CSV則可.*\.torrent$這可以了,可以按一下 Preview rows看看是否正確。

Spring boot v1.5 (六) spring data jpa 基本操作

最近天氣好熱,做甚麼事都覺得很懶,想要寫個spring data jpa也是懶懶的,不過這部分卻也是滿重要的一部分,前一篇介紹 JDBCTemplate ,已經覺得跟以前寫SQL方式有所差異了,JPA帶來的是物件導向的設計面思考,說到JPA不得不提提 ORM ,Object-relational mapping主要想法為簡化及物件導向的設計,讓RDB更貼近Object,在設計上可以更加便利,甚至透過一些設計可以讓Table具有物件導向的特性如繼承等等,以往要使用ORM的框架,都會先以 Hibernate 進行,不過近來慢慢地轉向JPA,主要還是在減少程式碼、增加彈性等等,大體的功能沒有差異很大,所以從Hibernate轉到JPA問題不大,JPA要介紹的東西還滿多的,所以我這裡會再分成三個章節來介紹。 SPRING DATA JPA基本操作 JPQL & Named SQL & Native SQL Cache & DB Design Pattern SPRING DATA JPA更加簡化的程式撰寫,只需要一個 Interface內寫一些查詢 method就可以操作JPA,因為利用 method 組合查詢條件,確實很方便也很容易理解,若是都沒有辦法符合需求當然也可以自己實作一個來用當然沒有問題。 學習目的 :SPRING DATA JPA基本操作。 學習時數 :3.5hr 教學影片: pom.xml 說明 spring-boot-starter-web:配置 Web Project所需的函式庫。 spring-boot-starter-test:配置 unit or mock test 所需的函式庫。 spring-boot-starter-actuator:配置監控spring boot所需的函式庫,後續spring cloud會使用到,所以一開就導入。 spring-boot-starter-jdbc:配置使用jdbc所需的函式庫。 postgresql:配置postgresql連接Driver所需的函式庫。 jasypt-spring-boot-starter:加解密所需的函式庫。 spring-boot-starter-data-jpa:配置Spring data jpa所需的函式庫。

IReport字型下拉選單中文亂碼

這個問題其實也不是很大啦,不過當你有很多的中文字型檔的時候可能就不知道要選哪一個,啟動IReport後,開啟報表後會發現左邊下拉選單中,最下面的字型清單中有出現方框,顯示不出該字型的名稱,這幾個字型應該是判斷新細明體,標楷體及細明體,如下圖 下載IReport的Source Code來檢查一下,it.businesslogic.ireport.gui.MainFrame發現這個JComboBox有特別設定Arial字型,當然只要是中文的都顯示不出來ㄚ,所以點掉這一行後重新編譯,嘿嘿就可以了。 jComboBoxFont.setFont(new java.awt.Font("Arial", 0, 11)); 我目前使用的版本為 IReport-3.0.0-src