继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

各种加密算法总结(对称、非对称)

qq_Sunshine暖阳_0
关注TA
已关注
手记 11
粉丝 2
获赞 98

加密算法真的很多哦!!累死爸爸了。。。
而且很多还是不懂,慢慢来吧,加油!!!

对称加密算法
1.DES

package com.security;
import java.security.InvalidKeyException;    
import java.security.NoSuchAlgorithmException;    
//import java.security.Security;    
import java.security.Security;

import javax.crypto.BadPaddingException;    
import javax.crypto.Cipher;    
import javax.crypto.IllegalBlockSizeException;    
import javax.crypto.KeyGenerator;    
import javax.crypto.NoSuchPaddingException;    
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;    
public class LoveDES {
    private static String src="imooc security des";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //jdkDES();
        bcDES();
    }
    public static void jdkDES(){
        try {
            //生成key
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            keyGenerator.init(56);
            SecretKey secretKey=keyGenerator.generateKey();
            byte[] bytesKey=secretKey.getEncoded();
            //KEY转换
            DESKeySpec desKeySpec=new DESKeySpec(bytesKey);
            SecretKeyFactory factory=SecretKeyFactory.getInstance("DES");
            SecretKey convertSecretKey=factory.generateSecret(desKeySpec);
            //加密
            Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加解密算法、工作方式、填充方式
            cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("jdk des encrypt:"+Hex.toHexString(result));
            //解密
            cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
            result=cipher.doFinal(result);
            System.out.println("jdk des decrypt:"+new String(result));
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    public static void bcDES(){
        try {
            Security.addProvider(new BouncyCastleProvider());
            //生成key
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");
            keyGenerator.getProvider();
            keyGenerator.init(56);
            SecretKey secretKey=keyGenerator.generateKey();
            byte[] bytesKey=secretKey.getEncoded();
            //KEY转换
            DESKeySpec desKeySpec=new DESKeySpec(bytesKey);
            SecretKeyFactory factory=SecretKeyFactory.getInstance("DES");
            SecretKey convertSecretKey=factory.generateSecret(desKeySpec);
            //加密
            Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加解密算法、工作方式、填充方式
            cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("bc des encrypt:"+Hex.toHexString(result));
            //解密
            cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
            result=cipher.doFinal(result);
            System.out.println("bc des decrypt:"+new String(result));
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

}

2.3DES

package com.security;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;

import org.bouncycastle.util.encoders.Hex;

public class Love3DES {
    private static String src="imooc security 3des";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        jdk3DES();
    }
    private static void jdk3DES(){
        try {
            //生成key
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
            //keyGenerator.init(168);
            keyGenerator.init(new SecureRandom());
            SecretKey secretKey=keyGenerator.generateKey();
            byte[] bytesKey=secretKey.getEncoded();
            //KEY转换
            DESedeKeySpec desKeySpec=new DESedeKeySpec(bytesKey);
            SecretKeyFactory factory=SecretKeyFactory.getInstance("DESede");
            SecretKey convertSecretKey=factory.generateSecret(desKeySpec);
            //加密
            Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");//加解密算法、工作方式、填充方式
            cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("jdk 3des encrypt:"+Hex.toHexString(result));
            //解密
            cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
            result=cipher.doFinal(result);
            System.out.println("jdk 3des decrypt:"+new String(result));
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

}

3.AES

package com.security;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;    
//import java.security.Security;    
import java.security.Security;

import javax.crypto.BadPaddingException;    
import javax.crypto.Cipher;    
import javax.crypto.IllegalBlockSizeException;    
import javax.crypto.KeyGenerator;    
import javax.crypto.NoSuchPaddingException;    
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;    
import javax.crypto.KeyGenerator;

public class LoveAES {
    private static String src="imooc security aes";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        jdkAES();
    }
    public static void jdkAES(){
        try {
            //生成KEY
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
            SecretKey secretKey=keyGenerator.generateKey();
            byte[] keyBytes=secretKey.getEncoded();
            //key转换
            Key key=new SecretKeySpec(keyBytes, "AES");
            //加密
            Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("jdk aes encrypt:"+Base64.encodeBase64String(result));
            //解密
            cipher.init(Cipher.DECRYPT_MODE, key);
            result=cipher.doFinal(result);
            System.out.println("jdk aes decrypt:"+new String(result));
        } catch (Exception e) {
            // TODO: handle exception
        }

    }
}

4.PBE

package com.security;

import java.security.SecureRandom;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;    
//import java.security.Security;    
import java.security.Security;

import javax.crypto.BadPaddingException;    
import javax.crypto.Cipher;    
import javax.crypto.IllegalBlockSizeException;    
import javax.crypto.KeyGenerator;    
import javax.crypto.NoSuchPaddingException;    
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;    
import javax.crypto.KeyGenerator;
public class LovePBE {
    private static String src="imooc security pbe";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        jdkPBE();
    }
    public static void jdkPBE(){
        try {
            //初始化盐
            SecureRandom random = new SecureRandom();
            byte[] salt = random.generateSeed(8);
            //口令与密钥
            String password = "imooc";//口令
            PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
            Key key=factory.generateSecret(pbeKeySpec);
            //加密
            PBEParameterSpec pbeParameterSpec=new PBEParameterSpec(salt, 100);
            Cipher cipher=Cipher.getInstance("PBEWITHMD5andDES");
            cipher.init(Cipher.ENCRYPT_MODE,key,pbeParameterSpec);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("jdk pbe encrypt:"+Base64.encodeBase64String(result));
            //解密
            cipher.init(Cipher.DECRYPT_MODE,key,pbeParameterSpec);
            result=cipher.doFinal(result);
            System.out.println("jdk pbe decrypt:"+new String(result));
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

}

5.Base64

package com.security;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jcajce.provider.symmetric.ARC4.Base;
import org.bouncycastle.util.encoders.Base64Encoder;
import sun.security.*;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
public class LoveBase64 {
    private static String src="immoc security base64";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //jdkbase64();
        //commonsCodesBase64();
        bouncyCastleBase64();
    }
    public static void jdkbase64(){

        try {
            BASE64Encoder encoder=new BASE64Encoder(); 
        String encode=encoder.encode(src.getBytes());
        System.out.println("encode:"+encode);
        BASE64Decoder decoder=new BASE64Decoder(); 
        System.out.println("decode:"+new String(decoder.decodeBuffer(encode)));

        } catch (IOException e) {
            // TODO: handle exception
        }
    }

    public static void commonsCodesBase64(){
        byte[] encodeBytes=Base64.encodeBase64(src.getBytes());
        System.out.println("encode:"+new String(encodeBytes));
        byte[] decodeBytes=Base64.decodeBase64(encodeBytes);
        System.out.println("decode:"+new String(decodeBytes));
    }

    public static void bouncyCastleBase64(){
       byte[] encodeBytes=org.bouncycastle.util.encoders.Base64.encode(src.getBytes());
       System.out.println("encode:"+new String(encodeBytes));
       byte[] decodeBytes=org.bouncycastle.util.encoders.Base64.decode(encodeBytes);
       System.out.println("decode:"+new String(decodeBytes));
    }

}

非对称加密
1.DH

package com.security2;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Objects;

import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;

import org.apache.commons.codec.binary.Base64;

public class LoveDH {
    private static String src="imooc security dh";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        jdkDH();
    }
    public static void jdkDH(){
        try {
            //1.初始化发送方密钥
            KeyPairGenerator senderkeyPairGenerator = KeyPairGenerator.getInstance("DH");
            senderkeyPairGenerator.initialize(512);
            KeyPair senderKeyPair=senderkeyPairGenerator.generateKeyPair();
            byte[] senderPublicKeyEnc=senderKeyPair.getPublic().getEncoded();//发送方公钥 ,发送给接收方
            //2.初始化接收方密钥
            KeyFactory receiverKeyFactory=KeyFactory.getInstance("DH");
            X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(senderPublicKeyEnc);;
            PublicKey receiverPublicKey=receiverKeyFactory.generatePublic(x509EncodedKeySpec);
            DHParameterSpec dhParameterSpec=((DHPublicKey)receiverPublicKey).getParams();
            KeyPairGenerator receiverKeyPairGenerator=KeyPairGenerator.getInstance("DH");
            receiverKeyPairGenerator.initialize(dhParameterSpec);
            KeyPair receiverKeypair=receiverKeyPairGenerator.generateKeyPair();
            PrivateKey receiverPrivateKey=receiverKeypair.getPrivate();
            byte[] receiverPublicKeyEnc=receiverKeypair.getPublic().getEncoded();
            //密钥构建
            KeyAgreement receiverkeyAgreement=KeyAgreement.getInstance("DH");
            receiverkeyAgreement.init(receiverPrivateKey);
            receiverkeyAgreement.doPhase(receiverPublicKey, true);
            SecretKey receiverDesKey=receiverkeyAgreement.generateSecret("DES");
            KeyFactory senderkeyFactory=KeyFactory.getInstance("DH");
            x509EncodedKeySpec=new X509EncodedKeySpec(receiverPublicKeyEnc);
            PublicKey senderpublicKey=senderkeyFactory.generatePublic(x509EncodedKeySpec);
            KeyAgreement senderkeyAgreement=KeyAgreement.getInstance("DH");
            senderkeyAgreement.init(senderKeyPair.getPrivate());
            senderkeyAgreement.doPhase(senderpublicKey, true);
            SecretKey senderDesKey=senderkeyAgreement.generateSecret("DES");
            if(Objects.equals(receiverDesKey, receiverDesKey)){
                System.out.println("双方密钥相同");
            }
            //加密
            Cipher cipher=Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE,senderDesKey);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("jdk dh encrypt:"+Base64.encodeBase64String(result));
            //解密
            cipher.init(Cipher.DECRYPT_MODE,receiverDesKey);
           result=cipher.doFinal(result);
            System.out.println("jdk dh encrypt:"+new String(result));
        }catch(Exception e) {
            // TODO: handle exception
        }

    }
}

2.ElGamal

package com.security2;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.spec.DHParameterSpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class LoveElGamal {
    private static String src="imooc security elgamal";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        bcElGamal();
    }
    public static void bcElGamal(){
        try {
            //公钥加密,私钥解密
            Security.addProvider(new BouncyCastleProvider());
            //1.初始化密钥
            AlgorithmParameterGenerator algorithmParameterGenerator = AlgorithmParameterGenerator
                    .getInstance("ElGamal");
            algorithmParameterGenerator.init(256);
            AlgorithmParameters algorithmParameters=algorithmParameterGenerator.generateParameters();
            DHParameterSpec dhParameterSpec=(DHParameterSpec)algorithmParameters.getParameterSpec(DHParameterSpec.class);
            KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("ElGamal");
            keyPairGenerator.initialize(dhParameterSpec, new SecureRandom());
            KeyPair keyPair=keyPairGenerator.generateKeyPair();
            PublicKey elGamalPublicKey=keyPair.getPublic();
            PrivateKey elGamalPrivateKey=keyPair.getPrivate();
            System.out.println("PublicKey:"+Base64.encodeBase64String(elGamalPublicKey.getEncoded()));
            System.out.println("PrivateKey:"+Base64.encodeBase64String(elGamalPrivateKey.getEncoded()));

            //4公钥加密,私钥解密---加密
            X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(elGamalPublicKey.getEncoded());
            KeyFactory keyFactory=KeyFactory.getInstance("RSA");
            PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("公钥加密,私钥解密---加密:"+Base64.encodeBase64String(result));
            //5.公钥加密,私钥解密---解密
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(elGamalPrivateKey.getEncoded());
            keyFactory=KeyFactory.getInstance("ElGamal");
            PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            result=cipher.doFinal(result);
            System.out.println("公钥加密,私钥解密---解密:"+new String(result));
            //2.私钥加密,公钥解密---加密
           /* PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(elGamalPrivateKey.getEncoded());
            KeyFactory keyFactory=KeyFactory.getInstance("RSA");
            PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("私钥加密,公钥解密---加密:"+Base64.encodeBase64String(result));
            //3.私钥加密,公钥解密---解密
            X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(elGamalPublicKey.getEncoded());
            keyFactory=KeyFactory.getInstance("RSA");
            PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);
            cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            result=cipher.doFinal(result);
            System.out.println("私钥加密,公钥解密---解密:"+new String(result));
            */
        } catch (Exception e) {
            // TODO: handle exception
        }

    }
}

3.RSA

package com.security2;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class LoveRSA {
    private static String src="imooc security rsa";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        jdkRSA();
    }
    public static void jdkRSA(){
        try {
            //1.初始化密钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(512);
            KeyPair keyPair=keyPairGenerator.generateKeyPair();
            RSAPublicKey rsaPublicKey=(RSAPublicKey)keyPair.getPublic();
            RSAPrivateKey rsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();
            System.out.println("Public Key:"+Base64.encodeBase64String(rsaPublicKey.getEncoded()));
            System.out.println("Private Key:"+Base64.encodeBase64String(rsaPrivateKey.getEncoded()));
            //2.私钥加密,公钥解密---加密
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            KeyFactory keyFactory=KeyFactory.getInstance("RSA");
            PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] result=cipher.doFinal(src.getBytes());
            System.out.println("私钥加密,公钥解密---加密:"+Base64.encodeBase64String(result));
            //3.私钥加密,公钥解密---解密
            X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            keyFactory=KeyFactory.getInstance("RSA");
            PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);
            cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            result=cipher.doFinal(result);
            System.out.println("私钥加密,公钥解密---解密:"+new String(result));
            //4公钥加密,私钥解密---加密
            x509EncodedKeySpec=new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            keyFactory=KeyFactory.getInstance("RSA");
            publicKey=keyFactory.generatePublic(x509EncodedKeySpec);
            cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            result=cipher.doFinal(src.getBytes());
            System.out.println("公钥加密,私钥解密---加密:"+Base64.encodeBase64String(result));
            //5.公钥加密,私钥解密---解密
            pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            keyFactory=KeyFactory.getInstance("RSA");
            privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            result=cipher.doFinal(result);
            System.out.println("公钥加密,私钥解密---解密:"+new String(result));
        } catch (Exception e) {
            // TODO: handle exception
        }

    }
}
打开App,阅读手记
9人推荐
发表评论
随时随地看视频慕课网APP

热门评论

真的很棒的一篇博文。

查看全部评论