Interviewer:? You know the signature algorithm micro-channel pay you talk about what you know cryptography

Under micro-channel single signature algorithm

Alipay single signature algorithm

The difference between the BASE64, MD5, RSA, SHA, HMAC and so we used encryption algorithm

BASE64

  • As defined in RFC2045, Base64 is defined as: Base64 code is designed to transfer the contents of the 8-bit byte of any sequence described as a person can not easily be directly recognized form. (The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable.) Is common in the mail, http encryption, interception http information, you will find the user name to log operation, password field by BASE64 encrypted.
/** 
 * BASE64解密 
 *  
 * @param key 
 * @return 
 * @throws Exception 
 */  
public static byte[] decryptBASE64(String key) throws Exception {  
    return (new BASE64Decoder()).decodeBuffer(key);  
}  
  
/** 
 * BASE64加密 
 *  
 * @param key 
 * @return 
 * @throws Exception 
 */  
public static String encryptBASE64(byte[] key) throws Exception {  
    return (new BASE64Encoder()).encodeBuffer(key);  
}  
复制代码
  • Mainly BASE64Encoder, BASE64Decoder two classes, we need to know to use the corresponding method. Also, the number of bits produced after BASE byte encrypted multiple of 8, if not enough bits to fill the symbol =.

MD5

  • MD5 - message-digest algorithm 5 (Information - digest algorithm) abbreviations widely used in encryption and decryption techniques commonly used in the file verification. check? No matter how big the file, after MD5 can generate a unique MD5 value. Like the current ISO calibration are MD5 checksum. how to use? ISO after the course MD5 MD5 value is generated. General download linux-ISO friends have seen the download link next to lying string of MD5. It is used to verify that the file consistent.
/** 
 * MD5加密 
 *  
 * @param data 
 * @return 
 * @throws Exception 
 */  
public static byte[] encryptMD5(byte[] data) throws Exception {  
  
    MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);  
    md5.update(data);  
  
    return md5.digest();  
  
}  
复制代码

RSA

  • RSA public-key cryptosystem. The so-called public key cryptography is the use of a different encryption key and decryption key, a "is derived from the known encryption key decryption key is computationally infeasible" cryptosystems.

  • In public-key cryptosystem, the encryption key (that is, the public key) PK is public information, and the decryption key (ie secret key) SK is confidential. Encryption algorithm decryption algorithm D and E are also disclosed. Although the decryption key SK is determined by a public key PK, and can not be calculated because the Euler function phi (N) n in large numbers, it can not be calculated according to SK PK.


————————————————
版权声明:本文为CSDN博主「小网客」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/smallnetvisitor/article/details/84924214
复制代码

SHA

  • SHA (Secure Hash Algorithm, Secure Hash Algorithm), digital signatures and other cryptographic applications important tool is widely used in the field of information security e-commerce. Although, by SHA and MD5 collision method have been cracked, but still SHA encryption algorithm is generally recognized as safe, more secure than MD5.
 package com.chen.test;

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

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
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 java.util.HashMap;
import java.util.Map;

public class RSAUtils {

    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";


    public static Map<String, String> createKeys(int keySize){
        //为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator kpg;
        try{
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        }catch(NoSuchAlgorithmException e){
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 得到公钥
     * @param publicKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 得到私钥
     * @param privateKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 公钥加密
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, RSAPrivateKey privateKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥加密
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateEncrypt(String data, RSAPrivateKey privateKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 公钥解密
     * @param data
     * @param publicKey
     * @return
     */

    public static String publicDecrypt(String data, RSAPublicKey publicKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
        int maxBlock = 0;
        if(opmode == Cipher.DECRYPT_MODE){
            maxBlock = keySize / 8;
        }else{
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try{
            while(datas.length > offSet){
                if(datas.length-offSet > maxBlock){
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                }else{
                    buff = cipher.doFinal(datas, offSet, datas.length-offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        }catch(Exception e){
            throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }

}
复制代码

HMAC

  • HMAC (Hash Message Authentication Code, hash message authentication code, the authentication protocol based on Hash Algorithm key. Principles message authentication code authentication is achieved, a fixed-length value generated using the public key as a function of authentication and identification, with the identification & integrity of the message using a key to generate a small fixed-size data blocks, i.e., the MAC, and added to the message, and then transmitted. recipient using the key shared with a sender identification authentication.
/** 
 * 初始化HMAC密钥 
 *  
 * @return 
 * @throws Exception 
 */  
public static String initMacKey() throws Exception {  
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);  
  
    SecretKey secretKey = keyGenerator.generateKey();  
    return encryptBASE64(secretKey.getEncoded());  
}  
  
/** 
 * HMAC加密 
 *  
 * @param data 
 * @param key 
 * @return 
 * @throws Exception 
 */  
public static byte[] encryptHMAC(byte[] data, String key) throws Exception {  
  
    SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);  
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());  
    mac.init(secretKey);  
  
    return mac.doFinal(data);  
  
}  
复制代码

Complete class (does not include RSA encryption algorithm)

import java.security.MessageDigest;  
  
import javax.crypto.KeyGenerator;  
import javax.crypto.Mac;  
import javax.crypto.SecretKey;  
  
import sun.misc.BASE64Decoder;  
import sun.misc.BASE64Encoder;  
  
/** 
 * 基础加密组件 
 *  
 * @author 梁栋 
 * @version 1.0 
 * @since 1.0 
 */  
public abstract class Coder {  
    public static final String KEY_SHA = "SHA";  
    public static final String KEY_MD5 = "MD5";  
  
    /** 
     * MAC算法可选以下多种算法 
     *  
     * <pre> 
     * HmacMD5  
     * HmacSHA1  
     * HmacSHA256  
     * HmacSHA384  
     * HmacSHA512 
     * </pre> 
     */  
    public static final String KEY_MAC = "HmacMD5";  
  
    /** 
     * BASE64解密 
     *  
     * @param key 
     * @return 
     * @throws Exception 
     */  
    public static byte[] decryptBASE64(String key) throws Exception {  
        return (new BASE64Decoder()).decodeBuffer(key);  
    }  
  
    /** 
     * BASE64加密 
     *  
     * @param key 
     * @return 
     * @throws Exception 
     */  
    public static String encryptBASE64(byte[] key) throws Exception {  
        return (new BASE64Encoder()).encodeBuffer(key);  
    }  
  
    /** 
     * MD5加密 
     *  
     * @param data 
     * @return 
     * @throws Exception 
     */  
    public static byte[] encryptMD5(byte[] data) throws Exception {  
  
        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);  
        md5.update(data);  
  
        return md5.digest();  
  
    }  
  
    /** 
     * SHA加密 
     *  
     * @param data 
     * @return 
     * @throws Exception 
     */  
    public static byte[] encryptSHA(byte[] data) throws Exception {  
  
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);  
        sha.update(data);  
  
        return sha.digest();  
  
    }  
  
    /** 
     * 初始化HMAC密钥 
     *  
     * @return 
     * @throws Exception 
     */  
    public static String initMacKey() throws Exception {  
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);  
  
        SecretKey secretKey = keyGenerator.generateKey();  
        return encryptBASE64(secretKey.getEncoded());  
    }  
  
    /** 
     * HMAC加密 
     *  
     * @param data 
     * @param key 
     * @return 
     * @throws Exception 
     */  
    public static byte[] encryptHMAC(byte[] data, String key) throws Exception {  
  
        SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);  
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());  
        mac.init(secretKey);  
  
        return mac.doFinal(data);  
  
    }  
}  
复制代码

Test category

import static org.junit.Assert.*;  
  
import org.junit.Test;  
  
/** 
 *  
 * @author 梁栋 
 * @version 1.0 
 * @since 1.0 
 */  
public class CoderTest {  
  
    @Test  
    public void test() throws Exception {  
        String inputStr = "简单加密";  
        System.err.println("原文:/n" + inputStr);  
  
        byte[] inputData = inputStr.getBytes();  
        String code = Coder.encryptBASE64(inputData);  
  
        System.err.println("BASE64加密后:/n" + code);  
  
        byte[] output = Coder.decryptBASE64(code);  
  
        String outputStr = new String(output);  
  
        System.err.println("BASE64解密后:/n" + outputStr);  
  
        // 验证BASE64加密解密一致性  
        assertEquals(inputStr, outputStr);  
  
        // 验证MD5对于同一内容加密是否一致  
        assertArrayEquals(Coder.encryptMD5(inputData), Coder  
                .encryptMD5(inputData));  
  
        // 验证SHA对于同一内容加密是否一致  
        assertArrayEquals(Coder.encryptSHA(inputData), Coder  
                .encryptSHA(inputData));  
  
        String key = Coder.initMacKey();  
        System.err.println("Mac密钥:/n" + key);  
  
        // 验证HMAC对于同一内容,同一密钥加密是否一致  
        assertArrayEquals(Coder.encryptHMAC(inputData, key), Coder.encryptHMAC(  
                inputData, key));  
  
        BigInteger md5 = new BigInteger(Coder.encryptMD5(inputData));  
        System.err.println("MD5:/n" + md5.toString(16));  
  
        BigInteger sha = new BigInteger(Coder.encryptSHA(inputData));  
        System.err.println("SHA:/n" + sha.toString(32));  
  
        BigInteger mac = new BigInteger(Coder.encryptHMAC(inputData, inputStr));  
        System.err.println("HMAC:/n" + mac.toString(16));  
    }  
}  
复制代码

result

原文:  
简单加密  
BASE64加密后:  
566A5Y2V5Yqg5a+G  
  
BASE64解密后:  
简单加密  
Mac密钥:  
uGxdHC+6ylRDaik++leFtGwiMbuYUJ6mqHWyhSgF4trVkVBBSQvY/a22xU8XT1RUemdCWW155Bke  
pBIpkd7QHg==  
  
MD5:  
-550b4d90349ad4629462113e7934de56  
SHA:  
91k9vo7p400cjkgfhjh0ia9qthsjagfn  
HMAC:  
2287d192387e95694bdbba2fa941009a  
复制代码

Guess you like

Origin juejin.im/post/5e09741f518825497837833b