博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
加密签名
阅读量:4941 次
发布时间:2019-06-11

本文共 5897 字,大约阅读时间需要 19 分钟。

## 摘要
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

你可能感兴趣的文章
Oracle 按表名导出数据
查看>>
HDU 1255 覆盖的面积[离散化 + 扫描线 + 线段树]
查看>>
【转】打包 压缩 命令tar zip
查看>>
【转】Android开发实践:自定义带消息循环(Looper)的工作线程
查看>>
HTML 字符实体
查看>>
WinCE下NTFS文件系统的注意点
查看>>
java 实现二分查找法
查看>>
手机端实现6位短信验证码input输入框效果(样式及代码方法)
查看>>
Java进阶学习:log4j的学习和使用
查看>>
LeetCode:分发饼干【455】
查看>>
Middle-help 终极实现元素水平垂直居中
查看>>
Java 将容器List里面的内容保存到数组
查看>>
2016-01-05 y原始数据(2)
查看>>
设置session超时的三种方式
查看>>
在 SharePoint Server 2016 本地环境中设置 OneDrive for Business
查看>>
python数据分析-数据处理
查看>>
【转】JAVA进阶之路
查看>>
java调用sqlserver存储过程
查看>>
前端多选插件bootstrap-select的使用
查看>>
建议博客园搭个威客平台,可行的发展方向和盈利方向
查看>>