不使用NoPadding的RSA示例

时间:2010-04-05 19:06:57

标签: java security encryption rsa

在哪里可以找到使用“NoPadding”的RSA加密示例?

- 更新

更好:如何使这个SSCCE正确运行而不抛出“太多的RSA阻止数据”异常?

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;

/**
 * Basic RSA example.
 */
public class TestRSA {

    public static void main(String[] args) throws Exception {

 byte[] input = new byte[100];

 Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
 KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");

 // create the keys

 RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger("d46f473a2d746537de2056ae3092c451",
  16), new BigInteger("11", 16));
 RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger(
  "d46f473a2d746537de2056ae3092c451", 16), new BigInteger("57791d5430d593164082036ad8b29fb1",
  16));

 RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
 RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec);

 // encryption step

 cipher.init(Cipher.ENCRYPT_MODE, pubKey);

 byte[] cipherText = cipher.doFinal(input);

 // decryption step

 cipher.init(Cipher.DECRYPT_MODE, privKey);

 byte[] plainText = cipher.doFinal(cipherText);

    }
}

- 更新:关于循环

使用:

 byte[] cipherText = new byte[input.length];
 for (int i = 0; i < input.length; i++) {
     byte[] singleByteArray = new byte[] { input[i] };
     cipherText[i] = cipher.doFinal(singleByteArray)[0];
 }

不能正常工作。由于未知原因,cipherText变为零 - 即使输入是0x03的数组。

2 个答案:

答案 0 :(得分:3)

SunJCE提供程序的Sun Providers Documentation告诉您Cipher.getInstance()参数中允许的填充规范。试试Cipher.getInstance("RSA/ECB/PKCS1PADDING");

编辑:
   这不是一个填充问题,更多的是你对RSA在密码学中的使用方式有误解。您可以1)使模数大于数据,2)使用Hybrid cryptosystem,或3)最不希望的是手动将输入分解为每个小于模数的块。如果要使用PKCS1填充(通常建议使用),则输入长度不得大于n-11个字节,其中n是存储RSA模数所需的字节数。

答案 1 :(得分:-1)

 Cipher cipher = Cipher.getInstance("RSA");
 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
 byte[] cipherData = cipher.doFinal(content);

更新:您确定需要bouncycastle吗?为什么不将RSA作为参数传递给Cipher.getInstance(..)

更新2:为什么不尝试这些RSA encryption examples中的任何一个?