1.加密和解密php
2.对称加密和非对称加密java
3.关于单向加密android
4.加密和解密代码展现git
5.RSA非对称加解密github
身份认证算法
陌生人通讯segmentfault
支付宝支付加密数组
MD5安全
加密过程服务器
private final String desEncryptString = "yangchong"; private final String desEncryptKey = "19930311"; s1 = DES.encryptDES(desEncryptString, desEncryptKey); Log.e("加密和解密", s1); 加密和解密: 84r1gS+D3Op8yrSnF5ZDrQ== //s1为加密后的密文
解密过程
String s2 = DES.decryptDES(s1, desEncryptKey); Log.e("加密和解密", s2); //加密和解密: yangchong
public class DES { //初始化向量,随意填写 private static byte[] iv = {1,2,3,4,5,6,7,8}; /** * * @param encryptString 明文 * @param encryptKey 密钥 * @return 加密后的密文 */ public static String encryptDES(String encryptString,String encryptKey){ try { //实例化IvParameterSpec对象,使用指定的初始化向量 IvParameterSpec zeroIv=new IvParameterSpec(iv); //实例化SecretKeySpec,根据传入的密钥得到字节数组来构造SecretKeySpec SecretKeySpec key =new SecretKeySpec(encryptKey.getBytes(),"DES"); //建立密码器 Cipher cipher=Cipher.getInstance("DES/CBC/PKCS5Padding"); //用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE,key,zeroIv); //执行加密操做 byte[]encryptedData=cipher.doFinal(encryptString.getBytes()); return Base64.encodeToString(encryptedData,0); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } return null; } /** * 解密的过程与加密的过程大体相同 * @param decryptString 密文 * @param decryptKey 密钥 * @return 返回明文 */ public static String decryptDES(String decryptString,String decryptKey){ try { //先使用Base64解密 byte[]byteMi = Base64.decode(decryptString,0); //实例化IvParameterSpec对象使用指定的初始化向量 IvParameterSpec zeroIv=new IvParameterSpec(iv); //实例化SecretKeySpec,根据传入的密钥得到字节数组来构造SecretKeySpec, SecretKeySpec key=new SecretKeySpec(decryptKey.getBytes(),"DES"); //建立密码器 Cipher cipher=Cipher.getInstance("DES/CBC/PKCS5Padding"); //用密钥初始化Cipher对象,上面是加密,这是解密模式 cipher.init(Cipher.DECRYPT_MODE,key,zeroIv); //获取解密后的数据 byte [] decryptedData=cipher.doFinal(byteMi); return new String(decryptedData); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } return null; } }
public class AES { private static final String Algorithm = "AES"; private final static String HEX = "0123456789ABCDEF"; //加密函数,key为密钥 public static String encrypt(String key, String src) throws Exception { byte[] rawKey = getRawKey(key.getBytes()); byte[] result = encrypt(rawKey, src.getBytes()); return toHex(result); } //解密函数。key值必须和加密时的key一致 public static String decrypt(String key, String encrypted) throws Exception { byte[] rawKey = getRawKey(key.getBytes()); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); } private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance(Algorithm); // SHA1PRNG 强随机种子算法, 要区别Android 4.2.2以上版本的调用方法 SecureRandom sr = null; if (android.os.Build.VERSION.SDK_INT >= 17) { sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); } else { sr = SecureRandom.getInstance("SHA1PRNG"); } sr.setSeed(seed); kgen.init(256, sr); // 256位或128位或192位 SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; } private static byte[] encrypt(byte[] key, byte[] src) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, Algorithm); Cipher cipher = Cipher.getInstance(Algorithm); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(src); return encrypted; } private static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, Algorithm); Cipher cipher = Cipher.getInstance(Algorithm); 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 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(); } }
第一步:获取随机的公钥和私钥
//秘钥默认长度 public static final int DEFAULT_KEY_SIZE = 2048; KeyPair keyPair = RSA.generateRSAKeyPair(DEFAULT_KEY_SIZE); if (keyPair != null) { // 公钥 publicKey = (RSAPublicKey) keyPair.getPublic(); // 私钥 privateKey = (RSAPrivateKey) keyPair.getPrivate(); }
第二步:公钥加密
//用公钥对字符串进行加密 try { bytes = RSA.encryptByPublicKey(DEFAULT_SPLIT, publicKey.getEncoded()); String s = new String(bytes); Log.e("加密和解密", s); } catch (Exception e) { e.printStackTrace(); }
第三步:私钥解密
//使用私钥进行解密 try { byte[] bytes = RSA.decryptByPrivateKey(this.bytes, privateKey.getEncoded()); String s = new String(bytes); Log.e("加密和解密", s); //解密后获得的数据:yangchong } catch (Exception e) { e.printStackTrace(); }
第一步:获取随机的公钥和私钥
//秘钥默认长度 public static final int DEFAULT_KEY_SIZE = 2048; KeyPair keyPair = RSA.generateRSAKeyPair(DEFAULT_KEY_SIZE); if (keyPair != null) { // 公钥 publicKey = (RSAPublicKey) keyPair.getPublic(); // 私钥 privateKey = (RSAPrivateKey) keyPair.getPrivate(); }
第二步:私钥加密
//使用私钥加密 try { bytes1 = RSA.encryptByPrivateKey(DEFAULT_SPLIT, privateKey.getEncoded()); String s = new String(bytes); Log.e("加密和解密", s); } catch (Exception e) { e.printStackTrace(); }
第三步:公钥解密
//使用公钥解密 try { byte[] bytes = RSA.decryptByPublicKey(this.bytes1, publicKey.getEncoded()); String s = new String(bytes); Log.e("加密和解密", s); //解密后获得的数据:yangchong } catch (Exception e) { e.printStackTrace(); }
代码以下所示:
public class RSA { public static final String RSA = "RSA";// 非对称加密密钥算法 public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式 /**
* * @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; } } /*-------------------------------------------------------------------------------------------------*/ /** * 用公钥对字符串进行加密 * @param data 原文 * @param publicKey 密钥 * @return byte[] 解密数据 */ public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception { // 获得公钥 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); KeyFactory kf = KeyFactory.getInstance(RSA); PublicKey keyPublic = kf.generatePublic(keySpec); // 加密数据 Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING); cp.init(Cipher.ENCRYPT_MODE, keyPublic); return cp.doFinal(data); } /** * 私钥加密 * * @param data 待加密数据 * @param privateKey 密钥 * @return byte[] 解密数据 */ public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception { // 获得私钥 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey); KeyFactory kf = KeyFactory.getInstance(RSA); PrivateKey keyPrivate = kf.generatePrivate(keySpec); // 数据加密 Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING); cipher.init(Cipher.ENCRYPT_MODE, keyPrivate); return cipher.doFinal(data); } /** * 公钥解密 * * @param data 待解密数据 * @param publicKey 密钥 * @return byte[] 解密数据 */ public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception { // 获得公钥 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); KeyFactory kf = KeyFactory.getInstance(RSA); PublicKey keyPublic = kf.generatePublic(keySpec); // 数据解密 Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING); cipher.init(Cipher.DECRYPT_MODE, keyPublic); return cipher.doFinal(data); } /** * 使用私钥进行解密 * @param encrypted 待解密数据 * @param privateKey 密钥 * @return byte[] 解密数据 * @throws Exception 异常 */ public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception { // 获得私钥 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey); KeyFactory kf = KeyFactory.getInstance(RSA); PrivateKey keyPrivate = kf.generatePrivate(keySpec); // 解密数据 Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING); cp.init(Cipher.DECRYPT_MODE, keyPrivate); byte[] arr = cp.doFinal(encrypted); return arr; } } ```
第一步:获取随机的公钥和私钥
//秘钥默认长度 public static final int DEFAULT_KEY_SIZE = 2048; KeyPair keyPair = RSA.generateRSAKeyPair(DEFAULT_KEY_SIZE); if (keyPair != null) { // 公钥 publicKey = (RSAPublicKey) keyPair.getPublic(); // 私钥 privateKey = (RSAPrivateKey) keyPair.getPrivate(); }
第二步:用公钥对对象进行加密
//用公钥对对象进行加密 YC yc = new YC(); yc.setAge(25); yc.setName("杨充"); StringBuilder stringBuilder = new StringBuilder(); for(int a=0 ; a<500 ; a++){ stringBuilder.append("都比小杨"+a); } yc.setInfo(stringBuilder.toString()); String string = yc.toString(); long start = System.currentTimeMillis(); encryptBytes = new byte[0]; try { encryptBytes = RSA.encryptByPublicKeyForSpilt(string.getBytes(),publicKey.getEncoded()); } catch (Exception e) { e.printStackTrace(); } long end=System.currentTimeMillis(); Log.e("YC","公钥加密耗时 cost time---->"+(end-start)); String encryStr = new String(encryptBytes); Log.e("YC","加密前数据长度 --1-->"+string.length()); Log.e("YC","加密后数据长度 --1-->"+encryStr.length());
第三步:使用私钥进行解密
//使用私钥进行解密 long start2 = System.currentTimeMillis(); byte[] decryptBytes= new byte[0]; try { decryptBytes = RSA.decryptByPrivateKeyForSpilt(encryptBytes,privateKey.getEncoded()); } catch (Exception e) { e.printStackTrace(); } String decryStr = new String(decryptBytes); long end2 =System.currentTimeMillis(); Log.e("YC","私钥解密耗时 cost time---->"+(end2-start2)); Log.e("YC","解密后数据 --1-->"+decryStr);
第四步:加密和解密效率比较
代码以下所示
//秘钥默认长度 private static final int DEFAULT_KEY_SIZE = 2048; // 当前秘钥支持加密的最大字节数 private static final int DEFAULT_BUFFER_SIZE = (DEFAULT_KEY_SIZE / 8) - 11; // 当要加密的内容超过bufferSize,则采用partSplit进行分块加密 private static final byte[] DEFAULT_SPLIT = "#PART#".getBytes(); /** * 用公钥对字符串进行分段加密 * @param data 须要加密数据 * @param publicKey 公钥 * @return byte[] 加密数据 * @throws Exception 异常
*/ public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception { int dataLen = data.length; if (dataLen <= DEFAULT_BUFFER_SIZE) { return encryptByPublicKey(data, publicKey); } List<Byte> allBytes = new ArrayList<>(2048); int bufIndex = 0; int subDataLoop = 0; byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; for (int i = 0; i < dataLen; i++) { if (buf != null) { buf[bufIndex] = data[i]; } if (++bufIndex == DEFAULT_BUFFER_SIZE || i == dataLen - 1) { subDataLoop++; if (subDataLoop != 1) { for (byte b : DEFAULT_SPLIT) { allBytes.add(b); } } byte[] encryptBytes = encryptByPublicKey(buf, publicKey); for (byte b : encryptBytes) { allBytes.add(b); } bufIndex = 0; if (i == dataLen - 1) { buf = null; } else { buf = new byte[Math.min(DEFAULT_BUFFER_SIZE, dataLen - i - 1)]; } } } byte[] bytes = new byte[allBytes.size()]; int i = 0; for (Byte b : allBytes) { bytes[i++] = b; } return bytes; } /** * 用秘钥对字符串进行分段加密 * * @param data 要加密的原始数据 * @param privateKey 秘钥 * @return byte[] 加密数据 * @throws Exception 异常 * https://github.com/yangchong211 */ public static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception { int dataLen = data.length; if (dataLen <= DEFAULT_BUFFER_SIZE) { return encryptByPrivateKey(data, privateKey); } List<Byte> allBytes = new ArrayList<Byte>(2048); int bufIndex = 0; int subDataLoop = 0; byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; for (int i = 0; i < dataLen; i++) { if (buf != null) { buf[bufIndex] = data[i]; } if (++bufIndex == DEFAULT_BUFFER_SIZE || i == dataLen - 1) { subDataLoop++; if (subDataLoop != 1) { for (byte b : DEFAULT_SPLIT) { allBytes.add(b); } } byte[] encryptBytes = encryptByPrivateKey(buf, privateKey); for (byte b : encryptBytes) { allBytes.add(b); } bufIndex = 0; if (i == dataLen - 1) { buf = null; } else { buf = new byte[Math.min(DEFAULT_BUFFER_SIZE, dataLen - i - 1)]; } } } byte[] bytes = new byte[allBytes.size()]; int i = 0; for (Byte b : allBytes) { bytes[i++] = b; } return bytes; } /** * 用公钥分段解密 * * @param encrypted 待解密数据 * @param publicKey 公钥 * @return byte[] 解密数据 * @throws Exception 异常 * https://github.com/yangchong211 */ public static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception { int splitLen = DEFAULT_SPLIT.length; if (splitLen <= 0) { return decryptByPublicKey(encrypted, publicKey); } int dataLen = encrypted.length; List<Byte> allBytes = new ArrayList<Byte>(1024); int latestStartIndex = 0; for (int i = 0; i < dataLen; i++) { byte bt = encrypted[i]; boolean isMatchSplit = false; if (i == dataLen - 1) { // 到data的最后了 byte[] part = new byte[dataLen - latestStartIndex]; System.arraycopy(encrypted, latestStartIndex, part, 0, part.length); byte[] decryptPart = decryptByPublicKey(part, publicKey); for (byte b : decryptPart) { allBytes.add(b); } latestStartIndex = i + splitLen; i = latestStartIndex - 1; } else if (bt == DEFAULT_SPLIT[0]) { // 这个是以split[0]开头 if (splitLen > 1) { if (i + splitLen < dataLen) { // 没有超出data的范围 for (int j = 1; j < splitLen; j++) { if (DEFAULT_SPLIT[j] != encrypted[i + j]) { break; } if (j == splitLen - 1) { // 验证到split的最后一位,都没有break,则代表已经确认是split段 isMatchSplit = true; } } } } else { // split只有一位,则已经匹配了 isMatchSplit = true; } } if (isMatchSplit) { byte[] part = new byte[i - latestStartIndex]; System.arraycopy(encrypted, latestStartIndex, part, 0, part.length); byte[] decryptPart = decryptByPublicKey(part, publicKey); for (byte b : decryptPart) { allBytes.add(b); } latestStartIndex = i + splitLen; i = latestStartIndex - 1; } } byte[] bytes = new byte[allBytes.size()]; int i = 0; for (Byte b : allBytes) { bytes[i++] = b; } return bytes; } /** * 使用私钥分段解密 * * @param encrypted 待解密数据 * @param privateKey 私钥 * @return byte[] 解密数据 * @throws Exception 异常 * https://github.com/yangchong211 */ public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception { int splitLen = DEFAULT_SPLIT.length; if (splitLen <= 0) { return decryptByPrivateKey(encrypted, privateKey); } int dataLen = encrypted.length; List<Byte> allBytes = new ArrayList<Byte>(1024); int latestStartIndex = 0; for (int i = 0; i < dataLen; i++) { byte bt = encrypted[i]; boolean isMatchSplit = false; if (i == dataLen - 1) { // 到data的最后了 byte[] part = new byte[dataLen - latestStartIndex]; System.arraycopy(encrypted, latestStartIndex, part, 0, part.length); byte[] decryptPart = decryptByPrivateKey(part, privateKey); for (byte b : decryptPart) { allBytes.add(b); } latestStartIndex = i + splitLen; i = latestStartIndex - 1; } else if (bt == DEFAULT_SPLIT[0]) { // 这个是以split[0]开头 if (splitLen > 1) { if (i + splitLen < dataLen) { // 没有超出data的范围 for (int j = 1; j < splitLen; j++) { if (DEFAULT_SPLIT[j] != encrypted[i + j]) { break; } if (j == splitLen - 1) { // 验证到split的最后一位,都没有break,则代表已经确认是split段 isMatchSplit = true; } } } } else { // split只有一位,则已经匹配了 isMatchSplit = true; } } if (isMatchSplit) { byte[] part = new byte[i - latestStartIndex]; System.arraycopy(encrypted, latestStartIndex, part, 0, part.length); byte[] decryptPart = decryptByPrivateKey(part, privateKey); for (byte b : decryptPart) { allBytes.add(b); } latestStartIndex = i + splitLen; i = latestStartIndex - 1; } } byte[] bytes = new byte[allBytes.size()]; int i = 0; for (Byte b : allBytes) { bytes[i++] = b; } return bytes; } ```