加密签名

## 摘要
md5 sha1
```
package com.wch.encrypt;
 
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
* Created by weichunhe on 2016/4/29.
*/
public class Digest {
    private static Logger log = LoggerFactory.getLogger(Digest.class);
 
    public static void sha1() {
        String sha1 = DigestUtils.sha1Hex("spring");
        log.info("sha1摘要:{}->{}", "spring", sha1);
 
    }
 
    public static void md5(){
        String md5 = DigestUtils.md5Hex("spring");
        log.info("md5摘要:{}->{}","spring",md5);
    }
 
    public static void main(String[] args) {
        sha1();
        md5();
    }
}
```

## 对称加密
DES AES
```
package com.wch.encrypt;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
 
/**
* Created by weichunhe on 2016/4/29.
*/
public class DES {
    public static String deskey = "{PONY}";
 
    public static String encrypt(String strIn) {
 
        try {
            Key key = getKey(deskey);
 
            Cipher encryptCipher = Cipher.getInstance("DES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, key);
 
            return byteArr2HexStr(encryptCipher.doFinal(strIn.getBytes()));
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public static String dencrypt(String strIn) {
 
        try {
            Key key = getKey(deskey);
            Cipher encryptCipher = Cipher.getInstance("DES");
            encryptCipher.init(Cipher.DECRYPT_MODE, key);
            return new String(encryptCipher.doFinal(hexStringToBytes(strIn)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    private static Key getKey(String strKey) throws Exception {
        byte[] arrBTmp = strKey.getBytes();
        byte[] arrB = new byte[8];
        for (int i = 0; (i < arrBTmp.length) && (i < arrB.length); ++i) {
            arrB[i] = arrBTmp[i];
        }
        Key key = new SecretKeySpec(arrB, "DES");
        return key;
    }
 
    private static String byteArr2HexStr(byte[] arrB) throws Exception {
        int iLen = arrB.length;
        StringBuffer sb = new StringBuffer(iLen * 2);
        for (int i = 0; i < iLen; ++i) {
            int intTmp = arrB[i];
            while (intTmp < 0) {
                intTmp += 256;
            }
            if (intTmp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(intTmp, 16));
        }
        return sb.toString();
    }
 
    /**
     * Convert byte[] to hex
     * string.这里我们可以将byte转换成int,然后利用Integer.toHexString(int)来转换成16进制字符串。
     *
     * @param src byte[] data
     * @return hex string
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
 
    /**
     * Convert hex string to byte[]
     *
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
 
    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
 
 
    public static void main(String[] args) {
        String strIn = "666666";
        System.out.println(encrypt(strIn));
        System.out.println(dencrypt("37b8acd28f207ce2"));
    }
}
```

## 非对称加密、签名
RSA
```
package com.wch.encrypt;
 
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
 
/**
* Created by weichunhe on 2016/4/29.
*/
public class Rsa {
    public static void main(String[] args) throws Exception {
        KeyFactory factory = KeyFactory.getInstance("RSA");
        byte[] bytes = Base64
                .getDecoder()
                .decode("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1gr+rIfYlaNUNLiFsK/Knb54nQrCRTRMOdujTwkpqKLo4pNYj2StmryWETeFxOCFtCt/7ixTUrU2RGGjkIOlYC3144h0dJKDtPXw9+mFyW1VwWvtfoiSUeKTEbz1tSHghEcdEvVq6qlSQukiLAEZabiwfEE30TQ6g979X6YXhnQIDAQAB");
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        PublicKey publicKey = factory.generatePublic(spec);
 
        byte[] pirvateBytes = Base64
                .getDecoder()
                .decode("MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBALWCv6sh9iVo1Q0uIWwr8qdvnidCsJFNEw526NPCSmooujik1iPZK2avJYRN4XE4IW0K3/uLFNStTZEYaOQg6VgLfXjiHR0koO09fD36YXJbVXBa+1+iJJR4pMRvPW1IeCERx0S9WrqqVJC6SIsARlpuLB8QTfRNDqD3v1fpheGdAgMBAAECgYEArmr1w3zfCxOxpvitJUUV589aKl/rS7TEmyGomdQZrel1CPlczRXinsmvQ3OTLzjA5geNNCpx2eyunL7YDF+T2WgcvpPlM+TUrBnTI9gKYwLXiWPuWou8oZolHaTuQQuLfnJTZ+6cYjHA3S4xnrJaEvvs8xgy6/UAJWXUpm/dQAECQQDlW9LPOrWaaVFuZqftVTwhTjhVmBZ/AeuXcmmmF2KBGaujbXJuVHVE5rzW9/6TQoWinuK4J/UOLcFl3VTTEPgZAkEAypggJwgYq3uz0KX8YScHV/gUZa56l5gRofMrIpiek4uvt2JM1kqgIq9T9PIOnv7dz7buRk2GXi3GLgEuhDr2JQJBAJPAypZ7QMBfdnkDosyOqzTdegcR+fQJ3aZrq0m3KNr4GY0nlZ8jw4QGjMKDcjmVkhdH+dAe1Ywzx7ICmoF6HgkCQQCTo+lKiIvx7GROWahi5J5lbVTwBQcyEpBHBX8Z5z8pJ1MWwXxdbmTk4gC9MOmW1QWwqg9bDIQvfgw+2n2bv5xBAkEAhUaiDfOywrIB3VUZWTqeIlVfqXHd8a9AcellTgIjK8WIu9gNGIfkWUVoVeOq0GCFTVqwO5tlac+oeDHCCimLyQ==");
        PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(pirvateBytes);
        PrivateKey privateKey = factory.generatePrivate(privateSpec);
 
        //matrix-utils jar
//        byte[] encode = RSA.encrypt("wch".getBytes(), privateKey);
//        System.out.println(Base64.getEncoder().encodeToString(encode));
//        System.out.println(new String(RSA.decrypt(encode, publicKey)));
//
//        byte[] publicEncode = RSA.encrypt("pubic".getBytes(), publicKey);
//        System.out.println(Base64.getEncoder().encodeToString(publicEncode));
//        System.out.println(new String(RSA.decrypt(publicEncode, privateKey)));
//
//        byte[] sign = RSA.sign("wch".getBytes(), privateKey);
//        System.out.println(Base64.getEncoder().encodeToString(sign));
//
//        System.out.println(RSA.verify("wch".getBytes(), sign, publicKey));
 
    }
}
```




原文地址:https://www.cnblogs.com/vvch/p/5465597.html