public static String encrypt(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(input.getBytes("MS932"));
return toHexString(md.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
private static String toHexString(byte[] b) {
StringBuffer hexString = new StringBuffer();
String plainText=null;
for (int i = 0; i < b.length; i++) {
plainText = Integer.toHexString(0xFF & b[i]);
if (plainText.length() < 2) {
plainText = "0" + plainText;
}
hexString.append(plainText);
}
return new String(hexString);
}
public static void main(String[] args) {
String string = encrypt("kino");
System.out.println(string);
}
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* 「KEROKERO」という文字列を「TORI」というキーを使って暗号化する
* @author kero
*rahZRQ3GiNPeDa85P0NCwA==
*/
public class Test1 extends Base64 {
public static void main(String[] args) throws Exception {
Key skey = makeKey1(128);
// 暗号化
byte[] enc = encode1("KEROKERO".getBytes(), skey);
//System.out.println(encodeBase64(enc));
// 復号化
byte[] dec = decode1(decodeBase64("5ymWJSWsIvUyD7s6dUL4CA=="), skey);
System.out.println(new String(dec));
}
/**
* 秘密鍵をバイト列から生成する
* @param key_bits 鍵の長さ(ビット単位)
*/
public static Key makeKey1(int key_bits) {
// バイト列
byte[] key = new byte[key_bits / 8];
// バイト列の内容(秘密鍵の値)はプログラマーが決める
for (int i = 0; i < key.length; i++) {
key[i] = (byte) (i + 1);
}
return new SecretKeySpec(key, "AES");
}
/**
* 暗号化
*/
public static byte[] encode1(byte[] src, Key skey) {
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skey);
return cipher.doFinal(src);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 復号化
*/
public static byte[] decode1(byte[] src, Key skey) {
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skey);
return cipher.doFinal(src);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
public class Base64 {
public static String encodeBase64(byte[] data) throws Exception {
ByteArrayOutputStream forEncode = new ByteArrayOutputStream();
OutputStream toBase64 = MimeUtility.encode(forEncode, "base64");
toBase64.write(data);
toBase64.close();
return forEncode.toString("iso-8859-1");
}
public static byte[] decodeBase64(String base64) throws Exception {
InputStream fromBase64 = MimeUtility.decode(
new ByteArrayInputStream(base64.getBytes()), "base64");
byte[] buf = new byte[1024];
ByteArrayOutputStream toByteArray = new ByteArrayOutputStream();
for (int len = -1;(len = fromBase64.read(buf)) != -1;)
toByteArray.write(buf, 0, len);
return toByteArray.toByteArray();
}
public Base64() {
super();
}
}
最終更新:2011年06月06日 06:40