首页 > 代码库 > Android加密算法之AES加密和解密实现
Android加密算法之AES加密和解密实现
<pre name="code" class="plain"><span style="font-family:Microsoft YaHei;font-size:18px;">前面写了常用了MD5加密算法,一个肯定不能满足本屌丝的胃口,最近发现AES加密算法貌似挺牛逼的样子,还是是美国联邦政府采用的一种区块高级加密标准,一看到“高级”就把我吓尿了,果然牛逼,废话少说,先学会用再说。</span>
/** * @param * @return AES加密算法加密 * @throws Exception */ public static String encrypt(String seed, String cleartext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } /** * @param * @return AES加密算法加密 * @throws Exception */ 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); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static String toHex(byte[] buf) { final String HEX = "0123456789ABCDEF"; if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { result.append(HEX.charAt((buf[i] >> 4) & 0x0f)).append( HEX.charAt(buf[i] & 0x0f)); } return result.toString(); } /** * @param raw * @param encrypted * @return AES加密算法解密 * @throws Exception */ 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[] decrypt(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } 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 byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); 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; }
测试代码:
<span style="font-family:Courier New;font-size:18px;"> String masterPassword = "test"; String originalText = "0123456789"; String encryptingCode = SimpleCrypto.encrypt(masterPassword,originalText); Log.i("加密结果为 ",encryptingCode); String decryptingCode = SimpleCrypto.decrypt(masterPassword, encryptingCode); Log.i("解密结果",decryptingCode); </span>
PS:AES属于对称加密方法,可破解有木有!
Android加密算法之AES加密和解密实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。