无法使用java中的RSA-OAEP进行加密和解密

时间:2018-02-02 12:30:13

标签: java encryption cryptography rsa public-key-encryption

我能够生成密钥对和加密&用以下语句解密4个字符串的字符

 byte[] input = "userid".getBytes();

但是当我像下面一样增加字符串长度时,我会遇到异常

byte[] input = "userid:789".getBytes();

代码:

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;

public class RSAOAEP {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    byte[] input = "userid:789".getBytes();
    Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
    SecureRandom random = new SecureRandom();
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");

    generator.initialize(386, random);

    KeyPair pair = generator.generateKeyPair();
    Key pubKey = pair.getPublic();

    Key privKey = pair.getPrivate();

    System.out.println("privateKey: "+privKey);
    System.out.println("publicKey: "+pubKey);

    cipher.init(Cipher.ENCRYPT_MODE, pubKey, random);
    byte[] cipherText = cipher.doFinal(input);
    System.out.println("cipher: " + new String(cipherText));

    cipher.init(Cipher.DECRYPT_MODE, privKey);
    byte[] plainText = cipher.doFinal(cipherText);
    System.out.println("plain : " + new String(plainText));
  }
}

例外:

  

线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:   RSA阻止的数据过多   org.bouncycastle.jcajce.provider.asymmetric.rsa.CipherSpi.engineDoFinal(未知   来源)在javax.crypto.Cipher.doFinal(Cipher.java:2165)at   RSAOAEP.main(RSAOAEP.java:29)

0 个答案:

没有答案