간혹 암호화가 필요할 때가 있다. 이 경우 사용가능한 대칭키 암호화에 사용되는 자바 유틸이다.
javax패키지를 사용하며 안드로이드에서 그대로 사용이 가능하다.
Base64는 안드로이드 오픈소스에서 가져다가 사용하였다.
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
public class CryptoUtil {
Cipher ecipher;
Cipher dcipher;
public CryptoUtil(SecretKey key, String algorithm) {
try {
ecipher = Cipher.getInstance(algorithm);
dcipher = Cipher.getInstance(algorithm);
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return Base64.encodeToString(enc, Base64.URL_SAFE|Base64.NO_WRAP);
//return String.valueOf(enc);
} catch (javax.crypto.BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = Base64.decode(str, Base64.URL_SAFE|Base64.NO_WRAP);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
// Generate a temporary key. In practice, you would save this key.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
CryptoUtil c = new CryptoUtil(key, "DES");
// Encrypt
String encrypted = c.encrypt("안녕하세요 이요삼입니다...");
System.out.println(encrypted);
// Decrypt
String decrypted = c.decrypt(encrypted);
System.out.println(decrypted);
}
}