Java examples for Security:RSA
Generate a RSA key pair with public key and private key.
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; public class Main{ /**/*w w w . ja va2 s . co m*/ * Key algorithm to be used in this class. */ public static final String KEY_ALGORITHM = "RSA"; /** * Default key length. The value shall be in the range of 512-65536. */ private static final int KEY_LENGTH = 1024; /** * Identifier of pubic key in the Map. */ public static final String PUBLIC_KEY = "PublicKey"; /** * Identifier of private key in the Map. */ public static final String PRIVATE_KEY = "PrivateKey"; /** * Generate a RSA key pair with public key and private key. * * @param keyMap to save the key pair, the public key is indicated by * "PublicKey" and private key is indicated by "PrivateKey". * @return */ public static boolean generateKeyPair(Map<String, Object> keyMap) { //Get one instance of KeyPairGenerator with RSA. KeyPairGenerator keyPairGenerator = null; try { keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex); return false; } //Get a random seed. SecureRandom secureRandom = new SecureRandom(); //Use current datetime as random seed. String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault()).format(new Date()); secureRandom.setSeed(currentDateTime.getBytes()); //Initialze the key generator with the random number provider. We need to call initialze everytime to get a NEW key pair. keyPairGenerator.initialize(KEY_LENGTH, secureRandom); //Ready to generate a key pair. KeyPair keyPair = keyPairGenerator.genKeyPair(); //Get public and private key. PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); keyMap.put(PUBLIC_KEY, publicKey.getEncoded()); keyMap.put(PRIVATE_KEY, privateKey.getEncoded()); return true; } }