importjavax.crypto.*;importjava.security.*;publicclassEncrypter{privatestaticSecureRandomrand=null;publicstaticbyte[]encrypt(Stringmessage,Keykey)throwsException{checkVer...
import javax.crypto.*;
import java.security.*;
public class Encrypter
{
private static SecureRandom rand = null;
public static byte[] encrypt(String message, Key key) throws Exception
{
checkVersion();
Cipher c = Cipher.getInstance("RSA");
if(rand == null)
{
rand = SecureRandom.getInstance("SHA1PRNG");
Long seed = new Long(System.currentTimeMillis());
rand.setSeed(seed.toString().getBytes());
}
c.init(Cipher.ENCRYPT_MODE, key, rand);
return c.doFinal(message.getBytes("US-ASCII"));
}
public static void checkVersion(){
String version = System.getProperty("java.version");
char minor = version.charAt(2);
if(minor != '5')
throw new RuntimeException("JDK 1.5 is required to run this RSA" +
"application. \nJRE version "+ version + " found");
}
public static String decrypt(byte[] ct, Key key) throws Exception
{
checkVersion();
Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.DECRYPT_MODE, key);
byte[] bytes = c.doFinal(ct);
return new String(bytes, "US-ASCII");
}
public static KeyPair generateKeys() throws Exception
{
checkVersion();
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
if(rand == null)
{
rand = SecureRandom.getInstance("SHA1PRNG");
Long seed = new Long(System.currentTimeMillis());
rand.setSeed(seed.toString().getBytes());
}
keygen.initialize(512, rand);
return keygen.genKeyPair();
}
}
展开