当前位置: 首页 > 知识库问答 >
问题:

使用Java实现RSA加密/解密

袁翰池
2023-03-14

我正在做一个简单的程序来加密/解密使用RSA算法在Java。我创建一个密码对象如下:

//Create a Cipher object
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");

我通过调用加密函数进行加密:

String cipher=encrypt(textByte, pair, rsaCipher);
System.out.println("The Encryption using RSA Algorithm : "+cipher);

解密过程如下:

//Decryption
String plain=decrypt(Base64.decodeBase64(cipher),pair, rsaCipher);
System.out.println("The Decryption using RSA Algorithm : "+plain);

但是,当我将创建密码对象的代码编辑为://Create a Cipher object Cipher rsapier=Cipher时。getInstance(“RSA”);

问题出在哪里。在第一种情况下(当空格出现时),我指定了NoPadd?为什么空格出现在解密的消息中?即使我使用填充,我希望这不应该发生。

编辑:这是加密和解密方法:

public static String encrypt(byte[] textBytes, KeyPair pair, Cipher rsaCipher) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
    //get the public key
    PublicKey pk=pair.getPublic(); 


    //Initialize the cipher for encryption. Use the public key.
    rsaCipher.init(Cipher.ENCRYPT_MODE, pk);

    //Perform the encryption using doFinal
    byte[] encByte = rsaCipher.doFinal(textBytes);

    // converts to base64 for easier display.
    byte[] base64Cipher = Base64.encodeBase64(encByte);

    return new String(base64Cipher);
}//end encrypt

public static String decrypt(byte[] cipherBytes, KeyPair pair, Cipher rsaCipher) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException
{
    //get the public key
    PrivateKey pvk=pair.getPrivate(); 

    //Create a Cipher object
    //Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");

    //Initialize the cipher for encryption. Use the public key.
    rsaCipher.init(Cipher.DECRYPT_MODE, pvk);

    //Perform the encryption using doFinal
    byte[] decByte = rsaCipher.doFinal(cipherBytes);

    return new String(decByte);

}//end decrypt

共有2个答案

史昀
2023-03-14
//This is a complete encryption and decryption module using 
//Algorithm: JWEAlgorithm.RSA_OAEP_256
//Encryption Method: A128CBC_HS256

public static String  encrypt(String text) throws Exception {
    // Set the plain text
    Payload payload = new Payload(text);
    // Create the header
    JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A128CBC_HS256);
    // Create the JWE object and encrypt it
    JWEObject jweObject = new JWEObject(header, payload);
    jweObject.encrypt(new RSAEncrypter(getPublicKey()));
    // Serialise to compact JOSE form...
    String jweString = jweObject.serialize();
    LOG.info("Generated Encrypted Key : {}", jweString);
    return jweString;
}

public static String decrypt(String text) throws Exception {
    // Parse into JWE object...
    JWEObject jweObject = JWEObject.parse(text);
    jweObject.decrypt(new RSADecrypter(getPrivateKey()));
    // Get the plain text
    Payload payload = jweObject.getPayload();
    System.out.println(payload.toString());
    return payload.toString();
}

private static RSAPublicKey getPublicKey() throws Exception {
    String filename = "/home/vaibhav/Setups/cert/pub.der";
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();

    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPublicKey) kf.generatePublic(spec);
}

private static RSAPrivateKey getPrivateKey() throws Exception {
    String filename = "/home/vaibhav/Setups/cert/private.pkcs8";
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();

    PKCS8EncodedKeySpec spec1 = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPrivateKey) kf.generatePrivate(spec1);
}
章茂
2023-03-14

你的问题确实是填充物。安全的RSA功能需要某种填充,PKCS#1.5或OAEP填充。再者,要求查找加密的纯文本的开始和结束。

RSA的模块化指数是使用大整数执行的。然后,这些操作的结果表示为八位组字符串。这些八位字符串基本上是整数的大端、无符号、固定长度表示。这些整数保留00值字节(在RSA标准中称为I2OS原语)。所以您看到的是模块化指数的结果,00填充仍然存在。

长话短说,始终使用填充方案。如今,OAEP更可取。与混合加密方案一起使用,或使用更高级别的容器格式,如CMS或PGP。

 类似资料:
  • 本文向大家介绍java使用RSA加密方式实现数据加密解密的代码,包括了java使用RSA加密方式实现数据加密解密的代码的使用技巧和注意事项,需要的朋友参考一下 RSA的应用 RSA是一种非对称加密算法。现在,很多登陆表单的密码的都采用RSA加密,例如京东中的登陆使用公钥对密码进行加密 java使用RSA加密方式实现数据加密解密,需要首先产生私钥和公钥 测试代码 RSA工具类的实现 总结 以上所述是

  • 本文向大家介绍python实现RSA加密(解密)算法,包括了python实现RSA加密(解密)算法的使用技巧和注意事项,需要的朋友参考一下 RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。 今天只有短的RSA钥匙才可能被强力方式解破。到2008年为止,世界上还没有任何可靠的攻击RSA算法的方式。只要其密钥的长度足够长,用RSA加密

  • 问题内容: 我正在尝试使用RSA算法在.NET中加密字符串,并在Java中解密结果。目前,我已经可以做相反的事情(用Java加密,用.NET解密)。这里有我的代码可以实际工作(JAVA加密): 和(.NET解密) 现在我想做相反的事情……但是我遇到了一些错误,例如(密钥的大小应该是128个字节……等等)我应该怎么做? 在这里,我添加当前的 无效 代码: 。净 爪哇 问题答案: Java解密代码的最

  • 问题内容: 我正在使用RSA在JAVA上进行加密,并尝试使用.NET进行解密。我包括我的JAVA代码和.NET代码,希望有人对此有所了解。 JAVA代码: 从此JAVA代码中,我得到了加密字符串的结果,该结果恰好是: FOP4 AAIH6hcabXnrvNG5YUk + / + nBv9n9HU0CAgZjkIWQIDjbOpSwoPVBFERrZ6641x2QaoJw5yv18XAay 0WrC

  • 如何在Python usomg OpenSSL中执行RSA加密和解密? 我有以下几点:

  • 如有任何帮助,我们将不胜感激。