java/消息摘要算法&数字签名

Posted kaixinyufeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java/消息摘要算法&数字签名相关的知识,希望对你有一定的参考价值。

一。消息摘要算法

常用摘要算法:

 

以下 (HEX)内容:bc指Bouncy Castle  |  cc指:Apache commons Codec

1。消息摘要算法MD5及MD族(MD2,MD4) 

消息摘要算法应用:

MD算法实现:

package com.imooc.security.md;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class ImoocMD {
    
    private static String src = "imooc security md";

    public static void main(String[] args) {
         jdkMD5();
         jdkMD2();
         bcMD4();
         bcMD5();
         ccMD5();
         ccMD2();
    }
    
    public static void jdkMD5() {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md.digest(src.getBytes());
            System.out.println("JDK MD5 : " + Hex.encodeHexString(md5Bytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
    public static void jdkMD2() {
        try {
            MessageDigest md = MessageDigest.getInstance("MD2");
            byte[] md2Bytes = md.digest(src.getBytes());
            System.out.println("JDK MD2 : " + Hex.encodeHexString(md2Bytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
    public static void bcMD5() {
        Digest digest = new MD5Digest();
        digest.update(src.getBytes(), 0, src.getBytes().length);
        byte[] md5Bytes = new byte[digest.getDigestSize()];
        digest.doFinal(md5Bytes, 0);
        System.out.println("BC MD5 : " + org.bouncycastle.util.encoders.Hex.toHexString(md5Bytes));
    }
    
    public static void bcMD4() {
        try {
            Security.addProvider(new BouncyCastleProvider());
            MessageDigest md = MessageDigest.getInstance("MD4");
            byte[] md5Bytes = md.digest(src.getBytes());
            System.out.println("BC MD4 : " + Hex.encodeHexString(md5Bytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
    public static void ccMD5() {
        System.out.println("CC MD5 : " + DigestUtils.md5Hex(src.getBytes()));
    }
    
    public static void ccMD2() {
        System.out.println("CC MD2 : " + DigestUtils.md2Hex(src.getBytes()));
    }

}
View Code

 

2。消息摘要算法SHA(安全散列算法)

SHA算法实现:

package com.imooc.security.sha;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class ImoocSHA {
    
    private static String src = "imooc security sha";

    public static void main(String[] args) {
         jdkSHA1();
         bcSHA1();
         bcSHA224();
         ccSHA1();
    }
    
    public static void jdkSHA1() {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(src.getBytes());
            System.out.println("jdk sha-1 : " + Hex.encodeHexString(md.digest()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
    public static void bcSHA1() {
        Digest digest = new SHA1Digest();
        digest.update(src.getBytes(), 0, src.getBytes().length);
        byte[] sha1Bytes = new byte[digest.getDigestSize()];
        digest.doFinal(sha1Bytes, 0);
        System.out.println("bc sha-1 : " + org.bouncycastle.util.encoders.Hex.toHexString(sha1Bytes));
    }
    
    public static void bcSHA224() {
        Digest digest = new SHA224Digest();
        digest.update(src.getBytes(), 0, src.getBytes().length);
        byte[] sha224Bytes = new byte[digest.getDigestSize()];
        digest.doFinal(sha224Bytes, 0);
        System.out.println("bc sha-224 : " + org.bouncycastle.util.encoders.Hex.toHexString(sha224Bytes));
    }
    
    public static void bcSHA224_2() {
        Security.addProvider(new BouncyCastleProvider());
        //...练习内容,^_^
    }
    
    public static void ccSHA1() {
        System.out.println("cc sha1 - 1 :" + DigestUtils.sha1Hex(src.getBytes()));
        System.out.println("cc sha1 - 2 :" + DigestUtils.sha1Hex(src));
    }
    
    //384、256、512。。。。。。

}
View Code

 

SHA算法应用

 

3。消息摘要算法--MAC

HMAC算法实现:

package com.imooc.security.hmac;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

public class ImoocHmac {
    
    private static String src = "imooc security hmac";

    public static void main(String[] args) {
         jdkHmacMD5();
         bcHmacMD5();
    }
    
    public static void jdkHmacMD5() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");//初始化KeyGenerator
            SecretKey secretKey = keyGenerator.generateKey();//产生密钥
//            byte[] key = secretKey.getEncoded();//获得密钥
            byte[] key = Hex.decodeHex(new char[] {\'a\', \'a\', \'a\', \'a\', \'a\', \'a\', \'a\', \'a\', \'a\', \'a\'});
            
            SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5");//还原密钥
            Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());//实例化MAC
            mac.init(restoreSecretKey);//初始化Mac
            byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());//执行摘要
            System.out.println("jdk hmacMD5 : " + Hex.encodeHexString(hmacMD5Bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void bcHmacMD5() {
        HMac hmac = new HMac(new MD5Digest());
        hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa")));
        hmac.update(src.getBytes(), 0, src.getBytes().length);
        
        byte[] hmacMD5Bytes = new byte[hmac.getMacSize()];//执行摘要
        hmac.doFinal(hmacMD5Bytes, 0);
        
        System.out.println("bc hmacMD5 : " + org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5Bytes));
        
    }

}
View Code

 

HMAC算法应用:

 

二。数字签名

数字签名算法--RSA(经典)

RSA是数字签名的经典算法,包括:MD/SHA两类。

数字签名算法实现--RSA

package com.imooc.security.rsa2;

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

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

public class ImoocRSA {
    
    private static String src = "imooc security rsa";

    public static void main(String[] args) {
        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();
            
            //2.执行签名
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(privateKey);
            signature.update(src.getBytes());
            byte[] result = signature.sign();
            System.out.println("jdk rsa sign : " + Hex.encodeHexString(result));
            
            //3.验证签名
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(publicKey);
            signature.update(src.getBytes());
            boolean bool = signature.verify(result);
            System.out.println("jdk rsa verify : " + bool);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
View Code

数字签名算法RSA应用:

数字签名算法实现--DSA

DSA与RSA区别:

DSA仅包含数字签名,使用DSA这种算法的证书无法进行加密通信。

RSA算法既包括加解密,同时也有数字签名算法。

DSA算法实现:

package com.imooc.security.dsa;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

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

public class ImoocDSA {
    
    private static String src = "imooc security dsa";

    public static void main(String[] args) {
        jdkDSA();
    }
    
    public static void jdkDSA() {
        try {
            //1.初始化密钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
            keyPairGenerator.initialize(512);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            DSAPublicKey dsaPublicKey = (DSAPublicKey) keyPair.getPublic();
            DSAPrivateKey dsaPrivateKey = (DSAPrivateKey)keyPair.getPrivate();
            
            //2.执行签名
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("DSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initSign(privateKey);
            signature.update(src.getBytes());
            byte[] result = signature.sign();
            System.out.println("jdk dsa sign : " + Hex.encodeHexString(result));
            
            //3.验证签名
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("DSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            signature = Signature.getInstance("SHA1withDSA");
            signature.initVerify(publicKey);
            signature.update(src.getBytes());
            boolean bool = signature.verify(result);
            System.out.println("jdk dsa verify : " + bool);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
View Code

DSA应用:

 

数字签名算法实现--ECDSA

package com.imooc.security.ecdsa;

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.Signature;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

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

public class ImoocECDSA {
    
    private static String src = "imooc security ecdsa";

    public static void main(String[] args) {
        jdkECDSA();
    }
    
    public static void jdkECDSA() {
        try {
            //1.初始化密钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
            keyPairGenerator.initialize(256);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic();
            ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate();
            
            //2.执行签名
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("SHA1withECDSA");
            signature.initSign(privateKey);
            signature.update(src.getBytes());
            byte[] result = signature.sign();
            System.out.println("jdk ecdsa sign : " + Hex.encodeHexString(result));
            
            //3.验证签名
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("EC");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            signature = Signature.getInstance("SHA1withECDSA");
            signature.initVerify(publicKey);
            signature.update(src.getBytes());
            boolean bool = signature.verify(result);
            System.out.println("jdk ecdsa verify : " + bool);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

}
View Code

ECDSA应用:

 

 三。BASE64加密算法

加解密基础与base64算法

1。密码常用术语

注:md5只能加密,不能解密.

2。加解密基础

【1】密码分类

 

【2】散列函数(单向函数):用来验证数据完整性(而不是用来加解密)

散列函数据相关算法:

【3】数字签名:

【4】OSI与TCP/IP安全体系

 

【5】Java安全组成、包及第三方扩展

(1)JCA:提供基本的加密框架,如消息摘要、数字签名等。

(2)JCE:JCA基础上扩展,提供加密算法、消息摘要、密钥管理功能。(JDK包中)

(3)JSSE:保证在网络传输的数据定全

(4)JAAS:基于Java平台基于身份验证功能(系统安全/权限)

Java安装目录/security/java.security文件

 

 

3。实现base64算法

package com.imooc.security.base64;

import java.io.IOException;

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

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ImoocBase64 {
    
    private static String src = "imooc security base64";

    public static void main(String[] args) {
        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) {
            e.printStackTrace();
        }
    }
    
    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));
    }

}
View Code

注:Base64Encoder不建议使用。

Base64算法应用场景

 

 四。对称加密算法

1.Java对称加密算法--DES

package com.imooc.security.des;

import java.security.Key;
import java.security.Security;

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

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

public class ImoocDES {
    
    private static String src = "imooc security des";

    public static void main(String[] args) {
        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");
            Key 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.encodeHexString(result));
            
            //解密
            cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
            result = cipher.doFinal(result);
            System.out.println("jdk des decrypt : " + new String(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    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");
            Key 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(消息摘要算法

加解密---Java安全

Java数字签名算法--RSA

SHA1 算法

安卓逆向 -- 算法基础(数字签名)

java中的MD5工具类