Boa tarde pessoal,
Estou quase lá na minha classe q criptografa e descriptografa usando CMS enveloped data.
O seguinte código q obtive até agora irei compartilha-lo com vcs para me ajudarem a descobrir o q pode ser feito pra corrigir a Exception “too much data for RSA block”.
public class CMSteste {
private KeyStore keystore;
private static BASE64Encoder b64Encoder = new BASE64Encoder();
private static BASE64Decoder b64Decoder = new BASE64Decoder();
public static void main(String [] args) throws Exception {
String ksName = "C:\\Documents and Settings\\tfreitas\\keystore.ks";
String alias = "CN=Makrocert Public Primary CA,7B357AE5000000000139";
String password = "minhasenha";
String infile = "C:\\teste\\criptoTestes\\file.txt";
String outfile = "C:\\teste\\criptoTestes\\filecrip.txt";
String decfile = "C:\\teste\\criptoTestes\\filedecrip.txt";
CMSteste sealed = new CMSteste(ksName, password);
sealed.encrypt(alias, infile, outfile);
sealed.decrypt(alias, password, outfile, decfile);
}
public CMSteste() throws Exception {
//Pegando o Certificado
IUtilBuscaCertificados iuc = UtilBuscaCertificado.getInstancia();
//pega o certificado pelo email
X509Certificate certificadoNoToken = iuc.getCertificadoPeloEmail("meuemail@hotmail.com.br");
//pega o keystore passando o provider da Assembla
this.keystore = KeyStore.getInstance("msks", UtilCertificados.getProvider());
this.keystore.load(null, null);
}
public void encrypt(String alias, String infile, String outfile) throws Exception {
// get certificate out of keystore
Certificate c = this.keystore.getCertificate(alias);
X509Certificate x509 = (X509Certificate) c;
// read in list from file
BufferedReader reader = new BufferedReader(new FileReader(infile));
// file should be ...
ArrayList list = new ArrayList();
String line = null;
while ((line = reader.readLine()) != null) {
list.add(line);
}
String[] array = (String[]) list.toArray(new String[0]);
// turn String[] object into a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(array);
oos.flush();
oos.close();
byte[] arrayAsBytes = baos.toByteArray();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addKeyTransRecipient(x509);
CMSEnvelopedData cmsed = null ;
// encrypt byte[] in CMS
cmsed =
edGen.generate(
new CMSProcessableByteArray(arrayAsBytes),
CMSEnvelopedDataGenerator.AES256_CBC, "BC");
byte[] asn1Bytes = cmsed.getEncoded();
// turn ASN.1 byte[] into a base64 String
String b64Array = b64Encoder.encode(asn1Bytes);
PrintWriter writer = new PrintWriter(new FileOutputStream(outfile));
writer.write(b64Array);
writer.flush();
writer.close();
}
public void decrypt(String alias, String password, String infile, String outfile) throws Exception {
Key k = this.keystore.getKey(alias, password.toCharArray());
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) k;
BufferedReader reader = new BufferedReader(new FileReader(infile));
// read base64 CMS data from file
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
// get ASN.1 bytes from base64
byte [] asn1Bytes = b64Decoder.decodeBuffer(sb.toString());
CMSEnvelopedData cmsed = new CMSEnvelopedData(asn1Bytes);
RecipientInformationStore recipients = cmsed.getRecipientInfos();
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
byte[] recData = null;
while (it.hasNext()) {
RecipientInformation recipient = (RecipientInformation)it.next();
// get decrypted byte[]
//------AQUI Q DA ERROOOOO ERROOOOOOOO--------
recData = recipient.getContent(rsaPrivateKey, "BC");
}
// transform byte[] back into original object: String[]
ByteArrayInputStream bais = new ByteArrayInputStream(recData);
ObjectInputStream ois = new ObjectInputStream(bais);
String[] array = (String[]) ois.readObject();
PrintWriter writer = new PrintWriter(new FileOutputStream(outfile));
for (int i = 0, n = array.length; i < n; i++) {
writer.println(array[i]);
}
writer.flush();
writer.close();
}
}
Preciso urgente de ajuda com isso. Até agora já descobri q o erro ocorre por q tentamos descriptografar algo maior q minha chave RSA. E isso gera uma excessao segundo o q disse esse cara num forum. “BouncyCastle RSA gives an exception if you try to encrypt a block
which is longer than the key size. In your case the key size is 512
== 64 bytes. I think the only work around is to break your text into
64 byte blocks.”
Alguem me ajuda???
Desde já agradeço à atenção!