宛若重生的gravatar头像
宛若重生 2014-07-23 17:07:52

有什么好的java加密解密方法,求共享

不只是对字符串,还有集合,json格式呀,等等多种格式的

所有回答列表(5)
最代码官方的gravatar头像
最代码官方  LV167 2014年7月23日
package com.zuidaima.util;

import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtilTest {

	private static final String AES = "AES";

	private static final String INVITE_CODE_KEY = "www.zuidaima.com";

	private static byte[] encrypt(byte[] src, String key) throws Exception {
		Cipher cipher = Cipher.getInstance(AES);
		SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);
		cipher.init(Cipher.ENCRYPT_MODE, securekey);
		return cipher.doFinal(src);
	}

	private static byte[] decrypt(byte[] src, String key) throws Exception {
		Cipher cipher = Cipher.getInstance(AES);
		SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);
		cipher.init(Cipher.DECRYPT_MODE, securekey);
		return cipher.doFinal(src);
	}

	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}

	private static byte[] hex2byte(byte[] b) {
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("invalid arg b:" + b);
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	public final static String decryptInviteCode(String data) {
		try {
			return new String(decrypt(hex2byte(data.getBytes()),
					INVITE_CODE_KEY));
		} catch (Exception e) {
		}
		return null;
	}

	public final static String encryptInviteCode(String password) {
		try {
			return byte2hex(encrypt(password.getBytes(), INVITE_CODE_KEY));
		} catch (Exception e) {
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
		Date now = new Date();
		System.out.println(now.toLocaleString());

		String inviteCode = AESUtilTest.encryptInviteCode(System
				.currentTimeMillis() + "_1");
		System.out.println("inviteCode  " + inviteCode);

		String des = AESUtilTest.decryptInviteCode(inviteCode);
		System.out.println(des);

	}
}

运行结果:

2014-7-23 22:03:30
inviteCode  511FA08748E4A0702EC8DF7F4D9B7CBA
1406124210578_1

注意,key必须是16位的,否则加密解密失败。

评论(0) 最佳答案
Stealth的gravatar头像
Stealth  LV6 2014年7月23日

可以自己写算法,然后根据自己加密的key再解出来就是了

holysir的gravatar头像
holysir  LV28 2014年7月28日

AES也可以解密的

一飞冲天Crystal的gravatar头像
一飞冲天Crystal  LV1 2014年8月1日

jAVA工具类写好了   比方MD5  直接调用吧

等待美丽的花儿的gravatar头像
等待美丽的花儿  LV7 2014年8月1日

你可以网上查一下,RSA非对称加密。。这个相对比较安全。

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友