白白白湫 2024-04-23 16:53 采纳率: 25.7%
浏览 21
已结题

django中rsa加解密,vue前端中怎么随之加解密

django中加解密如下:

def decode_pubkey(getpub):  # 解码公钥
    public_key_bytes = base64.b64decode(getpub)
    server_public_key = serialization.load_der_public_key(
        public_key_bytes,
        backend=default_backend()
    )
    # print(server_public_key)
    return server_public_key


def date_encode(getpub, original_string):  

    original_string_bytes = original_string.encode("utf-8")
    ciphertext = decode_pubkey(getpub).encrypt(
        original_string_bytes,
        padding.PKCS1v15()
    )

    encrypted_data_string = base64.b64encode(ciphertext).decode('utf-8')

    # print("Encrypted data:", encrypted_data_string)

    return encrypted_data_string


def date_decode(encode_str, private_key_str):
    private_key_bytes = base64.b64decode(private_key_str)
    ciphertext_bytes = base64.b64decode(encode_str)

    private_key = serialization.load_der_private_key(
        private_key_bytes,
        password=None,
        backend=default_backend()
    )

    plaintext = private_key.decrypt(
        ciphertext_bytes,
        padding.PKCS1v15()
    )

    plaintext1 = plaintext.decode('utf-8') 

    return plaintext1

公私钥转化为der格式,前端vue中该怎么进行加解密,对传递到django数据加密,拿到django传回来的数据进行解密

  • 写回答

5条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-04-23 16:53
    关注

    引自免费微信小程序:皆我百晓生

    在Vue前端实现与Django后端类似的RSA加解密功能,你需要安装一个支持RSA的JavaScript库。这里推荐使用node-rsa库。首先,在你的Vue项目中安装这个库:

    npm install node-rsa --save
    

    接下来,根据提供的Python代码,我们将编写对应的JavaScript版本。

    首先,创建一个RSA服务文件(例如:rsaService.js):

    import NodeRSA from 'node-rsa';
    
    const rsa = new NodeRSA();
    
    export function decodePubkey(getpub) {
      const buffer = Buffer.from(getpub, 'base64');
      const key = rsa.importKey(buffer.toString(), 'pkcs8-public-pem', { encryptionScheme: 'pkcs1' });
      return key;
    }
    
    export function encryptData(originalString, getpub) {
      const originalStringBytes = Buffer.from(originalString, 'utf8');
      const ciphertext = rsa.encrypt(originalStringBytes, 'pkcs1');
    
      const encryptedDataBase64 = ciphertext.toString('base64');
      return encryptedDataBase64;
    }
    
    export function decryptData(encryptedData, privateKeyStr) {
      const ciphertextBase64 = Buffer.from(encryptedData, 'base64').toString();
      const decryptedBuffer = rsa.decrypt(Buffer.from(ciphertextBase64, 'base64'), 'pkcs1');
    
      const plaintext = decryptedBuffer.toString('utf8');
      return plaintext;
    }
    

    然后在你的Vue组件中使用这些函数进行加解密操作:

    <template>
      <!-- Your template code here -->
    </template>
    
    <script>
    import { decodePubkey, encryptData, decryptData } from '@/services/rsaService';
    
    export default {
      methods: {
        async sendDataToServer(data) {
          // 加密数据
          const publicKey = await this.getPublicKeyFromServer(); // 假设你从服务器获取了公钥
          const encryptedData = encryptData(data, publicKey);
    
          // 发送到后端
          // axios.post('/your-api-endpoint', { encryptedData })
          //   .then(response => console.log(response))
          //   .catch(error => console.error(error));
        },
    
        async receiveAndDecryptData(encryptedData, privateKeyStr) {
          // 解密数据
          const decryptedData = decryptData(encryptedData, privateKeyStr);
    
          // 使用解密后的数据
          console.log('Decrypted data:', decryptedData);
        },
      },
    };
    </script>
    

    注意:在实际应用中,公钥和私钥应该安全地存储,并且只在适当的地方使用。这里的示例仅用于演示目的。在生产环境中,确保妥善处理公钥和私钥,防止泄露。此外,为了保护敏感信息,建议在传输过程中使用HTTPS或其他加密机制。

    在Django后端发送给前端的数据应该是经过加密的,前端接收到数据后再调用decryptData方法进行解密。同样,前端向后端发送数据时,应先调用encryptData方法对数据进行加密。

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月24日
  • 创建了问题 4月23日

悬赏问题

  • ¥15 一道ban了很多东西的pyjail题
  • ¥15 关于#r语言#的问题:如何将生成的四幅图排在一起,且对变量的赋值进行更改,让组合的图漂亮、美观@(相关搜索:森林图)
  • ¥15 C++识别堆叠物体异常
  • ¥15 微软硬件驱动认证账号申请
  • ¥15 有人知道怎么在R语言里下载Git上的miceco这个包吗
  • ¥15 GPT写作提示指令词
  • ¥20 根据动态演化博弈支付矩阵完成复制动态方程求解和演化相图分析等
  • ¥20 关于DAC输出1.000V对分辨率和精度的要求
  • ¥15 华为超融合部署环境下RedHat虚拟机分区扩容问题
  • ¥15 哪位能做百度地图导航触点播报?