Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Can't get RSAPublicKey and RSAPrivateKey

843811Mar 29 2010 — edited Mar 29 2010
This is my code:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;

public class lab2_1 {

public static void main(String[] args) {

try{
KeyFactory kf = KeyFactory.getInstance("RSA");

RSAPublicKeySpec pubks = new RSAPublicKeySpec(new BigInteger("12345678", 16), new BigInteger("11", 16));
RSAPrivateKeySpec priks = new RSAPrivateKeySpec(new BigInteger("12345678", 16), new BigInteger("12345678", 16));

try{
RSAPublicKey pubKey = (RSAPublicKey)kf.generatePublic(pubks);
RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priks);

try{
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt");

try{
Cipher cipher = Cipher.getInstance("RSA");
try{
cipher.init(Cipher.ENCRYPT_MODE, pubKey);

CipherOutputStream cos = new CipherOutputStream(fos, cipher);
byte[] readedData = new byte[8];
try{
int i = fis.read(readedData);
while(i != 1){
cos.write(readedData, 0, i);
i = fis.read(readedData);
}

cos.close();
}
catch(IOException e){
System.out.println("IO exception. can not read data");
}
}
catch(InvalidKeyException e){
System.out.println("invalid key exception");
}
}
catch(NoSuchPaddingException e){
System.out.println("no such padding exception");
}
}
catch(FileNotFoundException e){
System.out.println("File not found exception");
}
}
catch(InvalidKeySpecException e){
System.out.println("Invalid key spec exception for private and public key");
}
}
catch(NoSuchAlgorithmException e)
{
System.out.println("No such algorithm exception");
}
}

}

When I ran this code, the "invalid key spec exception for private and public key" appeared. I don't know how to fix it. Can anyone help me? Thanks

Edited by: son_echipbk on Mar 28, 2010 9:18 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 26 2010
Added on Mar 29 2010
1 comment
360 views