Created
March 6, 2012 05:05
-
-
Save smd877/1983710 to your computer and use it in GitHub Desktop.
Javaの暗号化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.spec.SecretKeySpec; | |
import org.apache.commons.codec.DecoderException; | |
import org.apache.commons.codec.binary.Hex; | |
public class BlowfishTest { | |
public static final String ALGORITHM = "Blowfish"; | |
public static void main(String[] args) { | |
try { | |
// 暗号キー | |
String key = "testtest"; | |
// 暗号化したい文字列 | |
String text = "ここに暗号化したい文字列を入力"; | |
// 暗号化した文字列 | |
String strEncrypt = encrypt(key, text); | |
// 複合化した文字列(=text) | |
String strDecrypt = decrypt(key, strEncrypt); | |
} | |
catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* 暗号化処理 | |
* | |
* @param key 暗号キー | |
* @param text 暗号化したい文字列 | |
* @return 暗号化した文字列 | |
* @throws NoSuchAlgorithmException | |
* @throws NoSuchPaddingException | |
* @throws InvalidKeyException | |
* @throws IllegalBlockSizeException | |
* @throws BadPaddingException | |
*/ | |
public static String encrypt(String key, String text) throws NoSuchAlgorithmException, NoSuchPaddingException, | |
InvalidKeyException, IllegalBlockSizeException, BadPaddingException { | |
SecretKeySpec sksSpec = new SecretKeySpec(key.getBytes(), ALGORITHM); | |
Cipher cipher = Cipher.getInstance(ALGORITHM); | |
cipher.init(Cipher.ENCRYPT_MODE, sksSpec); | |
byte[] encrypted = cipher.doFinal(text.getBytes()); | |
return new String(Hex.encodeHex(encrypted)); | |
} | |
/** | |
* 複合化処理 | |
* | |
* @param key 暗号キー | |
* @param text 複合化したい文字列 | |
* @return 暗号化した文字列 | |
* @throws DecoderException | |
* @throws NoSuchAlgorithmException | |
* @throws NoSuchPaddingException | |
* @throws InvalidKeyException | |
* @throws IllegalBlockSizeException | |
* @throws BadPaddingException | |
*/ | |
public static String decrypt(String key, String text) throws DecoderException, NoSuchAlgorithmException, | |
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { | |
byte[] encrypted = Hex.decodeHex(text.toCharArray()); | |
SecretKeySpec sksSpec = new SecretKeySpec(key.getBytes(), ALGORITHM); | |
Cipher cipher = Cipher.getInstance(ALGORITHM); | |
cipher.init(Cipher.DECRYPT_MODE, sksSpec); | |
byte[] decrypted = cipher.doFinal(encrypted); | |
return new String(decrypted); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment