跳到主要內容

玩玩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;
}
}


留言

這個網誌中的熱門文章

IReport中的條碼類別BcImage

最近有一個繳費單的專案,需要列印條碼,因為IReport本身就有提供列印條碼的功能,所以就用IReport設計繳費單然後再用Jasperreport API寫批次程式去產生PDF,資料量大概3000多筆(頁)拆成幾個檔案,可是就發生了一個問題居然發生部分繳費單的條碼有問題,看了一下程式研判是Race Condition因為程式採用的是多執行緒,若是依序個別產生是不會有問題,但是同時執行的時候就會亂掉,而且都錯在條碼,令我覺得很奇怪,後來我查了一下發現it.businesslogic.ireport.barcode.BcImage 類別我猜是這裡的問題,就先加上synchronized重新編譯在去執行,嘿嘿條碼就對了,做了一下壓測也正常,程式碼如下,不過這樣事不是對了可能還要仔細查查看。 public class BcImage { private static net.sourceforge.barbecue.Barcode bc = null; public synchronized static net.sourceforge.barbecue.Barcode getBarcode() { return bc; } public synchronized static BufferedImage getBarcodeImage(int type, Object aText, boolean showText, boolean checkSum) { return getBarcodeImage(type, aText, showText, checkSum,"",0,0); } public synchronized static BufferedImage getBarcodeImage(int type, Object aText, boolean showText, boolean checkSum, String applicationIdentifier, int width, int height) { // 2of7, 3of9, Bookland, Codabar, Code128,...

Ext-Js Grid + DWR

Ext-Js中有Grid的sample,想說試試看加上DWR的效果如何?感覺上還不錯,以下是我參考Ext-Js附的grid array sample,加上DWR調整一下的code,我想可能還要加上資料在Loading的效果會比較好。 array-grid.js Ext.onReady(function(){ Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // example of custom renderer function function change(val){ if(val > 0){ return ' ' + val + ' '; }else if(val ' + val + ' '; } return val; } // example of custom renderer function function pctChange(val){ if(val > 0){ return ' ' + val + '% '; }else if(val ' + val + '% '; } return val; } //要設定Dwr傳回的Map的對應格式 var recordType = Ext.data.Record.create( [ {name:"reportid",mapping:"reportid",type:"string"}, {name:"reportName",mapping:"reportName",type:"string"} ] ); var myReader = new Ext.data.JsonReader( { totalProperty:"totalSize", root:"data" },recordType ); // create the data store //這裡是很重要的,這裡還可以加上listener等等的屬性喔 var store = new Ext.da...

IBM MQ 5.3 Server安裝在RHEL 4

最近在整理一些文件,整理出來一些IBM MQ相關的文件,因為相關專案都是自己來開發,所以有些文件我個人覺得還滿有價值,其實安裝IBM MQ Server在RHEL還滿簡單的,只要注意幾個關鍵點,還有就是不要用光碟中的JRE就順多了,這個問題我有問過IBM,得到的答案是建議安裝Sun的JRE會比較好,真得讓我......步驟如下 1.先安裝RHEL 4 這裡就省略不說了 2.於Sun網站下載For Linux J2SDK1.4.2以上版本,建議下載.bin版本。進行安裝: 2.1 執行./xxx.bin,會自動解壓縮出xxx.rpm 2.2 rpm -ivh xxx.rpm 2.3 會詢問安裝目錄,請依需求安裝這裡為預設。 2.4 安裝完成後,調整/etc/profile檔案,設定JAVA_HOME指定到J2SDK安裝的目錄,並將J2SDK的bin目錄加入path中。 3.安裝IBM MQ 3.1安裝MQ需先進行License安裝,否則安裝程式不會執行,因光碟中提供的mqlicense.sh,IBM已有提供更新版,故建議下載IBM網站提供的update版本進行安裝。 ※mqlicense.sh一樣也要設定權限,chmod 755 mqlicense.sh 3.2安裝完後的license會在/tmp下建立一license的目錄所以要注意/tmp需要開777的權限Chmod 777 –R /tmp 3.3先設定變數(可以設定/etc/profile) Export LD_ASSUME_KERNEL=2.4.19 Export RPM_FORCE_NPTL=1 3.4依據下列順序安裝: rpm -i MQSeriesRuntime-5.3.0-1.i386.rpm rpm -i MQSeriesSDK-5.3.0-1.i386.rpm rpm -i MQSeriesServer-5.3.0-1.i386.rpm 3.5安裝後需要進行下列環境變數設定方可使用MQ ln –sf /opt/mqm/lib/xxx/* /opt/m...