본문 바로가기

TroubleShooting/Java

blowfish 를 이용한 문자열 인코딩/디코딩 예제

728x90

blowfish 를 이용해서 문자열을 인코딩/디코딩할 일이 있어서 공개된 정보들을 찾아서 정리해본다.

 

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class MyCrypto {
    private String myKey;

    public String getMyKey() {
        return myKey;
    }

    public void setMyKey(String myKey) {
        this.myKey = myKey;
    }

    public MyCrypto() {

    }

    /** 	 
     * @Method Name : encryptString 	 
     * 암호화할 데이터를 입력받고 암호화한 문자열을 반환 	 
     * @param myKey	암호키
     * @param data		암호화할 데이터
     * @return 	 
     */ 	
    public String encryptString(String myKey, String data) {
        byte[] encrypted;
        try {
            byte[] keyData = myKey.getBytes(); 			
            SecretKeySpec KS = new SecretKeySpec(keyData, "Blowfish");
            //			Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding"); 			
            Cipher cipher = Cipher.getInstance("Blowfish");
            cipher.init(Cipher.ENCRYPT_MODE, KS);
            encrypted = cipher.doFinal(data.getBytes()); 		
        } catch (Exception e) { 			
            return "error encrypting: " + e.getMessage(); 		
        } 		
        return bytesToHex(encrypted); 	
    } 	 	
        
    /** 	 
     * * @Method Name : decryptString 	 
     * * 인코딩된 문자열을 입력받고 복호화해서 원 문자열을 반환 	 
     * * @param myKey	암호키 	 
     * * @param decStr	디코딩할 데이터 	 
     * * @return 	 */ 	
    public String decryptString(String myKey, String decStr) { 		
        byte[] decrypted = null; 		
        try {
            byte[] keyData = myKey.getBytes();		
            byte[] decData = hexToBytes(decStr);
            SecretKeySpec KS = new SecretKeySpec(keyData, "Blowfish"); 
            //			Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding"); 			
            Cipher cipher = Cipher.getInstance("Blowfish"); 			
            cipher.init(Cipher.DECRYPT_MODE, KS); 			
            decrypted = cipher.doFinal(decData); 		
        } catch (Exception e) { 			
            return "error decrypt: " + e.getMessage(); 		
        } 		
        
        return new String(decrypted); 	
    }
        
    public String encryptString(String data) { 		
        byte[] encrypted; 		
        try { 			
            byte[] keyData = this.myKey.getBytes(); 			
            SecretKeySpec KS = new SecretKeySpec(keyData, "Blowfish"); 			
            Cipher cipher = Cipher.getInstance("Blowfish"); 			
            cipher.init(Cipher.ENCRYPT_MODE, KS); 			
            encrypted = cipher.doFinal(data.getBytes()); 		
        } catch (Exception e) { 			
            return "error encrypting: " + e.getMessage(); 		
        } 		
        return bytesToHex(encrypted); 	
    } 	 	
    
    public String decryptString(String decStr) { 		
        byte[] decrypted = null; 		
        try { 			
            byte[] keyData = this.myKey.getBytes(); 			
            byte[] decData = hexToBytes(decStr); 			
            SecretKeySpec KS = new SecretKeySpec(keyData, "Blowfish"); 			
            Cipher cipher = Cipher.getInstance("Blowfish"); 			
            cipher.init(Cipher.DECRYPT_MODE, KS); 			
            decrypted = cipher.doFinal(decData); 		
        } catch (Exception e) { 			
            return "error decrypt: " + e.getMessage(); 		
        } 		
        return new String(decrypted); 	
    } 	 	
    
    /** 	 
     * * @Method Name : hexToBytes 	 
     * * 문자열의 각 글자들의 ascii 값으로 byte 배열로  	 
     * * @param str 	 
     * * @return 	 
     * */ 	
    private static byte[] hexToBytes(String str) { 		
        if (str == null) { 			
            return null; 		
        } else if (str.length() < 2) { 			
            return null; 		
        } else { 			
            int len = str.length() / 2; 			
            byte[] buffer = new byte[len]; 			
            for (int i = 0; i < len; i++) { 				
                buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16); 			
            } 			
            return buffer; 		
        }  	
    }  	
    
    /** 	 
     * * @Method Name : bytesToHex 	 
     * * byte 배열의 각각의 값을 해당하는 ascii 문자로 변환해서 문자열로 반환 	 
     * * @param data 	 
     * * @return 	 
     * */ 	
    private static String bytesToHex(byte[] data) { 		
        if (data == null) { 			
            return null; 		
        } else { 			
            int len = data.length; 			
            String str = ""; 			
            for (int i = 0; i < len; i++) { 				
                if ((data[i] & 0xFF) < 16) 					
                    str = str + "0"	+ java.lang.Integer.toHexString(data[i] & 0xFF); 				
                else 					
                    str = str + java.lang.Integer.toHexString(data[i] & 0xFF); 			
            } 			
            return str.toUpperCase(); 		
        } 	
    } 
}

사용 예.

@Test
public void test() throws UnsupportedEncodingException {
    MyCrypto cryto = new MyCrypto(); 		 		
    String encData = crypto.encryptString("mykey", "가나다45라Ag");  		
    System.out.println("encrypted string:" + encData); 		 		
    
    String decData = ""; 		
    decData = crypto.decryptString("mykey", encData); 		
    System.out.println("decrypted data = " + decData); 	
}

 

참고 사이트:

http://dexxtr.com/post/57145943236/blowfish-encrypt-and-decrypt-in-java-android

http://stackoverflow.com/questions/15948662/decrypting-in-java-with-blowfish