单项加密:md5 sha
双向加密:rsa(私钥+公钥) aes(密钥+iv偏移量) 填充算法
https://www.cnblogs.com/ppybear/p/12462449.html
Bouncy Castle Inc.公司提供的算法包,进行aes加密;方案1
package testMain; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.Key; import java.security.KeyFactory; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.PBEParametersGenerator; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator; import org.bouncycastle.crypto.macs.CFBBlockCipherMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.modes.CFBBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex; import com.bes.commons.codec.binary.Base64; import com.bes.enterprise.appserver.common.util.AES; import com.bes.enterprise.appserver.common.util.MD5Util; public class mmmm { private static final byte[] DEFAULT_IV = { -12, 56, -25, 63, 78, 32, 76, 89, 34, 76, -64, 88, -56, 23, 66, 11 }; private static final byte[] apiKey = {96, 26, 72, -105, 127, -48, 54, 39, -5, 74, -95, -64, -43, -3, -109, 85}; private static String PASSWORD = MD5Util.md5Str("BES9_5_0_2017"); private static final Base64 base64 = new Base64(); //private static String PPPPP= "AES/CBC/PKCS7Padding"; private static String PPPPP= "AES/CFB/PKCS5Padding"; public static void main(String[] args) throws Exception { System.out.println(PASSWORD.getBytes()); String password = "Basdasdas"; //jdk加密 String AESpassword = encrypt(password); System.out.println("jdk:" + AESpassword); //jdk:{AES}H/eSUbYWJQOYQp7rbNMrVQ== //{AES}jAF9c4oBeQF4agWl6HNkyQ== //BC加密 String encrypt = encrypt(password, apiKey); System.out.println("B C:" + encrypt); //BC解jdk的密 String encrypt1 = decrypt(AESpassword.substring("{AES}".length()), apiKey); System.out.println("B C解密jdk:" + encrypt1); //BC解bc的密 String encrypt2 = decrypt(encrypt, apiKey); System.out.println("B C解密bc:" + encrypt2); } //jdk public static String encrypt(String content) throws Exception { Cipher cipher = Cipher.getInstance(PPPPP); cipher.init(1, getSecretKey(), new IvParameterSpec(DEFAULT_IV)); byte[] rawCipherText = cipher.doFinal(content.getBytes()); return "{AES}" + new String(base64.encode(rawCipherText)); } public static String encrypt3(String content) throws Exception { Cipher cipher = Cipher.getInstance("PPPPP"); cipher.init(1, getSecretKey(), new IvParameterSpec(DEFAULT_IV)); byte[] rawCipherText = cipher.doFinal(content.getBytes()); return "{AES}" + new String(base64.encode(rawCipherText)); } public static String decrypt(String cipherText) throws Exception { Cipher cipher = Cipher.getInstance("PPPPP"); cipher.init(2, getSecretKey(), new IvParameterSpec(DEFAULT_IV)); byte[] rawData = cipherText.getBytes(); byte[] decryptData = base64.decode(new String(rawData, "{AES}".length(), rawData.length - "{AES}".length())); return new String(cipher.doFinal(decryptData)); } private static Key getSecretKey() throws Exception { SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec ps = new PBEKeySpec(PASSWORD.toCharArray(), PASSWORD.getBytes(), 1024, 128); SecretKey key = skf.generateSecret(ps); SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES"); return keySpec; } public static Key loadPublicKey(String stored) throws GeneralSecurityException, IOException { byte[] data = java.util.Base64.getDecoder().decode((stored.getBytes())); X509EncodedKeySpec spec = new X509EncodedKeySpec(data); KeyFactory fact = KeyFactory.getInstance("AES"); return fact.generatePublic(spec); } //bc public static String encrypt(String content, byte[] apiKey) throws Exception { if (apiKey == null) { throw new IllegalArgumentException("Key cannot be null!"); } String encrypted = null; if (apiKey.length != 32 && apiKey.length != 24 && apiKey.length != 16) { throw new IllegalArgumentException( "Key length must be 128/192/256 bits!"); } byte[] encryptedBytes = null; encryptedBytes = encrypt111(content.getBytes(), apiKey, DEFAULT_IV); encrypted = new String(base64.encode(encryptedBytes)); return encrypted; } private static byte[] encrypt111(byte[] plain, byte[] key, byte[] iv) throws Exception { PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new CFBBlockCipher(new AESEngine(), 128)); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(true, ivAndKey); return cipherData(aes, plain); } private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) throws Exception { int minSize = cipher.getOutputSize(data.length); byte[] outBuf = new byte[minSize]; int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0); int length2 = cipher.doFinal(outBuf, length1); int actualLength = length1 + length2; byte[] result = new byte[actualLength]; System.arraycopy(outBuf, 0, result, 0, result.length); return result; } //bc解密 public static String decrypt(String content, byte[] apiKey) throws Exception { if (apiKey == null) { throw new IllegalArgumentException("Key cannot be null!"); } String decrypted = null; byte[] encryptedContent = base64.decode(content); byte[] decryptedBytes = null; if (apiKey.length != 32 && apiKey.length != 24 && apiKey.length != 16) { throw new IllegalArgumentException( "Key length must be 128/192/256 bits!"); } decryptedBytes = decrypt222(encryptedContent, apiKey, DEFAULT_IV); decrypted = new String(decryptedBytes); return decrypted; } private static byte[] decrypt222(byte[] cipher, byte[] key, byte[] iv) throws Exception { PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new CFBBlockCipher(new AESEngine(), 128)); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(false, ivAndKey); return cipherData(aes, cipher); } }
Bouncy Castle Inc.公司提供的算法包,进行aes加密;方案2
package com; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.encoders.Hex; /*算法模式:CBC 填充模式:PKCS5 初始化向量IV:0x31, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38, 0x27, 0x36, 0x35, 0x33, 0x23, 0x32, 0x33,IV值一定是128位的(16字节). 为提高加密性能,建议使用Bouncy Castle Inc.公司提供的算法包,以下样例中使用的就是该公司的算法包。其运算速度是jdk自带的10倍以上。 */public class AESTest { private static final byte[] INIT_VECTOR = new byte[] {-12, 56, -25, 63, 78, 32, 76, 89, 34, 76, -64, 88, -56, 23, 66, 11}; public static void main(String[] args) { try { String apiKey = "222b8f353b79afb361e27b3523967928"; String content = "Bpokdsad"; String encrypt = encrypt(content, apiKey); System.out.println(encrypt); String decrypt = decrypt(encrypt, apiKey); System.out.println(decrypt); } catch (Exception e) { e.printStackTrace(); } } public static String encrypt(String content, String apiKey) throws Exception { if (apiKey == null) { throw new IllegalArgumentException("Key cannot be null!"); } String encrypted = null; byte[] keyBytes = apiKey.getBytes(); System.out.println(keyBytes.length); if (keyBytes.length != 32 && keyBytes.length != 24 //*8 && keyBytes.length != 16) { throw new IllegalArgumentException( "Key length must be 128/192/256 bits!"); } byte[] encryptedBytes = null; PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESFastEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(keyBytes), INIT_VECTOR); aes.init(true, ivAndKey); encryptedBytes = cipherData(aes, content.getBytes()); encrypted = new String(Hex.encode(encryptedBytes)); return encrypted; } public static String decrypt(String content, String apiKey) throws Exception { if (apiKey == null) { throw new IllegalArgumentException("Key cannot be null!"); } String decrypted = null; byte[] encryptedContent = Hex.decode(content); byte[] keyBytes = apiKey.getBytes(); byte[] decryptedBytes = null; if (keyBytes.length != 32 && keyBytes.length != 24 && keyBytes.length != 16) { throw new IllegalArgumentException( "Key length must be 128/192/256 bits!"); } PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESFastEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(keyBytes), INIT_VECTOR); aes.init(false, ivAndKey); decryptedBytes = cipherData(aes, encryptedContent); decrypted = new String(decryptedBytes); return decrypted; } private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) throws Exception { int minSize = cipher.getOutputSize(data.length); byte[] outBuf = new byte[minSize]; int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0); int length2 = cipher.doFinal(outBuf, length1); int actualLength = length1 + length2; byte[] result = new byte[actualLength]; System.arraycopy(outBuf, 0, result, 0, result.length); return result; } }
Bouncy Castle Inc.公司提供的算法包,进行rsa加密
package testRsa; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.generators.*; import org.bouncycastle.crypto.params.*; import org.bouncycastle.crypto.*; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.crypto.util.PrivateKeyInfoFactory; import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory; import org.bouncycastle.crypto.engines.*; import org.bouncycastle.asn1.pkcs.*; import org.bouncycastle.asn1.*; import java.math.BigInteger; import java.security.SecureRandom; import java.util.*; public class test_rsa { public static void main(String[] args) throws Exception { //生成密钥对 RSAKeyPairGenerator rsaKeyPairGenerator = new RSAKeyPairGenerator(); RSAKeyGenerationParameters rsaKeyGenerationParameters = new RSAKeyGenerationParameters(BigInteger.valueOf(3), new SecureRandom(), 1024, 25); //初始化参数 rsaKeyPairGenerator.init(rsaKeyGenerationParameters); AsymmetricCipherKeyPair keyPair = rsaKeyPairGenerator.generateKeyPair(); //公钥 AsymmetricKeyParameter publicKey = keyPair.getPublic(); //私钥 AsymmetricKeyParameter privateKey = keyPair.getPrivate(); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(privateKey); //变字符串 ASN1Object asn1ObjectPublic = subjectPublicKeyInfo.toASN1Primitive(); byte[] publicInfoByte = asn1ObjectPublic.getEncoded(); ASN1Object asn1ObjectPrivate = privateKeyInfo.toASN1Primitive(); byte[] privateInfoByte = asn1ObjectPrivate.getEncoded(); //这里可以将密钥对保存到本地 final Base64.Encoder encoder64 = Base64.getEncoder(); System.out.println("PublicKey:\n" + encoder64.encodeToString(publicInfoByte)); System.out.println("PrivateKey:\n" + encoder64.encodeToString(privateInfoByte)); //加密、解密 ASN1Object pubKeyObj = subjectPublicKeyInfo.toASN1Primitive();//这里也可以从流中读取,从本地导入 AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(SubjectPublicKeyInfo.getInstance(pubKeyObj)); AsymmetricBlockCipher cipher = new RSAEngine(); cipher.init(true, pubKey);//true表示加密 final Base64.Decoder decoder64 = Base64.getDecoder(); //加密 String data = "成aa功324$$了#*(=-nh)。。。"; System.out.println("\n明文:" + data); byte[] encryptData = cipher.processBlock(data.getBytes("utf-8") , 0, data.getBytes("utf-8").length); System.out.println("密文:" + encoder64.encodeToString(encryptData)); //解密 AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(privateInfoByte); cipher.init(false, priKey);//false表示解密 byte[] decriyptData=cipher.processBlock(encryptData, 0, encryptData.length); String decryptData = new String(decriyptData,"utf-8"); System.out.println("解密后数据:" + decryptData); } }
原文:https://www.cnblogs.com/sina-p/p/14551750.html