Hi all.
Working on a chat program that will encrypt everything. But to do so I must understand encryption, so I started a simple project where I simply learn how to use encryption, and I am trying to figure out RSA at the moment (first best). All I get is errors. This is my code:
package test;
/**
* Imports
*/
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import javax.crypto.*;
import java.math.BigInteger;
/**
* The main class
*
* @author anders
*/
public class Main
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
/**
* Handle exceptions
*/
try
{
/**
* Create the key generator
*/
KeyFactory keyFac = KeyFactory.getInstance("RSA");
System.out.println("tyuiop");
/**
* Create key specs
*/
RSAPrivateKeySpec specPrivate = new RSAPrivateKeySpec(
new BigInteger("6768977777777734985789347897493477838973493098765432345678987654345678987654567847934797987593797349587349474939989896897345", 32),
new BigInteger("6768977777777734985789347897493477838973493098765432345678987654345678987654567847934797987593797349587349474939989896897345", 32)
);
RSAPublicKeySpec specPublic = new RSAPublicKeySpec(
new BigInteger("6768977777777734985789347897493477838973493098765432345678987654345678987654567847934797987593797349587349474939989896897345", 32),
new BigInteger("6768977777777734985789347897493477838973493098765432345678987654345678987654567847934797987593797349587349474939989896897345", 32)
);
/**
* Generate keys
*/
RSAPrivateKey privateKey = (RSAPrivateKey) keyFac.generatePrivate( specPrivate );
RSAPublicKey publicKey = (RSAPublicKey) keyFac.generatePublic( specPublic );
/**
* Create Cipher object, and set it to encrypt
*/
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
/**
* Declare text to encrypt
*/
String txt = "text";
/**
* Encrypt data
*/
byte[] bytes = txt.getBytes();
String encTxt = new String( cipher.doFinal( bytes ) );
/**
* Output encrypted data
*/
System.out.println( encTxt );
/**
* Set the cipher to decrypt data
*/
cipher.init(Cipher.DECRYPT_MODE, publicKey);
/**
* Decrypt data
*/
bytes = encTxt.getBytes();
String decTxt = new String( cipher.doFinal( bytes ) );
/**
* Output decrypted data, and then the data that once was encrypted
*/
System.out.println( decTxt );
System.out.println( txt );
}
catch (Exception e)
{
/**
* Output exception data
*/
System.err.println("ERROR: " + e.toString());
}
}
}
That code throws a BadPaddingException exception (can be found under javax.crypto), which state that the "Data must start with zero".
The exception is thrown when I try to decrypt the data, I can encrypt it without any problems. Anyone have any idea of what is wrong?
Take care,
Mr Z.
There is no greater virtue, then the ability to face oneself.