Skip to content

Instantly share code, notes, and snippets.

@ogis-ito
Created May 26, 2014 11:29
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ogis-ito/1ed91db2994bc1443682 to your computer and use it in GitHub Desktop.
EncryptUtils.java
package sandbox;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class EncryptUtils {
static final Charset UTF8 = Charset.forName("UTF-8");
static final char[] HEX = "0123456789abcdef".toCharArray();
static final String ALGORITHM = "Blowfish";
static final String TRANSFORMATION = "Blowfish";
public static String encrypt(String key, String text) {
return toHexString(encrypt(getBytes(key), getBytes(text)));
}
public static byte[] encrypt(byte[] key, byte[] text) {
try {
SecretKeySpec spec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, spec);
return cipher.doFinal(text);
} catch (Exception e) {
throw toRuntimeException(e);
}
}
public static String decrypt(String key, String encrypted) {
return toString(decrypt(getBytes(key), parseHexBytes(encrypted)));
}
public static byte[] decrypt(byte[] key, byte[] encrypted) {
try {
SecretKeySpec spec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, spec);
return cipher.doFinal(encrypted);
} catch (Exception e) {
throw toRuntimeException(e);
}
}
static byte[] getBytes(String text) {
return text.getBytes(UTF8);
}
static String toString(byte[] bytes) {
return new String(bytes, UTF8);
}
static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(2 * bytes.length);
for (int i = 0; i < bytes.length; ++i) {
byte n = bytes[i];
sb.append(HEX[(n >> 4) & 0xF]);
sb.append(HEX[n & 0xF]);
}
return sb.toString();
}
static byte[] parseHexBytes(String s) {
if (s.length() % 2 != 0) {
s = '0' + s;
}
int length = s.length();
ByteArrayOutputStream baos = new ByteArrayOutputStream(length / 2);
for (int i = 0; i < length; i += 2) {
baos.write(Integer.parseInt(s.substring(i, i + 2), 16));
}
return baos.toByteArray();
}
static RuntimeException toRuntimeException(Exception e) {
if (e instanceof RuntimeException) {
return (RuntimeException) e;
} else {
return new RuntimeException(e);
}
}
public static void main(String [] args) {
try {
String encrypted = encrypt(args[0], args[1]);
System.out.println("encrypted: " + encrypted);
String decrypted = decrypt(args[0], encrypted);
System.out.println("decrypted: " + decrypted);
} catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java EncryptUtils {key} {text}");
}
}
}
@ogis-ito
Copy link
Author

Java で暗号化/復号化の仕方。結構長くなった。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment