数据加密相关
来源:互联网 发布:worktile类似软件 编辑:程序博客网 时间:2024/06/11 18:51
DES加解密
import java.security.InvalidAlgorithmParameterException;import java.security.Key;import java.security.spec.AlgorithmParameterSpec;import javax.crypto.Cipher;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import javax.crypto.spec.IvParameterSpec;/** * DES加解密工具类 不常用了 */public class DESUtils { public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding"; /** * 设定加密私钥 长度不能够小于8位 */ public static final String KEY = "dsadadsasdsad"; /** * DES算法,加密 * * @param data * 待加密字符串 * @return 加密后的字节数组,一般结合Base64编码使用 * @throws InvalidAlgorithmParameterException * @throws Exception */ public static String encode(String data) { if (data == null) return null; try { DESKeySpec dks = new DESKeySpec(KEY.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // key的长度不能够小于8位字节 Key secretKey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance(ALGORITHM_DES); IvParameterSpec iv = new IvParameterSpec("12345678".getBytes()); AlgorithmParameterSpec paramSpec = iv; cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec); byte[] bytes = cipher.doFinal(data.getBytes()); return byte2hex(bytes); } catch (Exception e) { e.printStackTrace(); return data; } } /** * DES算法,解密 * * @param data * 待解密字符串 * @param key * 解密私钥,长度不能够小于8位 * @return 解密后的字节数组 * @throws Exception * 异常 */ public static String decode(String data) { if (data == null) return null; try { DESKeySpec dks = new DESKeySpec(KEY.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // key的长度不能够小于8位字节 Key secretKey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance(ALGORITHM_DES); IvParameterSpec iv = new IvParameterSpec("12345678".getBytes()); AlgorithmParameterSpec paramSpec = iv; cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec); return new String(cipher.doFinal(hex2byte(data.getBytes()))); } catch (Exception e) { e.printStackTrace(); return data; } } /** * 二行制转字符串 * * @param b * @return */ private static String byte2hex(byte[] b) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; b != null && n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toUpperCase(); } private static byte[] hex2byte(byte[] b) { if ((b.length % 2) != 0) throw new IllegalArgumentException(); 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; }}
3DES加解密
/** * 3重DES加密 * @param src * @param DES_KEY 密钥长度不少于24的倍数位 * @return */public static String EncryptBy3DES(String src,String DES_KEY){ String result=null; try { SecureRandom secureRandom=new SecureRandom(); DESedeKeySpec sedeKeySpec=new DESedeKeySpec(DES_KEY.getBytes()); SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance("DESede"); SecretKey key=secretKeyFactory.generateSecret(sedeKeySpec); Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE,key,secureRandom); byte[] bytesresult=cipher.doFinal(src.getBytes()); result=new sun.misc.BASE64Encoder().encode(bytesresult); } catch (Exception e) { e.printStackTrace(); } return result;}/** * 3重DES解密 * @param src * @param DES_KEY * @return */public static String decryptBy3DES(String src,String DES_KEY){ String deresult=null; try { SecureRandom secureRandom=new SecureRandom(); DESedeKeySpec sedeKeySpec=new DESedeKeySpec(DES_KEY.getBytes()); SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance("DESede"); SecretKey key = secretKeyFactory.generateSecret(sedeKeySpec); Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE,key,secureRandom); byte[] bytesresult=cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(src)); deresult=new String(bytesresult); } catch (Exception e) { e.printStackTrace(); } return deresult;}测试:public class DES_3 { //定义一个要加密的字符串 private static String src="imooc security 3des"; public static void main(String[] args) { //调用加密的方法并打印查看结果 System.out.println(EncryptBy3DES(src,"123456781234567812345678")); //将加密后的结果放入解密的方法,由于是对称加密,因此加解密的密钥都是同一个 System.out.println(decryptBy3DES("lA/dMJvyrb2Q/BtmUKPPEdNwn5+TwCxA","123456781234567812345678")); }}
AES加解密
import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec; /** * AES加解密 */public class AESUtil { static final public byte[] KEY_VI = { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 }; public static final String bm = "UTF-8"; /** * 加密 * * @param cleartext * 明文 * @param dataPassword * 密钥 16位 * @return 加密后的字符串 * @throws Exception */ public static String encrypt(String cleartext, String dataPassword) throws Exception { IvParameterSpec zeroIv = new IvParameterSpec(KEY_VI); SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv); byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm)); return new String(parseByte2HexStr(encryptedData)); } /** * 解密 * * @param encrypted * 加密后的字符串 * @param dataPassword * 密钥 * @return 解密后的字符串 * @throws Exception */ public static String decrypt(String encrypted, String dataPassword) throws Exception { byte[] byteMi = parseHexStr2Byte(encrypted); IvParameterSpec zeroIv = new IvParameterSpec(KEY_VI); SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, zeroIv); byte[] decryptedData = cipher.doFinal(byteMi); return new String(decryptedData, bm); } /** * 将16进制转换为二进制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } /** * 将二进制转换成16进制 * * @param buf * @return */ public static String parseByte2HexStr(byte buf[]) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); }}
AES文件加解密
/** * 文件AES加解密工具类 * eg. 图片 视频 文件 */public class FileUtils { /** * AES加密使用的秘钥,注意的是秘钥的长度必须是16位 */ private static final String AES_KEY = "MyDifficultPassw"; /** * 使用AES加密标准进行加密 * * @param filePath 待加密的图片路径 * @param outPath AES加密后的文件的输出路径 * eg. Environment.getExternalStorageDirectory().getPath()+ "/test/encrypt.jpg"; * @return 返回true表示加密成功 */ public static Boolean aesEncrypt(String filePath, String outPath) { try { FileInputStream fis = null; fis = new FileInputStream(filePath); FileOutputStream fos = new FileOutputStream(outPath); //SecretKeySpec此类来根据一个字节数组构造一个 SecretKey SecretKeySpec sks = new SecretKeySpec(AES_KEY.getBytes(), "AES"); //Cipher类为加密和解密提供密码功能,获取实例 Cipher cipher = Cipher.getInstance("AES"); //初始化 cipher.init(Cipher.ENCRYPT_MODE, sks); //CipherOutputStream 为加密输出流 CipherOutputStream cos = new CipherOutputStream(fos, cipher); int b; byte[] d = new byte[1024]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } cos.flush(); cos.close(); fis.close(); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * 使用AES标准解密 * * @param path 待解密的文件路径路径 * @param finalPath 解密后的输出文件路径 */ public static void aesDecrypt(String path, String finalPath) { try { FileInputStream fis = null; fis = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); SecretKeySpec sks = new SecretKeySpec(AES_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); //CipherInputStream 为加密输入流 CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[1024]; while ((b = cis.read(d)) != -1) { out.write(d, 0, b); } out.flush(); out.close(); cis.close(); //获取字节流 byte[] bytes = out.toByteArray(); FileOutputStream fos = new FileOutputStream(new File(finalPath)); fos.write(bytes); fos.close(); } catch (Exception e) { e.printStackTrace(); } }}
视频文件快速加解密
/** * 视频快速加密工具类 * 通过异或视频头让播放器无法识别 */public class VideoUtils { /** * 要异或的字节长度 */ private static final int REVERSE_LENGTH = 100; /** * 加解密 * 播放前解密 播放后加密 时间短 * @param srcPath 源文件绝对路径 * @return */ public static boolean encrypt(String srcPath) { int len = REVERSE_LENGTH; try { File f = new File(srcPath); RandomAccessFile raf = new RandomAccessFile(f, "rw"); long totalLen = raf.length(); if (totalLen < REVERSE_LENGTH) len = (int) totalLen; FileChannel channel = raf.getChannel(); MappedByteBuffer buffer = channel.map( FileChannel.MapMode.READ_WRITE, 0, REVERSE_LENGTH); byte tmp; for (int i = 0; i < len; ++i) { byte rawByte = buffer.get(i); tmp = (byte) (rawByte ^ i); buffer.put(i, tmp); } buffer.force(); buffer.clear(); channel.close(); raf.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }}
MD5加密
/** * MD5工具类 */public class MD5Utils { private static final char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static String hexdigest(String string) { String s = null; try { s = hexdigest(string.getBytes()); } catch (Exception var3) { var3.printStackTrace(); } return s; } public static String hexdigest(byte[] bytes) { String s = null; try { MessageDigest e = MessageDigest.getInstance("MD5"); e.update(bytes); byte[] tmp = e.digest(); char[] str = new char[32]; int k = 0; for (int i = 0; i < 16; ++i) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 15]; str[k++] = hexDigits[byte0 & 15]; } s = new String(str); } catch (Exception var8) { var8.printStackTrace(); } return s; }}
RSA非对称加密
import java.io.ByteArrayOutputStream;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.PrivateKey;import java.security.PublicKey;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.InvalidKeySpecException;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import javax.crypto.Cipher;/** * RSA工具类 */public class RSAUtils { private static String RSA = "RSA"; /** * 随机生成RSA密钥对(默认密钥长度为1024) * * @return */ public static KeyPair generateRSAKeyPair() { return generateRSAKeyPair(1024); } /** * 随机生成RSA密钥对 * * @param keyLength 密钥长度,范围:512~2048 * 一般1024 * @return 密钥对 */ public static KeyPair generateRSAKeyPair(int keyLength) { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA); kpg.initialize(keyLength); return kpg.genKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * 用公钥加密 * 每次加密的字节数,不能超过密钥的长度值除以 8 再减去 11,所以采取分段加密的方式规避 * * @param dataStr 待加密的字符串 * @param publicKeyStr 公钥字符串 * @return 密文 */ public static String encryptData(String dataStr, String publicKeyStr) { byte[] data = dataStr.getBytes(); try { PublicKey publicKey = getPublicKeyByStr(publicKeyStr); Cipher cipher = Cipher.getInstance(RSA); // 编码前设定编码方式及密钥 cipher.init(Cipher.ENCRYPT_MODE, publicKey); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; // 模长 int keyLen = rsaPublicKey.getModulus().bitLength() / 8; int maxEncryptBlock = keyLen - 11; //如果明文长度大于模长-11则要分组加密 int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] temp; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > maxEncryptBlock) { temp = cipher.doFinal(data, offSet, maxEncryptBlock); } else { temp = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(temp, 0, temp.length); i++; offSet = i * maxEncryptBlock; } byte[] encryptedData = out.toByteArray(); out.close(); // 传入编码数据并返回编码结果 String result = Base64Utils.encode(encryptedData); return result; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 用私钥解密 * * @param encryptedData 密文 * @param privateKeyStr 私钥字符串 * @return 明文 */ public static String decryptData(String encryptedData, String privateKeyStr) { PrivateKey privateKey = getPrivateKeyByStr(privateKeyStr); try { byte[] bytes = Base64Utils.decode(encryptedData); Cipher cipher = Cipher.getInstance(RSA); cipher.init(Cipher.DECRYPT_MODE, privateKey); RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey; // 模长 int keyLen = rsaPrivateKey.getModulus().bitLength() / 8; int maxDecryptBlock = keyLen;//不用减11 //如果密文长度大于模长则要分组解密 int inputLen = bytes.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] temp; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > maxDecryptBlock) { temp = cipher.doFinal(bytes, offSet, maxDecryptBlock); } else { temp = cipher.doFinal(bytes, offSet, inputLen - offSet); } out.write(temp, 0, temp.length); i++; offSet = i * maxDecryptBlock; } byte[] decryptedData = out.toByteArray(); out.close(); String result = new String(decryptedData); return result; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根据生成的密钥对获得私钥 * * @param keyPair 生成的密钥对 * @return 私钥字符串 */ public static String getPrivateKey(KeyPair keyPair) { PrivateKey aPrivate = keyPair.getPrivate(); byte[] encoded = aPrivate.getEncoded(); String result = Base64Utils.encode(encoded); return result; } /** * 根据生成的密钥对获得获得公钥 * * @param keyPair 生成的密钥对 * @return 公钥字符串 */ public static String getPublicKey(KeyPair keyPair) { PublicKey aPublic = keyPair.getPublic(); byte[] encoded = aPublic.getEncoded(); String result = Base64Utils.encode(encoded); return result; } /** * 根据字符串得到公钥 * * @param key 密钥字符串(经过base64编码) * @return 公钥 */ public static PublicKey getPublicKeyByStr(String key) { byte[] keyBytes = Base64Utils.decode(key); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = null; try { keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; } /** * 根据私钥字符串得到私钥 * * @param key 密钥字符串(经过base64编码) * @return 私钥 */ public static PrivateKey getPrivateKeyByStr(String key) { byte[] keyBytes; keyBytes = Base64Utils.decode(key); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = null; try { keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; }}
/** * BASE64工具类 */public class Base64Utils { private static char[] base64EncodeChars = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; private static byte[] base64DecodeChars = new byte[] {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1}; /** * 加密 * * @param data * @return */ public static String encode(byte[] data) { StringBuffer sb = new StringBuffer(); int len = data.length; int i = 0; int b1, b2, b3; while (i < len) { b1 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[(b1 & 0x3) << 4]); sb.append("=="); break; } b2 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); sb.append("="); break; } b3 = data[i++] & 0xff; sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]); sb.append(base64EncodeChars[b3 & 0x3f]); } return sb.toString(); } /** * 解密 * * @param str * @return */ public static byte[] decode(String str) { try { return decodePrivate(str); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return new byte[] {}; } private static byte[] decodePrivate(String str) throws UnsupportedEncodingException { StringBuffer sb = new StringBuffer(); byte[] data = null; data = str.getBytes("US-ASCII"); int len = data.length; int i = 0; int b1, b2, b3, b4; while (i < len) { do { b1 = base64DecodeChars[data[i++]]; } while (i < len && b1 == -1); if (b1 == -1) break; do { b2 = base64DecodeChars[data[i++]]; } while (i < len && b2 == -1); if (b2 == -1) break; sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4))); do { b3 = data[i++]; if (b3 == 61) return sb.toString().getBytes("iso8859-1"); b3 = base64DecodeChars[b3]; } while (i < len && b3 == -1); if (b3 == -1) break; sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); do { b4 = data[i++]; if (b4 == 61) return sb.toString().getBytes("iso8859-1"); b4 = base64DecodeChars[b4]; } while (i < len && b4 == -1); if (b4 == -1) break; sb.append((char) (((b3 & 0x03) << 6) | b4)); } return sb.toString().getBytes("iso8859-1"); }}
测试代码
KeyPair keyPair = RSAUtils.generateRSAKeyPair(); String privateStr = RSAUtils.getPrivateKey(keyPair); String publicStr = RSAUtils.getPublicKey(keyPair); Log.e("获得公钥:", privateStr); Log.e("获得私钥:", publicStr); Log.e("MainActivity", "------------------------这是一条华丽的分割线---------------------------------------"); String s = RSAUtils.encryptData("这是要加密的内容", publicStr); Log.e("公钥加密后的内容为:", s); String result = RSAUtils.decryptData(s, privateStr); Log.e("私钥解密后的内容为:", result);
阅读全文
0 0
- 数据加密相关
- 加密相关
- 数据加密的相关概念以及与数据加密有关的
- 加密数据共享移动设备及相关程序研发成功
- 数据公钥加密和认证中的私钥公钥相关总结
- 数据加密
- 数据加密
- 数据加密
- 数据加密
- 数据加密
- 数据加密
- 数据加密
- 数据加密
- 数据加密
- 加密数据
- 数据加密
- 数据加密
- 数据加密
- 计蒜客 微软大楼设计方案(中等)
- windows下多版本python环境变量设置与pip不同版本方法(三步骤)
- 浅谈 C# ref 和 out 的使用方法
- 【SLAM】同时定位与地图创建在无人车领域的应用探索
- HAWQ取代传统数仓实践(十四)——事实表技术之累积快照
- 数据加密相关
- 外媒:微信正在吃掉中国互联网,但这并不是一件好事
- 21. Merge Two Sorted Lists
- web service 工作原理
- Android常用控件三之按钮、选择框
- 使用HTML5的Server-sent技术,Go服务器向页面推送消息
- RestFul接口调试返回对应编码结果
- 树和二叉树基本概念以及二叉树遍历
- Spring 拦截器