public class Encryptor { public static String encrypt(String seed, String cleartext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } public static String decrypt(String seed, String encrypted) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); sr.setSeed(seed); kgen.init(128, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; } private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec,new IvParameterSpec(new byte[cipher.getBlockSize()])); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec,new IvParameterSpec(new byte[cipher.getBlockSize()])); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } private static String toHex(String txt) { return toHex(txt.getBytes()); } private static String fromHex(String hex) { return new String(toByte(hex)); } private static byte[] toByte(String hexString) { int len = hexString.length()/2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue(); return result; } private static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2*buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private final static String HEX = "0123456789ABCDEF"; private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f)); } }
//Base64加密
public static String encodeSN(String str) { //String str = id; String strBase64 = new String(Base64.encode(str.getBytes(), Base64.DEFAULT)); String encode = parseAscii(strBase64.substring(0, strBase64.length() - 3)); try { return URLEncoder.encode(parseString(encode), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String parseString(String s) { //String s = code; StringBuilder result = new StringBuilder(); String[] chars = s.split(" "); for (String str : chars) { //for (int i = 0; i < chars.length; i++) { L.i(TAG, "" + str + " " + (char) Integer.parseInt(str, 16)); result.append((char) Integer.parseInt(str, 16)); } return result.toString(); } public static String parseAscii(String str) { StringBuilder sb = new StringBuilder(); byte[] bs = str.getBytes(); for (byte b : bs) { //for (int i = 0; i < bs.length; i++) { sb.append(toHex(160 - b)); sb.append(" "); } return sb.toString(); } public static String toHex(int n) { StringBuilder sb = new StringBuilder(); if (n / 16 == 0) { return toHexUtil(n); } else { String t = toHex(n / 16); int nn = n % 16; sb.append(t).append(toHexUtil(nn)); } return sb.toString(); } private static String toHexUtil(int n) { String rt; switch (n) { case 10: rt = "A"; break; case 11: rt = "B"; break; case 12: rt = "C"; break; case 13: rt = "D"; break; case 14: rt = "E"; break; case 15: rt = "F"; break; default: rt = "" + n; break; } return rt; }
import java.security.InvalidKeyException; import java.security.Key; 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.binary.Base64; public class DES { public DES() { } public static DES getInstance(String key) throws NoSuchPaddingException, NoSuchAlgorithmException { return getInstance(getKeyByStr(key)); } public static DES getInstance(byte key[]) throws NoSuchPaddingException, NoSuchAlgorithmException { DES des = new DES(); if (des.key == null) { SecretKeySpec spec = new SecretKeySpec(key, "DES"); des.key = spec; } des.cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); return des; } public byte[] encrypt(byte b[]) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalStateException { byte byteFina[] = null; cipher.init(1, key); byteFina = cipher.doFinal(b); return byteFina; } public byte[] decrypt(byte b[]) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalStateException { byte byteFina[] = null; cipher.init(2, key); byteFina = cipher.doFinal(b); return byteFina; } public static byte[] getKeyByStr(String str) { byte bRet[] = new byte[str.length() / 2]; for (int i = 0; i < str.length() / 2; i++) { Integer itg = new Integer(16 * getChrInt(str.charAt(2 * i)) + getChrInt(str.charAt(2 * i + 1))); bRet[i] = itg.byteValue(); } return bRet; } private static int getChrInt(char chr) { int iRet = 0; if (chr == "0".charAt(0)) iRet = 0; if (chr == "1".charAt(0)) iRet = 1; if (chr == "2".charAt(0)) iRet = 2; if (chr == "3".charAt(0)) iRet = 3; if (chr == "4".charAt(0)) iRet = 4; if (chr == "5".charAt(0)) iRet = 5; if (chr == "6".charAt(0)) iRet = 6; if (chr == "7".charAt(0)) iRet = 7; if (chr == "8".charAt(0)) iRet = 8; if (chr == "9".charAt(0)) iRet = 9; if (chr == "A".charAt(0)) iRet = 10; if (chr == "B".charAt(0)) iRet = 11; if (chr == "C".charAt(0)) iRet = 12; if (chr == "D".charAt(0)) iRet = 13; if (chr == "E".charAt(0)) iRet = 14; if (chr == "F".charAt(0)) iRet = 15; return iRet; } private Key key; private Cipher cipher; /** * @interpret 进行base64加密操作 * @param text * @param keyString * @return String */ public String encrypt(String text, String keyString) { String body = null; try { DES des = DES.getInstance(keyString); byte[] b = des.encrypt(text.getBytes("UTF8")); body = new String(Base64.encodeBase64(b)); } catch (Exception ex) { } return body; } /** * @interpret 进行base64进行解密 * @param text * @param keyString * @return String */ public String decrypt(String text, String keyString) { String body = null; try { DES des = DES.getInstance(keyString); byte[] b = Base64.decodeBase64(text.getBytes()); body = new String(des.decrypt(b), "UTF8"); } catch (Exception e) { e.printStackTrace(); } return body; } /** * * @param content 内容 * @param operation 加密或解密 * @param key 使用到的密钥:固定长度 * @return */ public String authcode(String content, String operation, String key){ String encontent = null; if (operation != null && operation.equals("DECODE")) { encontent = encrypt(content,key); } else if (operation != null && operation.equals("ENCODE")) { encontent = decrypt(content,key); } return encontent; } public static void main(String[] args) { DES des = new DES(); System.out.println(des.authcode("wewweewewew=","DECODE","0102030405060708"));//加密 System.out.println(des.authcode("d8fPhfd9JkW99p8aqhtVIA==","ENCODE","0102030405060708"));//解密 } }