RSA例子

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

public class RSATest {
    public RSATest() {
    }

    public static void generateKey() {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(1024);
            KeyPair kp = kpg.genKeyPair();
            PublicKey pbkey = kp.getPublic();
            PrivateKey prkey = kp.getPrivate();
            // 保存公钥
            FileOutputStream f1 = new FileOutputStream("pubkey.dat");
            ObjectOutputStream b1 = new ObjectOutputStream(f1);
            b1.writeObject(pbkey);
            // 保存私钥
            FileOutputStream f2 = new FileOutputStream("privatekey.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(prkey);
        } catch (Exception e) {
        }
    }

    public static void encrypt() throws Exception {
        String s = "Hello World!";
        // 获取公钥及参数e,n
        FileInputStream f = new FileInputStream("pubkey.dat");
        ObjectInputStream b = new ObjectInputStream(f);
        RSAPublicKey pbk = (RSAPublicKey) b.readObject();
        BigInteger e = pbk.getPublicExponent();
        BigInteger n = pbk.getModulus();
        System.out.println("e= " + e);
        System.out.println("n= " + n);
        // 获取明文m
        byte ptext[] = s.getBytes("UTF-8");
        BigInteger m = new BigInteger(ptext);
        // 计算密文c
        BigInteger c = m.modPow(e, n);

        // 保存密文
        String cs = c.toString();
        System.out.println("保存的密文:" + cs);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("encrypt.dat")));
        out.write(cs, 0, cs.length());
        out.close();
    }

    public static void decrypt() throws Exception {
        // 读取密文
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("encrypt.dat")));
        String ctext = in.readLine();
        System.out.println("读取的密文:" + ctext);

        BigInteger c = new BigInteger(ctext);
        // 读取私钥
        FileInputStream f = new FileInputStream("privatekey.dat");
        ObjectInputStream b = new ObjectInputStream(f);
        RSAPrivateKey prk = (RSAPrivateKey) b.readObject();

        // 获取私钥参数及解密
        BigInteger d = prk.getPrivateExponent();
        System.out.println("d= " + d);

        BigInteger n = prk.getModulus();
        System.out.println("n= " + n);

        BigInteger m = c.modPow(d, n);
        // 显示解密结果
        System.out.println("m= " + m);
        byte[] mt = m.toByteArray();
        System.out.println("PlainText is ");
        for (int i = 0; i < mt.length; i++) {
            System.out.print((char) mt[i]);
        }
    }

    public static void main(String args[]) {
        try {
            generateKey();
            encrypt();
            decrypt();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

另附:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;

/**
 * @author JavaDigest
 * 
 */
public class EncryptionUtil {

  /**
   * String to hold name of the encryption algorithm.
   */
  public static final String ALGORITHM = "RSA";

  /**
   * String to hold the name of the private key file.
   */
  public static final String PRIVATE_KEY_FILE = "C:/keys/private.key";

  /**
   * String to hold name of the public key file.
   */
  public static final String PUBLIC_KEY_FILE = "C:/keys/public.key";

  /**
   * Generate key which contains a pair of private and public key using 1024
   * bytes. Store the set of keys in Prvate.key and Public.key files.
   * 
   * @throws NoSuchAlgorithmException
   * @throws IOException
   * @throws FileNotFoundException
   */
  public static void generateKey() {
    try {
      final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
      keyGen.initialize(1024);
      final KeyPair key = keyGen.generateKeyPair();

      File privateKeyFile = new File(PRIVATE_KEY_FILE);
      File publicKeyFile = new File(PUBLIC_KEY_FILE);

      // Create files to store public and private key
      if (privateKeyFile.getParentFile() != null) {
        privateKeyFile.getParentFile().mkdirs();
      }
      privateKeyFile.createNewFile();

      if (publicKeyFile.getParentFile() != null) {
        publicKeyFile.getParentFile().mkdirs();
      }
      publicKeyFile.createNewFile();

      // Saving the Public key in a file
      ObjectOutputStream publicKeyOS = new ObjectOutputStream(
          new FileOutputStream(publicKeyFile));
      publicKeyOS.writeObject(key.getPublic());
      publicKeyOS.close();

      // Saving the Private key in a file
      ObjectOutputStream privateKeyOS = new ObjectOutputStream(
          new FileOutputStream(privateKeyFile));
      privateKeyOS.writeObject(key.getPrivate());
      privateKeyOS.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  /**
   * The method checks if the pair of public and private key has been generated.
   * 
   * @return flag indicating if the pair of keys were generated.
   */
  public static boolean areKeysPresent() {

    File privateKey = new File(PRIVATE_KEY_FILE);
    File publicKey = new File(PUBLIC_KEY_FILE);

    if (privateKey.exists() && publicKey.exists()) {
      return true;
    }
    return false;
  }

  /**
   * Encrypt the plain text using public key.
   * 
   * @param text
   *          : original plain text
   * @param key
   *          :The public key
   * @return Encrypted text
   * @throws java.lang.Exception
   */
  public static byte[] encrypt(String text, PublicKey key) {
    byte[] cipherText = null;
    try {
      // get an RSA cipher object and print the provider
      final Cipher cipher = Cipher.getInstance(ALGORITHM);
      // encrypt the plain text using the public key
      cipher.init(Cipher.ENCRYPT_MODE, key);
      cipherText = cipher.doFinal(text.getBytes());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return cipherText;
  }

  /**
   * Decrypt text using private key.
   * 
   * @param text
   *          :encrypted text
   * @param key
   *          :The private key
   * @return plain text
   * @throws java.lang.Exception
   */
  public static String decrypt(byte[] text, PrivateKey key) {
    byte[] dectyptedText = null;
    try {
      // get an RSA cipher object and print the provider
      final Cipher cipher = Cipher.getInstance(ALGORITHM);

      // decrypt the text using the private key
      cipher.init(Cipher.DECRYPT_MODE, key);
      dectyptedText = cipher.doFinal(text);

    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return new String(dectyptedText);
  }

  /**
   * Test the EncryptionUtil
   */
  public static void main(String[] args) {

    try {

      // Check if the pair of keys are present else generate those.
      if (!areKeysPresent()) {
        // Method generates a pair of keys using the RSA algorithm and stores it
        // in their respective files
        generateKey();
      }

      final String originalText = "Text to be encrypted ";
      ObjectInputStream inputStream = null;

      // Encrypt the string using the public key
      inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
      final PublicKey publicKey = (PublicKey) inputStream.readObject();
      final byte[] cipherText = encrypt(originalText, publicKey);

      // Decrypt the cipher text using the private key.
      inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
      final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
      final String plainText = decrypt(cipherText, privateKey);

      // Printing the Original, Encrypted and Decrypted Text
      System.out.println("Original: " + originalText);
      System.out.println("Encrypted: " +cipherText.toString());
      System.out.println("Encrypted: " +DatatypeConverter.printBase64Binary(cipherText));
      System.out.println("Decrypted: " + plainText);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
<think>好的,我现在需要帮助用户找到易语言实现RSA加解密的示例代码或教程。首先,用户之前的问题是关于PHP的RSA2加密解密和接口签名验签,但现在转向了易语言,这说明用户可能需要在不同的编程环境中实现类似的功能。我需要确保提供的示例代码符合易语言的语法和常用库。 首先,我需要回忆易语言中处理RSA加解密的常用方法。易语言通常使用第三方模块或调用Windows API来实现加密功能。例如,可能用到“加解密支持库”或者“OpenSSL动态链接库”。用户需要的是示例代码,所以应该提供具体的代码片段,并解释关键部分。 接下来,我需要检查用户提到的引用内容,虽然引用是关于PHP的,但其中提到的一些注意事项,比如明文长度限制和分段加密,可能同样适用于易语言。因此,在回答中需要提到这些注意事项,帮助用户避免常见错误。 然后,我需要确保代码的正确性。例如,在易语言中生成RSA密钥对可能需要调用相应的函数,而加密和解密函数的使用方式可能与PHP不同。需要确认函数名称和参数是否正确,比如是否使用“RSA公钥加密”和“RSA私钥解密”这样的命令。 另外,用户可能需要了解如何获取和安装所需的支持库或DLL文件,因此在回答中应该包含相关资源的获取方式,比如官方网站或论坛链接,但需要注意不能提供外部链接,所以可能需要建议用户搜索特定关键词。 同时,考虑到用户可能需要调试代码,应该提醒常见的错误点,比如密钥格式是否正确、数据长度限制以及编码问题(如Base64处理)。此外,分段加密的实现方法也是一个重要的点,需要简要说明。 最后,生成的相关问题应该覆盖用户可能遇到的后续疑问,比如异常处理、密钥生成、性能优化和应用场景等,这样可以帮助用户进一步深入学习和解决问题。</think>以下是易语言实现RSA加解密的示例代码及关键步骤解析: ```vb .版本 2 .程序集 窗口程序集_启动窗口 .子程序 _按钮_加密_被单击 变量 公钥内容, 明文数据, 加密结果, 字节集数据 公钥内容 = 读入文本文件("public.pem") //读取公钥文件 明文数据 = 编辑框_明文.内容 加密结果 = 加解密操作.RSA公钥加密(明文数据, 公钥内容, #填充方式_PKCS1) 编辑框_密文.内容 = 到文本(Base64编码(加密结果)) .子程序 _按钮_解密_被单击 变量 私钥内容, 密文数据, 解密结果 私钥内容 = 读入文本文件("private.pem") //读取私钥文件 密文数据 = Base64解码(到字节集(编辑框_密文.内容)) 解密结果 = 加解密操作.RSA私钥解密(密文数据, 私钥内容, #填充方式_PKCS1) 编辑框_解密结果.内容 = 到文本(解密结果) ``` 关键要素说明: 1. 需要引用`加解密支持库`或使用`OpenSSL动态链接库` 2. 密钥文件需使用PEM格式,支持PKCS#1和PKCS#8格式[^1] 3. 加密前建议对数据进行Base64编码处理 4. 明文长度限制为:密钥长度/8 - 11字节(PKCS1填充)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值