Security RSA非对称加密

 pom

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-rsa</artifactId>
            <version>1.0.9.RELEASE</version>
        </dependency>
RsaUtils
package com.example.demo.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by Eleven on 2022/10/28
 */
public class RsaUtils {

    private static final String algorithm = "RSA";

    /**
     * 构建RSA密钥对
     *
     * @return 生成后的公私钥信息
     */
    public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        String publicKeyString = Base64.encodeBase64String(publicKey.getEncoded());
        String privateKeyString = Base64.encodeBase64String(privateKey.getEncoded());
        return new RsaKeyPair(publicKeyString, privateKeyString);
    }

    /**
     * 公钥加密
     *
     * @param publicKeyString 公钥
     * @param text            待加密的文本
     * @return 加密后的文本
     */
    public static String encryptByPublicKey(String publicKeyString, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

    /**
     * 公钥解密
     *
     * @param publicKeyString 公钥
     * @param text            待解密的信息
     * @return 解密后的文本
     */
    public static String decryptByPublicKey(String publicKeyString, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 私钥加密
     *
     * @param privateKeyString 私钥
     * @param text             待加密的信息
     * @return 加密后的文本
     */
    public static String encryptByPrivateKey(String privateKeyString, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }


    /**
     * 私钥解密
     *
     * @param privateKeyString 私钥
     * @param text             待解密的文本
     * @return 解密后的文本
     */
    public static String decryptByPrivateKey(String privateKeyString, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }


    public static void main(String[] args) throws Exception {
        RsaUtils.RsaKeyPair rsaKeyPair = null;
        try {
            rsaKeyPair = RsaUtils.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println("公钥:");
        System.out.println(rsaKeyPair.getPublicKey());
        System.out.println("私钥:");
        System.out.println(rsaKeyPair.getPrivateKey());
        String phone = "aaaaaaaaaaaaaaa";
        //公钥加密,私钥解密
        System.out.println("公钥加密,私钥解密");
        String phoneRsa = RsaUtils.encryptByPublicKey(rsaKeyPair.getPublicKey(), phone);
        System.out.println("加密后:" + phoneRsa);
        String phoneRsa2 = RsaUtils.decryptByPrivateKey(rsaKeyPair.getPrivateKey(), phoneRsa);
        System.out.println("解密后:" + phoneRsa2);
        //私钥加密,公钥解密
        System.out.println("私钥加密,公钥解密");
        String phoneRsa3 = RsaUtils.encryptByPrivateKey(rsaKeyPair.getPrivateKey(), phone);
        System.out.println("加密后:" + phoneRsa3);
//        phoneRsa3 = phoneRsa3.substring(0, phoneRsa3.length() - 2);// 测试完整性, 删除2字符 是否还能解密
        String phoneRsa4 = RsaUtils.decryptByPublicKey(rsaKeyPair.getPublicKey(), phoneRsa3);
        System.out.println("解密后:" + phoneRsa4);
    }

    static class RsaKeyPair {
        private String publicKey;
        private String privateKey;

        public RsaKeyPair(String publicKey, String privateKey) {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }

        public String getPublicKey() {
            return publicKey;
        }

        public void setPublicKey(String publicKey) {
            this.publicKey = publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以为您提供一个简单的RSA非对称密码算法的Java实现,代码如下: ```java import java.math.BigInteger; import java.security.SecureRandom; public class RSA { private BigInteger privateKey; private BigInteger publicKey; private BigInteger modulus; private int bitLength = 1024; private SecureRandom random; // 构造函数 public RSA() { random = new SecureRandom(); BigInteger p = BigInteger.probablePrime(bitLength, random); BigInteger q = BigInteger.probablePrime(bitLength, random); BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); modulus = p.multiply(q); publicKey = BigInteger.probablePrime(bitLength / 2, random); while (phi.gcd(publicKey).compareTo(BigInteger.ONE) > 0 && publicKey.compareTo(phi) < 0) { publicKey.add(BigInteger.ONE); } privateKey = publicKey.modInverse(phi); } // 获取私钥 public BigInteger getPrivateKey() { return privateKey; } // 获取公钥 public BigInteger getPublicKey() { return publicKey; } // 获取模数 public BigInteger getModulus() { return modulus; } // 加密 public byte[] encrypt(byte[] message) { return (new BigInteger(message)).modPow(publicKey, modulus).toByteArray(); } // 解密 public byte[] decrypt(byte[] message) { return (new BigInteger(message)).modPow(privateKey, modulus).toByteArray(); } } ``` 使用该RSA类进行加密和解密的示例代码如下: ```java public static void main(String[] args) { RSA rsa = new RSA(); // 明文 String message = "Hello, world!"; // 加密 byte[] encryptedMessage = rsa.encrypt(message.getBytes()); // 解密 byte[] decryptedMessage = rsa.decrypt(encryptedMessage); System.out.println("明文: " + message); System.out.println("加密后的密文: " + new String(encryptedMessage)); System.out.println("解密后的明文: " + new String(decryptedMessage)); } ``` 注意:该实现只是一个简单的示例,实际使用中需要加入更多的安全措施,比如添加数字签名等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值