欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c# rsa注册实现加密文字

程序员文章站 2024-02-22 13:33:52
复制代码 代码如下:rsacryptoserviceprovider rsa = new rsacryptoserviceprovider(); private void...

复制代码 代码如下:

rsacryptoserviceprovider rsa = new rsacryptoserviceprovider();

private void btencoding_click(object sender, eventargs e)
{
    if (mbox.text == "")
    {
        messagebox.show("加密文字信息不能为空!");
        return;
    }
    if (publickey.text == "")
    {
        messagebox.show("请生成公钥!");
        return;
    }
    try
    {
        string pubkey = publickey.text;
        byte[] mw = asciiencoding.ascii.getbytes(mbox.text);
        rsacryptoserviceprovider crypt = new rsacryptoserviceprovider();
        crypt.fromxmlstring(pubkey);

        mw = crypt.encrypt(mw, false);
        string encryttext = convert.tobase64string(mw);//加密后的结果怎样处理解决显示乱码问题
        cbox.text = encryttext;
    }
    catch
    {
        messagebox.show("请检查是否打开公匙或者公匙是否损坏!");
    }
}

private void btdecoding_click(object sender, eventargs e)
{
    if (cbox.text == "")
    {
        messagebox.show("请生成密钥!");
        return;
    }
    try
    {
        rsacryptoserviceprovider crypt = new rsacryptoserviceprovider();
        byte[] bytes = convert.frombase64string(cbox.text);//从密文框中取出的字符串正确处理才能解密
        string prtkey = privatekey.text;
        crypt.fromxmlstring(prtkey);
        byte[] decryptbyte = crypt.decrypt(bytes, false);
        string decrypttext = encoding.default.getstring(decryptbyte);

        mbox.text = decrypttext;
    }
    catch (cryptographicexception ex)
    {
        //messagebox.show("请检查是否打开私匙或者私匙是否损坏!");
        messagebox.show(ex.tostring());
    } if (cbox.text == "")
    {
        messagebox.show("请生成密钥!");
        return;
    }
}