关于RAS加密解密的一个文章,看着一个就够了!!!

RAS在网上看了太多文章很多都是不全的,复制过去各种问题,所有就有写个博客的想法,一是方便大家,二是方便自己,好了废话不多说了!

 

首先要注意一下证书级别

1024位的证书,加密时最大支持117个字节,解密时为128;
2048位的证书,加密时最大支持245个字节,解密时为256。

 

创建RAS工具类

package club.loserblog.blogreception.util;

import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import sun.misc.BASE64Decoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @ClassName RsaUtil
 * @Description TODO
 * @Author loser
 * @Date 2020/4/12 18:26
 **/
public class RsaUtil {
    private PublicKey commonKey;

    private PrivateKey secrecyKey;

    /*
    * 1024位的证书,加密时最大支持117个字节,解密时为128;
    * 2048位的证书,加密时最大支持245个字节,解密时为256。
    * */

    /**
     * @Author: dingmingming
     * @Description: 初始化公钥和密钥
     * @Date: 2020/4/12 18:37
     * @Param:
     * @Return:
     **/
    public RsaUtil() throws GeneralSecurityException{
        KeyPairGenerator pairGenerator = KeyPairGenerator.getInstance("RSA");
        pairGenerator.initialize(1024);
        KeyPair keyPair = pairGenerator.generateKeyPair();
        this.commonKey = keyPair.getPublic();
        this.secrecyKey = keyPair.getPrivate();
    }

    /**
     * @Author: dingmingming
     * @Description: 恢复公钥和密钥
     * @Date: 2020/4/12 18:37
     * @Param:
     * @Return:
     **/
    public RsaUtil(byte[] commonKey,byte[] secrecyKey)  throws GeneralSecurityException{
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(commonKey);
        this.commonKey = keyFactory.generatePublic(x509EncodedKeySpec);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(secrecyKey);
        this.secrecyKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    }

    /**
     * @Author: dingmingming
     * @Description: 将公钥转换为字节
     * @Date: 2020/4/12 18:39
     * @Param:
     * @Return:
     **/
    public byte[] getCommonKey(){
        return commonKey.getEncoded();
    }

    /**
     * @Author: dingmingming
     * @Description: 将私钥转换为字节
     * @Date: 2020/4/12 18:39
     * @Param:
     * @Return:
     **/
    public byte[] getSecrecyKey(){
        return secrecyKey.getEncoded();
    }

    /**
     * @Author: dingmingming
     * @Description: 利用公钥加密
     * @Date: 2020/4/12 18:45
     * @Param:
     * @Return:
     **/
    public String encryptStr(String encryptStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(1, this.commonKey);
        byte[] result = encryptStr.getBytes();
        int inputLen = result.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;

        for(int i = 0; inputLen - offSet > 0; offSet = i * 117) {
            byte[] cache;
            if(inputLen - offSet > 117) {
                cache = cipher.doFinal(result, offSet, 117);
            } else {
                cache = cipher.doFinal(result, offSet, inputLen - offSet);
            }

            out.write(cache, 0, cache.length);
            ++i;
        }

        byte[] encryptedData = out.toByteArray();
        out.close();
        String encryptData = Base64.getEncoder().encodeToString(encryptedData);
        return encryptData;
    }

    /**
     * @Author: dingmingming
     * @Description: 利用私钥解密
     * @Date: 2020/4/12 18:45
     * @Param:
     * @Return:
     **/
    public String decryptStr(String decryptStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(2, secrecyKey);
        byte[] result = new BASE64Decoder().decodeBuffer(decryptStr);
        int inputLen = result.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;

        for(int i = 0; inputLen - offSet > 0; offSet = i * 128) {
            byte[] cache;
            if(inputLen - offSet > 128) {
                cache = cipher.doFinal(result, offSet, 128);
            } else {
                cache = cipher.doFinal(result, offSet, inputLen - offSet);
            }

            out.write(cache, 0, cache.length);

            ++i;
        }

        byte[] decryptedData = out.toByteArray();
        out.close();
        String decryptData = new String(decryptedData,"UTF-8");
        return decryptData;
    }

}

获取前端数据处理

 public ModelAndView getBlogInfoForLook(HttpServletRequest request) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
        //blogId 代表的是前端的参数名称 这个大家应该都了解
        String blogId = request.getParameter("blogId").trim();
        //这里是重点要注意的 一定要替换
        //为什么要替换 因为参数传递的过程中 会将加密字符中的加号变成空格,因此我们需要将其替换回来 避免解密失败
        blogId = blogId.replaceAll(" ","+");

        //可以进行揭秘操作了
}

前端这一块我只是重点说一下解密 ,因为解密猜的坑有点多,加密都没有什么问题调用方法就行

好了就这样了!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的RAS加密解密程序的C++实现: ``` #include <iostream> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/err.h> using namespace std; // 生成RSA密钥对 RSA* generateRSAKeyPair(int keyLength) { RSA* rsa = NULL; BIGNUM* bn = NULL; FILE* fp = NULL; int ret = 0; // 创建RSA结构体 rsa = RSA_new(); if (rsa == NULL) { return NULL; } // 生成大数 bn = BN_new(); ret = BN_set_word(bn, RSA_F4); if (ret != 1) { goto free_all; } // 生成RSA密钥对 ret = RSA_generate_key_ex(rsa, keyLength, bn, NULL); if (ret != 1) { goto free_all; } // 返回生成的RSA密钥对 return rsa; free_all: if (rsa != NULL) { RSA_free(rsa); } if (bn != NULL) { BN_free(bn); } if (fp != NULL) { fclose(fp); } return NULL; } // RSA加密 int RSAEncrypt(const unsigned char* inData, int inLen, unsigned char* outData, RSA* rsa) { int ret = 0; // 获取RSA公钥 const BIGNUM* e = RSA_get0_e(rsa); const BIGNUM* n = RSA_get0_n(rsa); // 创建RSA公钥结构体 RSA* pubRSA = RSA_new(); ret = RSA_set0_key(pubRSA, const_cast<BIGNUM*>(n), const_cast<BIGNUM*>(e), NULL); if (ret != 1) { goto free_all; } // RSA加密 ret = RSA_public_encrypt(inLen, inData, outData, pubRSA, RSA_PKCS1_PADDING); if (ret < 0) { goto free_all; } // 释放RSA公钥结构体 RSA_free(pubRSA); // 返回加密数据长度 return ret; free_all: if (pubRSA != NULL) { RSA_free(pubRSA); } return -1; } // RSA解密 int RSADecrypt(const unsigned char* inData, int inLen, unsigned char* outData, RSA* rsa) { int ret = 0; // 获取RSA私钥 const BIGNUM* d = RSA_get0_d(rsa); const BIGNUM* n = RSA_get0_n(rsa); // 创建RSA私钥结构体 RSA* priRSA = RSA_new(); ret = RSA_set0_key(priRSA, const_cast<BIGNUM*>(n), const_cast<BIGNUM*>(d), NULL); if (ret != 1) { goto free_all; } // RSA解密 ret = RSA_private_decrypt(inLen, inData, outData, priRSA, RSA_PKCS1_PADDING); if (ret < 0) { goto free_all; } // 释放RSA私钥结构体 RSA_free(priRSA); // 返回解密数据长度 return ret; free_all: if (priRSA != NULL) { RSA_free(priRSA); } return -1; } int main() { RSA* rsa = NULL; unsigned char inData[1024] = "Hello, World!"; unsigned char outData[1024] = {0}; int outLen = 0; // 生成RSA密钥对 rsa = generateRSAKeyPair(1024); if (rsa == NULL) { cout << "Generate RSA key pair failed!" << endl; return -1; } // RSA加密 outLen = RSAEncrypt(inData, strlen((const char*)inData), outData, rsa); if (outLen < 0) { cout << "RSA encrypt failed!" << endl; return -1; } // RSA解密 outLen = RSADecrypt(outData, outLen, inData, rsa); if (outLen < 0) { cout << "RSA decrypt failed!" << endl; return -1; } // 输出解密结果 cout << "RSA decrypt result: " << inData << endl; // 释放RSA密钥对 RSA_free(rsa); return 0; } ``` 这个程序使用了OpenSSL库来实现RAS加密解密。在程序中,先使用`generateRSAKeyPair`函数生成RSA密钥对,然后使用`RSAEncrypt`函数来加密数据,使用`RSADecrypt`函数来解密数据。程序最终输出解密结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值