Java加密解密大全(MD5、RSA)

发布时间:2024年01月10日

一、MD5加密

密文形式:5eb63bbbe01eeed093cb22bb8f5acdc3

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法!");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static void main(String[] args) {
        System.out.println(stringToMD5("hello world"));
    }
}

二、RSA加解密(公加私解,私加公解)

密文形式:W1WTmVo870wB9t6/kGxTV4b2wuI7iHGLNDP+24SyD45==

package com.bytedance.frameworks.core.encrypt;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSA {

    public static String RSAEncryptByPublickey(String str, String publicKey) throws Exception {
        /* RSA通过公钥加密 */
        
        //base64编码的公钥
        byte[] decoded = Base64.decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encode(cipher.doFinal(str.getBytes("UTF-8")));

        return outStr;
    }

    public static String RSAEncryptByPrivatekey(String content,String private_key) {
        /* RSA通过私钥加密 */

        String charset = "utf-8";
        try {

            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(private_key));

            KeyFactory keyf = KeyFactory.getInstance("RSA");

            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");

            signature.initSign(priKey);

            signature.update(content.getBytes(charset));

            byte[] signed = signature.sign();

            return Base64.encode(signed);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    public static String RSADecryptByPublicKey(String str, String publicKey) throws Exception {
        /* RSA通过公钥解密 */

        byte[] inputByte = Base64.decode(str);
        //base64编码的私钥
        byte[] decoded = Base64.decode(publicKey);
        PublicKey pubKey =  KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, pubKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    public static String RSADecryptByPrivateKey(String data, String privateKey) throws Exception {
        /* RSA通过私钥解密 */

        byte[] inputByte = Base64.decode(data);
        //base64编码的私钥
        byte[] decoded = Base64.decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        String str1 = outStr.substring(0,32);
        String hex = base64Tohex(str1);
        String Des_key = hex.substring(0,16);
        return Des_key;


    }
    
    public static String byteToHex(byte b)
    {
        String hexString = Integer.toHexString(b & 0xFF);
        //由于十六进制是由0~9、A~F来表示1~16,所以如果Byte转换成Hex后如果是<16,就会是一个字符(比如A=10),通常是使用两个字符来表示16进制位的,
        //假如一个字符的话,遇到字符串11,这到底是1个字节,还是1和1两个字节,容易混淆,如果是补0,那么1和1补充后就是0101,11就表示纯粹的11
        if (hexString.length() < 2)
        {
            hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
        }
        return hexString.toUpperCase();
    }
    public static String bytesToHex(byte[] bytes)
    {
        StringBuffer sb = new StringBuffer();
        if (bytes != null && bytes.length > 0)
        {
            for (int i = 0; i < bytes.length; i++) {
                String hex = byteToHex(bytes[i]);
                sb.append(hex);
            }
        }
        return sb.toString();
    }

    public static String base64Tohex(String bstxt){
        byte[] bs = Base64.decode(bstxt);
        String hex = bytesToHex(bs);
        return hex.toLowerCase();

    }
    
    
    public static void main(String[] args) {

    }
}

三、RSA私钥加密

package com.bytedance.frameworks.core.encrypt;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSAEncrypt {
    public static final String KEY_ALGORTHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "SHA256WithRSA";

    public static String RSAEnByPrivate(String content,String PrivateKey) throws Exception {

        // BC模式
        java.security.Security.addProvider(
                new org.bouncycastle.jce.provider.BouncyCastleProvider()
        );

        //解密私钥
        byte[] keyBytes = decryptBASE64(PrivateKey);
        // byte[] keyBytes = privateKey.getBytes();

        //构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        //指定加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
        //取私钥匙对象
        PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        //用私钥对信息生成数字签名

        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateKey2);
        signature.update(content.getBytes());

        return Base64.encode(signature.sign());
    }
    public static byte[] decryptBASE64(String key) throws Exception {


        return (new BASE64Decoder()).decodeBuffer(key);
    }

    public static void main(String[] args) throws Exception  {
        String content = "xxx";
        String PrivateKey = "xxx";
        System.out.println(RSAEnByPrivate(content,PrivateKey));
    }



}

四、RSA私钥加密PKCS1Padding模式

    public static String encryptByPrivateKey(String content,String privateKey) throws Exception {
        byte[] keyBytes = Base64.decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey PrivateKey = keyFactory.generatePrivate(keySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, PrivateKey);
        byte[] cipherText = cipher.doFinal(content.getBytes());
        String cipherStr = Base64.encode(cipherText);
        return cipherStr;
    }
文章来源:https://blog.csdn.net/weixin_51111267/article/details/131829528
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。