想将明文用rsa密钥加密,密钥保存在byte数组中。
代码如下:
Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, ???);
问题是在cipher的第二个参数中,需要填入Key类型的rsa密钥。我的rsa密钥原来是保存在文本文件中的,读出来之后变成了Byte数组类型,请问如何把它转换成Key类型(或者RSAPrivateKey)?

解决方案 »

  1.   

    你看看RSAPrivateKey这个类有哪些构造方法啊,如果能够直接接受byte[]作为参数,那不就很简单了,如果不能够直接接受,看它构造方法能够接受什么,想办法转换一下。
      

  2.   

    RSAPrivateKey不接受以byte[]为参数的构造函数。
      

  3.   

    我以前做的,给你参考一下:
      private Key getKeyFromFile(String filename, int type) throws FileNotFoundException {
          FileInputStream fis = null;
          fis = new FileInputStream(filename);
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          int b;
          try {
              while ((b = fis.read()) != -1) {
                  baos.write(b);
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
          byte[] keydata = baos.toByteArray();      Key key = null;
          try {
              KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
              switch (type) {
                  case PRIVATE:
                      PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(keydata);
                      key = kf.generatePrivate(encodedPrivateKey);
                      return key;
                  case PUBLIC:
                      X509EncodedKeySpec encodedPublicKey = new X509EncodedKeySpec(keydata);
                      key = kf.generatePublic(encodedPublicKey);
                      return key;
              }
          } catch (NoSuchAlgorithmException e) {
              e.printStackTrace();
          } catch (NoSuchProviderException e) {
              e.printStackTrace();
          } catch (InvalidKeySpecException e) {
              e.printStackTrace();
          }      return key;
      }
      

  4.   

    关键就在:
    PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(keydata);
    key = kf.generatePrivate(encodedPrivateKey);
    这2句上面