首页 > 其他分享 >RSA非对称加密和MD5不可逆加密代码示例

RSA非对称加密和MD5不可逆加密代码示例

时间:2023-01-11 15:25:00浏览次数:35  
标签:公钥 私钥 String 示例 RSA return static 加密

加密算法可以分为三大类:

  • 对称加密算法:DES 
  • 非对称加密算法: RSA
  • Hash算法: MD5

登陆密码加密流程:

web端用公钥加密密码,server端用私钥解码,将解出的明文用MD5加密后存入数据库或与数据库的密码比较,这种方式会有中间人攻击的问题,只能用https方式,

如果用http方式,需要在web端生成公钥和私钥,将公钥发给server端,server端生成一串随机字符串并用公钥加密发给web端,web端用私钥解码并拼接上密码组成新的

字符串,将随机字符串作为AES加密算法的密码对密码进行加密发送给server端,server端使用随机字符串对新的字符串进行解密,server端系解析解密后的字符串,校验随机字符串是否一致.

RSA:

package login;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {
    static final Base64.Decoder decoder = Base64.getDecoder();
    static final Base64.Encoder encoder = Base64.getEncoder();

    public static void main(String[] args) throws Exception {
        // 随机生成一对密钥(包含公钥和私钥)
        KeyPair keyPair = generateKeyPair();
        // 获取 公钥 和 私钥
        RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
        // 创建 已编码的公钥规格
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
        // 创建 已编码的私钥规格
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(priKey.getEncoded());
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        // 原文数据
        String data = "你好, World!";
        // 客户端: 用公钥加密原文, 返回加密后的数据
        byte[] cipherData = encrypt(data.getBytes(), publicKey);
        // 服务端: 用私钥解密数据, 返回原文
        byte[] plainData = decrypt(cipherData, privateKey);
        // 输出密文
        System.out.println(new String(cipherData));
        // 输出查看解密后的原文
        System.out.println(new String(plainData));  // 结果打印: 你好, World
    }



    /**
     * 随机生成密钥对(包含公钥和私钥)
     */
    private static KeyPair generateKeyPair() throws Exception {
        // 获取指定算法的密钥对生成器
        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器(密钥长度要适中, 太短不安全, 太长加密/解密速度慢)
        gen.initialize(2048);
        // 随机生成一对密钥(包含公钥和私钥)
        KeyPair keyPair = gen.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        //公钥私钥base64编码
        String publicKeyString = new String(encoder.encode(rsaPublicKey.getEncoded()));
        String privateKeyString = new String(encoder.encode(rsaPrivateKey.getEncoded()));
        return keyPair;
    }
    /**
     * 公钥加密数据
     */
    private static byte[] encrypt(byte[] plainData, PublicKey pubKey) throws Exception {
        // 获取指定算法的密码器
        Cipher cipher = Cipher.getInstance("RSA");
        // 初始化密码器(公钥加密模型)
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        // 加密数据, 返回加密后的密文
        return cipher.doFinal(plainData);
    }
    /**
     * 私钥解密数据
     */
    private static byte[] decrypt(byte[] cipherData, PrivateKey priKey) throws Exception {
        // 获取指定算法的密码器
        Cipher cipher = Cipher.getInstance("RSA");
        // 初始化密码器(私钥解密模型)
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        // 解密数据, 返回解密后的明文
        return cipher.doFinal(cipherData);
    }

}

MD5加盐:

package login;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordEncoder {
    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
 
    private Object salt;
    private String algorithm;
 
    public PasswordEncoder(Object salt, String algorithm) {
        this.salt = salt;
        this.algorithm = algorithm;
    }
 
    public String encode(String rawPass) {
        String result = null;
        try {
            //参数可以是"MD5","SHA"等
            MessageDigest md = MessageDigest.getInstance(algorithm);
            //加密后的字符串
            result = byteArrayToHexString(md.digest(mergePasswordAndSalt(rawPass).getBytes("utf-8")));
        } catch (Exception ex) {
        }
        return result;
    }
 
    public boolean isPasswordValid(String encPass, String rawPass) {
        String pass1 = "" + encPass;
        String pass2 = encode(rawPass);
 
        return pass1.equals(pass2);
    }
 
    private String mergePasswordAndSalt(String password) {
        if (password == null) {
            password = "";
        }
 
        if ((salt == null) || "".equals(salt)) {
            return password;
        } else {
            return password + "{" + salt.toString() + "}";
        }
    }
 
    /**
     * 转换字节数组为16进制字串
     * @param b 字节数组
     * @return 16进制字串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }
 
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
 
 
    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String salt = "be5e0323a9195ade5f56695ed9f2eb6b036f3e6417115d0cbe2fb9d74d8740406838dc84f152014b39a2414fb3530a40bc028a9e87642bd03cf5c36a1f70801e";
        PasswordEncoder encoderMd5 = new PasswordEncoder(salt, "MD5");
        String encode = encoderMd5.encode("zxp52077");
        System.out.println(encode);
        boolean passwordValid = encoderMd5.isPasswordValid("c21feb87d79fd42e4336e4c231785ff9", "test");
        System.out.println(passwordValid);
 
        PasswordEncoder encoderSha = new PasswordEncoder(salt, "SHA");
        String pass2 = encoderSha.encode("test");
        System.out.println(pass2);
        boolean passwordValid2 = encoderSha.isPasswordValid("409cf43cbdc92e1979018b2e2fdc60c7f07673e9", "test");
        System.out.println(passwordValid2);


    }
 
}

 

标签:公钥,私钥,String,示例,RSA,return,static,加密
From: https://www.cnblogs.com/1--2/p/17043846.html

相关文章

  • 联邦学习 (FL) 中常见的3种模型聚合方法的 Tensorflow 示例
    联合学习(FL)是一种出色的ML方法,它使多个设备(例如物联网(IoT)设备)或计算机能够在模型训练完成时进行协作,而无需共享它们的数据。“客户端”是FL中使用的计算机和......
  • Sharding-Proxy 分库分表示例
    我司当前的一个数据库,分了51个数据库及表,使用 Sharding-JDBC去独立连接。(Sharding-JDBC是Sharding-Sphere的第一个产品,也是Sharding-Sphere的前身。它定位为轻量级Java框......
  • Python 发电子邮件示例
    #!/usr/bin/envpython#-*-coding:utf-8-*-#python3.5importreimportosimportsmtplibfromioimportStringIOfromvalidate_emailimportvalidate_emailfromema......
  • SQL Server 2016 Always Encrypted(始终加密)
    AlwaysEncrypted功能旨在保护AzureSQLDatabase或SQLServer数据库中存储的敏感数据,如信用卡号或身份证号(例如美国社会安全号码)。始终加密允许客户端对客户端应用程......
  • 【加密与解密】第三章⑦
    其他功能1.图形化功能这种模式比文本模式的可视性更好,用户更容易看清函数的代码流程。通过空格切换文本模式或者图形化模式。2.修改可执行文件使用IDA可以直接修改二进......
  • Golang实现16/32位MD5加密
    转自:Golang实现16/32位MD5加密packagemainimport( "crypto/md5" "encoding/hex" "fmt")//返回一个32位md5加密后的字符串funcGetMD5Encode(datastring)stri......
  • 知行之桥传输带附件的文件示例
    在大多数的项目中,交易伙伴往往只要求传输报文消息,业务数据经由报文内容来进行传输。但有些交易伙伴也会要求传输带附件的文件,比如在与大众和延锋汽车YFAI对接的项目当中,交......
  • SimpleAdmin手摸手教学之:国密加密
    一、什么是国密加密二、国密实现本系统实现了国密SM2和SM4加解密,可以在SimpleAdmin.Core下的Utils->Cryptogram文件夹下找到。2.1SM2Sm2加解密需要配置公钥和私钥,在......
  • 设计器demo示例数据库连接不上
    首先看下示例的 demo数据库是否启动。启动后可以看下左侧的控制台是否有错误,如果启动后链接还有问题,那么将设计器关闭,然后看下系统进程是否有重新连接。......
  • java SSL加密传输
    网络传输是存在风险的,因此对服服务端和客户端进行安全校验和传输信息的加密就显得非常的重要。上面一句有点拗口,简单解释如下文: 当客户使用SSL向站点服务器发送请求时......