Android中的AES256加密

AES256加密即密钥长度为256bit,加密过程中所需要的时间要比128bit多花40%,安全程度自然比128更加安全;

代码:

/**
	 * 说明: AES256加密
	 * 
	 * @param stringToEncode
	 *            明文
	 * @param keyString
	 *            密钥
	 * @return Bses64格式密文
	 */
	public static String AES256Encode(String stringToEncode, String keyString)
			throws NullPointerException {
		if (keyString.length() == 0 || keyString == null) {
			return null;
		}
		if (stringToEncode.length() == 0 || stringToEncode == null) {
			return null;
		}
		try {
			SecretKeySpec skeySpec = getKey(keyString);
			byte[] data = stringToEncode.getBytes("UTF8");
			final byte[] iv = new byte[16];
			Arrays.fill(iv, (byte) 0x00);
			IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
			String encrypedValue = Base64.encodeToString(cipher.doFinal(data),
					Base64.DEFAULT);
			return encrypedValue;
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 
	 * 说明 :AES256解密
	 * 
	 * @param text
	 *            Base64格式密文
	 * @param keyString
	 *            密钥
	 * @return String格式明文
	 */
	public static String AES256Decrypt(String text, String keyString) {
		// byte[] rawKey = getRawKey(key);
		if (keyString.length() == 0 || keyString == null) {
			return null;
		}
		if (text.length() == 0 || text == null) {
			return null;
		}
		try {
			SecretKey key = getKey(keyString);
			final byte[] iv = new byte[16];
			Arrays.fill(iv, (byte) 0x00);
			IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
			byte[] data = Base64.decode(text, Base64.DEFAULT);
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
			byte[] decrypedValueBytes = (cipher.doFinal(data));
			String decrypedValue = new String(decrypedValueBytes, "UTF-8");
			return decrypedValue;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 
	 * 说明 :将密钥转行成SecretKeySpec格式
	 * 
	 * @param password
	 *            16进制密钥
	 * @return SecretKeySpec格式密钥
	 */
	private static SecretKeySpec getKey(String password)
			throws UnsupportedEncodingException {
		// 如果为128将长度改为128即可
		int keyLength = 256;
		byte[] keyBytes = new byte[keyLength / 8];
		// explicitly fill with zeros
		Arrays.fill(keyBytes, (byte) 0x0);
		byte[] passwordBytes = toByte(password);
		int length = passwordBytes.length < keyBytes.length ? passwordBytes.length
				: keyBytes.length;
		System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
		SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
		return key;
	}

	/**
	 * 
	 * 说明 :随机生成一组AES密钥
	 * 
	 * @return 16进制AES密钥
	 */
	public static String getRawKey() {
		KeyGenerator kgen = null;
		SecureRandom sr = null;
		try {
			kgen = KeyGenerator.getInstance("AES");
			// SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法
			if (android.os.Build.VERSION.SDK_INT >= 17) {
				sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
			} else {
				sr = SecureRandom.getInstance("SHA1PRNG");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		kgen.init(256, sr); // 256 bits or 128 bits,192bits
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		String result = bytes2Hex(raw);
		return result;
	}

	/**
	 * byte数组转换为16进制字符串
	 * 
	 * @param bts
	 *            数据源
	 * @return 16进制字符串
	 */
	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	/**
	 * 将16进制转换为byte数组
	 * 
	 * @param hexString
	 *            16进制字符串
	 * @return byte数组
	 */
	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;
	}


  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以!以下是一个示例的完整代码,用于在Android使用Java实现AES加密和解密: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; public class AESUtil { private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String CHARSET = "UTF-8"; private static byte[] encrypt(byte[] key, byte[] initVector, byte[] value) { try { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); return cipher.doFinal(value); } catch (Exception e) { e.printStackTrace(); } return null; } private static byte[] decrypt(byte[] key, byte[] initVector, byte[] encrypted) { try { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); return cipher.doFinal(encrypted); } catch (Exception e) { e.printStackTrace(); } return null; } public static String encrypt(String key, String initVector, String value) { try { byte[] encrypted = encrypt(key.getBytes(CHARSET), initVector.getBytes(CHARSET), value.getBytes(CHARSET)); return Base64.encodeToString(encrypted, Base64.DEFAULT); } catch (Exception e) { e.printStackTrace(); } return null; } public static String decrypt(String key, String initVector, String encrypted) { try { byte[] decoded = Base64.decode(encrypted, Base64.DEFAULT); byte[] decrypted = decrypt(key.getBytes(CHARSET), initVector.getBytes(CHARSET), decoded); return new String(decrypted, CHARSET); } catch (Exception e) { e.printStackTrace(); } return null; } } ``` 使用示例: ```java String key = "0123456789abcdef"; // 16字节的密钥 String initVector = "ABCDEF0123456789"; // 16字节的初始向量 String originalText = "Hello, AES!"; String encryptedText = AESUtil.encrypt(key, initVector, originalText); String decryptedText = AESUtil.decrypt(key, initVector, encryptedText); System.out.println("Original Text: " + originalText); System.out.println("Encrypted Text: " + encryptedText); System.out.println("Decrypted Text: " + decryptedText); ``` 请注意,这只是一个简单的示例代码,并不涵盖所有的错误处理和最佳实践。在实际使用,请根据需要进行适当的异常处理和安全性考虑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值