下面列出了怎么用java.security.spec.RSAKeyGenParameterSpec的API类实例代码及写法,或者点击链接到github查看源代码。
public static WalletKeyPair generateWalletRSAKey(int key_len)
{
try
{
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(key_len, RSAKeyGenParameterSpec.F4);
KeyPairGenerator key_gen = KeyPairGenerator.getInstance("RSA", Globals.getCryptoProviderName());
key_gen.initialize(spec);
KeyPair key_pair = key_gen.genKeyPair();
WalletKeyPair wkp = WalletKeyPair.newBuilder()
.setPublicKey(ByteString.copyFrom(key_pair.getPublic().getEncoded()))
.setPrivateKey(ByteString.copyFrom(key_pair.getPrivate().getEncoded()))
.setSignatureType(SignatureUtil.SIG_TYPE_RSA)
.build();
return wkp;
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Initialize Key Generator (Blowfish keygen and RSA keygen)
*
* @throws GeneralSecurityException
*/
public static void init() throws GeneralSecurityException {
log.info("Initializing Key Generator...");
blowfishKeyGen = KeyGenerator.getInstance("Blowfish");
KeyPairGenerator rsaKeyPairGenerator = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
rsaKeyPairGenerator.initialize(spec);
encryptedRSAKeyPairs = new EncryptedRSAKeyPair[10];
for (int i = 0; i < 10; i++) {
encryptedRSAKeyPairs[i] = new EncryptedRSAKeyPair(
rsaKeyPairGenerator.generateKeyPair());
}
// Pre-init RSA cipher.. saving about 300ms
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
rsaCipher.init(Cipher.DECRYPT_MODE, encryptedRSAKeyPairs[0].getRSAKeyPair().getPrivate());
}
public void initialize(
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (!(params instanceof RSAKeyGenParameterSpec))
{
throw new InvalidAlgorithmParameterException("parameter object not a RSAKeyGenParameterSpec");
}
RSAKeyGenParameterSpec rsaParams = (RSAKeyGenParameterSpec)params;
param = new RSAKeyGenerationParameters(
rsaParams.getPublicExponent(),
random, rsaParams.getKeysize(), defaultTests);
engine.init(param);
}
public static void main(String[] args) throws Exception {
int size = 0;
if (args.length >= 1) {
size = Integer.parseInt(args[0]);
} else {
throw new RuntimeException("Missing keysize to test with");
}
BigInteger publicExponent
= (args.length >= 2) ? new BigInteger(args[1]) : RSAKeyGenParameterSpec.F4;
System.out.println("Running test with key size: " + size
+ " and public exponent: " + publicExponent);
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
kpg1.initialize(new RSAKeyGenParameterSpec(size, publicExponent));
if (!specTest(kpg1.generateKeyPair(), publicExponent)) {
throw new RuntimeException("Test failed.");
}
}
private LoginController() throws GeneralSecurityException
{
_log.info("Loading LoginContoller...");
_hackProtection = new HashMap<>();
_keyPairs = new ScrambledKeyPair[10];
KeyPairGenerator keygen = null;
keygen = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
keygen.initialize(spec);
//generate the initial set of keys
for (int i = 0; i < 10; i++)
{
_keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
}
_log.info("Cached 10 KeyPairs for RSA communication");
testCipher((RSAPrivateKey) _keyPairs[0]._pair.getPrivate());
// Store keys for blowfish communication
generateBlowFishKeys();
}
public void initialize(
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (!(params instanceof RSAKeyGenParameterSpec))
{
throw new InvalidAlgorithmParameterException("parameter object not a RSAKeyGenParameterSpec");
}
RSAKeyGenParameterSpec rsaParams = (RSAKeyGenParameterSpec)params;
param = new RSAKeyGenerationParameters(
rsaParams.getPublicExponent(),
random, rsaParams.getKeysize(), defaultTests);
engine.init(param);
}
public static void main(String[] args) throws Exception {
int size = 0;
if (args.length >= 1) {
size = Integer.parseInt(args[0]);
} else {
throw new RuntimeException("Missing keysize to test with");
}
BigInteger publicExponent
= (args.length >= 2) ? new BigInteger(args[1]) : RSAKeyGenParameterSpec.F4;
System.out.println("Running test with key size: " + size
+ " and public exponent: " + publicExponent);
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
kpg1.initialize(new RSAKeyGenParameterSpec(size, publicExponent));
if (!specTest(kpg1.generateKeyPair(), publicExponent)) {
throw new RuntimeException("Test failed.");
}
}
/**
* Returns an AlgorithmParameterSpec for generating a RSASSA-PSS key,
* which include the PSSParameters.
* Requires jdk11.
*
* @param keySizeInBits the size of the modulus in bits.
* @param sha the name of the hash function for hashing the input (e.g. "SHA-256")
* @param mgf the name of the mask generating function (typically "MGF1")
* @param mgfSha the name of the hash function for the mask generating function
* (typically the same as sha).
* @param saltLength the length of the salt in bytes (typically the digest size of sha,
* i.e. 32 for "SHA-256")
* @throws NoSuchMethodException if the AlgorithmParameterSpec is not
* supported (i.e. this happens before jdk11).
*/
public RSAKeyGenParameterSpec getPssAlgorithmParameters(
int keySizeInBits,
String sha,
String mgf,
String mgfSha,
int saltLength) throws Exception {
BigInteger publicExponent = new BigInteger("65537");
PSSParameterSpec params =
new PSSParameterSpec(sha, mgf, new MGF1ParameterSpec(mgfSha), saltLength, 1);
// Uses reflection to call
// public RSAKeyGenParameterSpec(int keysize, BigInteger publicExponent,
// AlgorithmParameterSpec keyParams)
// because this method is only supported in jdk11. This throws a NoSuchMethodException
// for older jdks.
Constructor<RSAKeyGenParameterSpec> c =
RSAKeyGenParameterSpec.class.getConstructor(
int.class, BigInteger.class, AlgorithmParameterSpec.class);
return c.newInstance(keySizeInBits, publicExponent, params);
}
public static void main(String[] args) throws Exception {
int size = 0;
if (args.length >= 1) {
size = Integer.parseInt(args[0]);
} else {
throw new RuntimeException("Missing keysize to test with");
}
BigInteger publicExponent
= (args.length >= 2) ? new BigInteger(args[1]) : RSAKeyGenParameterSpec.F4;
System.out.println("Running test with key size: " + size
+ " and public exponent: " + publicExponent);
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
kpg1.initialize(new RSAKeyGenParameterSpec(size, publicExponent));
if (!specTest(kpg1.generateKeyPair(), publicExponent)) {
throw new RuntimeException("Test failed.");
}
}
public static AsymmetricCipherKeyPair generateRsaKeyPair(int keyStrength) throws Exception {
Security.addProvider(new BouncyCastleProvider());
try {
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
generator.init(new RSAKeyGenerationParameters(RSAKeyGenParameterSpec.F4, SecureRandom.getInstance("SHA1PRNG"), keyStrength, 80));
AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
return keyPair;
} catch (Exception e) {
throw new Exception("Cannot create RSA keypair", e);
}
}
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
if (params instanceof RSAKeyGenParameterSpec == false) {
throw new InvalidAlgorithmParameterException
("Params must be instance of RSAKeyGenParameterSpec");
}
RSAKeyGenParameterSpec rsaSpec = (RSAKeyGenParameterSpec)params;
int tmpKeySize = rsaSpec.getKeysize();
BigInteger tmpPublicExponent = rsaSpec.getPublicExponent();
if (tmpPublicExponent == null) {
tmpPublicExponent = RSAKeyGenParameterSpec.F4;
} else {
if (tmpPublicExponent.compareTo(RSAKeyGenParameterSpec.F0) < 0) {
throw new InvalidAlgorithmParameterException
("Public exponent must be 3 or larger");
}
if (tmpPublicExponent.bitLength() > tmpKeySize) {
throw new InvalidAlgorithmParameterException
("Public exponent must be smaller than key size");
}
}
// do not allow unreasonably large key sizes, probably user error
try {
RSAKeyFactory.checkKeyLengths(tmpKeySize, tmpPublicExponent,
512, 64 * 1024);
} catch (InvalidKeyException e) {
throw new InvalidAlgorithmParameterException(
"Invalid key sizes", e);
}
this.keySize = tmpKeySize;
this.publicExponent = tmpPublicExponent;
this.random = random;
}
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
int tmpSize;
if (params == null) {
tmpSize = DEF_RSA_KEY_SIZE;
} else if (params instanceof RSAKeyGenParameterSpec) {
if (((RSAKeyGenParameterSpec) params).getPublicExponent() != null) {
throw new InvalidAlgorithmParameterException
("Exponent parameter is not supported");
}
tmpSize = ((RSAKeyGenParameterSpec) params).getKeysize();
} else {
throw new InvalidAlgorithmParameterException
("Params must be an instance of RSAKeyGenParameterSpec");
}
try {
RSAKeyFactory.checkKeyLengths(tmpSize, null,
KEY_SIZE_MIN, KEY_SIZE_MAX);
} catch (InvalidKeyException e) {
throw new InvalidAlgorithmParameterException(
"Invalid Key sizes", e);
}
this.keySize = tmpSize;
}
public static void main(String[] args) throws Exception {
RSAKeyGenParameterSpec rsaSpec =
new RSAKeyGenParameterSpec (1024, RSAKeyGenParameterSpec.F4);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
kpg.initialize(rsaSpec);
// test generateKeyPair
KeyPair kpair = kpg.generateKeyPair();
if (kpair == null) {
throw new Exception("no keypair generated");
}
}
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
if (!(params instanceof RSAKeyGenParameterSpec)) {
throw new InvalidAlgorithmParameterException("Only RSAKeyGenParameterSpec supported");
}
this.keySize = ((RSAKeyGenParameterSpec) params).getKeysize();
}
private KeyPair generateRSAKeyPair() throws Exception {
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
KeyPairGenerator generator;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
generator = KeyPairGenerator.getInstance("RSA");
} else {
generator = KeyPairGenerator.getInstance("RSA", "BC");
}
generator.initialize(spec, secureRandom);
return generator.generateKeyPair();
}
public void initialize(int keySize, SecureRandom random) {
// do not allow unreasonably small or large key sizes,
// probably user error
try {
RSAKeyFactory.checkKeyLengths(keySize, RSAKeyGenParameterSpec.F4,
512, 64 * 1024);
} catch (InvalidKeyException e) {
throw new InvalidParameterException(e.getMessage());
}
this.keySize = keySize;
this.random = random;
this.publicExponent = RSAKeyGenParameterSpec.F4;
}
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
if (params instanceof RSAKeyGenParameterSpec == false) {
throw new InvalidAlgorithmParameterException
("Params must be instance of RSAKeyGenParameterSpec");
}
RSAKeyGenParameterSpec rsaSpec = (RSAKeyGenParameterSpec)params;
int tmpKeySize = rsaSpec.getKeysize();
BigInteger tmpPublicExponent = rsaSpec.getPublicExponent();
if (tmpPublicExponent == null) {
tmpPublicExponent = RSAKeyGenParameterSpec.F4;
} else {
if (tmpPublicExponent.compareTo(RSAKeyGenParameterSpec.F0) < 0) {
throw new InvalidAlgorithmParameterException
("Public exponent must be 3 or larger");
}
if (tmpPublicExponent.bitLength() > tmpKeySize) {
throw new InvalidAlgorithmParameterException
("Public exponent must be smaller than key size");
}
}
// do not allow unreasonably large key sizes, probably user error
try {
RSAKeyFactory.checkKeyLengths(tmpKeySize, tmpPublicExponent,
512, 64 * 1024);
} catch (InvalidKeyException e) {
throw new InvalidAlgorithmParameterException(
"Invalid key sizes", e);
}
this.keySize = tmpKeySize;
this.publicExponent = tmpPublicExponent;
this.random = random;
}
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
int tmpSize;
if (params == null) {
tmpSize = DEF_RSA_KEY_SIZE;
} else if (params instanceof RSAKeyGenParameterSpec) {
if (((RSAKeyGenParameterSpec) params).getPublicExponent() != null) {
throw new InvalidAlgorithmParameterException
("Exponent parameter is not supported");
}
tmpSize = ((RSAKeyGenParameterSpec) params).getKeysize();
} else {
throw new InvalidAlgorithmParameterException
("Params must be an instance of RSAKeyGenParameterSpec");
}
try {
RSAKeyFactory.checkKeyLengths(tmpSize, null,
KEY_SIZE_MIN, KEY_SIZE_MAX);
} catch (InvalidKeyException e) {
throw new InvalidAlgorithmParameterException(
"Invalid Key sizes", e);
}
this.keySize = tmpSize;
}
public static void main(String[] args) throws Exception {
RSAKeyGenParameterSpec rsaSpec =
new RSAKeyGenParameterSpec (1024, RSAKeyGenParameterSpec.F4);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
kpg.initialize(rsaSpec);
// test generateKeyPair
KeyPair kpair = kpg.generateKeyPair();
if (kpair == null) {
throw new Exception("no keypair generated");
}
}
private void initializeScrambledKeys() throws GeneralSecurityException {
var keygen = KeyPairGenerator.getInstance("RSA");
var spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
keygen.initialize(spec);
_keyPairs = new ScrambledKeyPair[10];
for (int i = 0; i < 10; i++) {
_keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
}
LOGGER.info("Cached 10 KeyPairs for RSA communication");
testCipher((RSAPrivateKey) _keyPairs[0].getPair().getPrivate());
}
private void loadRSAKeys() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4);
keyGen.initialize(spec);
_keyPairs = new KeyPair[KEYS_SIZE];
for (int i = 0; i < KEYS_SIZE; i++) {
_keyPairs[i] = keyGen.genKeyPair();
}
LOGGER.info("Cached {} RSA keys for Game Server communication.", _keyPairs.length);
}
@ReactMethod
public void createKeys(Promise promise) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
deleteBiometricKey();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(biometricKeyAlias, KeyProperties.PURPOSE_SIGN)
.setDigests(KeyProperties.DIGEST_SHA256)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4))
.setUserAuthenticationRequired(true)
.build();
keyPairGenerator.initialize(keyGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
byte[] encodedPublicKey = publicKey.getEncoded();
String publicKeyString = Base64.encodeToString(encodedPublicKey, Base64.DEFAULT);
publicKeyString = publicKeyString.replaceAll("\r", "").replaceAll("\n", "");
WritableMap resultMap = new WritableNativeMap();
resultMap.putString("publicKey", publicKeyString);
promise.resolve(resultMap);
} else {
promise.reject("Cannot generate keys on android versions below 6.0", "Cannot generate keys on android versions below 6.0");
}
} catch (Exception e) {
promise.reject("Error generating public private keys: " + e.getMessage(), "Error generating public private keys");
}
}
public void initialize(int keySize, SecureRandom random) {
// do not allow unreasonably small or large key sizes,
// probably user error
try {
RSAKeyFactory.checkKeyLengths(keySize, RSAKeyGenParameterSpec.F4,
512, 64 * 1024);
} catch (InvalidKeyException e) {
throw new InvalidParameterException(e.getMessage());
}
this.keySize = keySize;
this.random = random;
this.publicExponent = RSAKeyGenParameterSpec.F4;
}
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
int tmpSize;
if (params == null) {
tmpSize = KEY_SIZE_DEFAULT;
} else if (params instanceof RSAKeyGenParameterSpec) {
if (((RSAKeyGenParameterSpec) params).getPublicExponent() != null) {
throw new InvalidAlgorithmParameterException
("Exponent parameter is not supported");
}
tmpSize = ((RSAKeyGenParameterSpec) params).getKeysize();
} else {
throw new InvalidAlgorithmParameterException
("Params must be an instance of RSAKeyGenParameterSpec");
}
try {
RSAKeyFactory.checkKeyLengths(tmpSize, null,
KEY_SIZE_MIN, KEY_SIZE_MAX);
} catch (InvalidKeyException e) {
throw new InvalidAlgorithmParameterException(
"Invalid Key sizes", e);
}
this.keySize = tmpSize;
}
public static void main(String[] args) throws Exception {
RSAKeyGenParameterSpec rsaSpec =
new RSAKeyGenParameterSpec (1024, RSAKeyGenParameterSpec.F4);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
kpg.initialize(rsaSpec);
// test generateKeyPair
KeyPair kpair = kpg.generateKeyPair();
if (kpair == null) {
throw new Exception("no keypair generated");
}
}
public static KeyPair createKeyPair() {
KeyPairGenerator keyPairGenerator;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4), new SecureRandom());
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
throw new UnexpectedCheckedException(e);
}
return keyPairGenerator.generateKeyPair();
}
public void initialize(int keySize, SecureRandom random) {
try {
initialize(new RSAKeyGenParameterSpec(keySize,
RSAKeyGenParameterSpec.F4), null);
} catch (InvalidAlgorithmParameterException iape) {
throw new InvalidParameterException(iape.getMessage());
}
}
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
int tmpSize;
if (params == null) {
tmpSize = DEF_RSA_KEY_SIZE;
} else if (params instanceof RSAKeyGenParameterSpec) {
if (((RSAKeyGenParameterSpec) params).getPublicExponent() != null) {
throw new InvalidAlgorithmParameterException
("Exponent parameter is not supported");
}
tmpSize = ((RSAKeyGenParameterSpec) params).getKeysize();
} else {
throw new InvalidAlgorithmParameterException
("Params must be an instance of RSAKeyGenParameterSpec");
}
try {
RSAKeyFactory.checkKeyLengths(tmpSize, null,
KEY_SIZE_MIN, KEY_SIZE_MAX);
} catch (InvalidKeyException e) {
throw new InvalidAlgorithmParameterException(
"Invalid Key sizes", e);
}
this.keySize = tmpSize;
}
public static void main(String[] args) throws Exception {
RSAKeyGenParameterSpec rsaSpec =
new RSAKeyGenParameterSpec (1024, RSAKeyGenParameterSpec.F4);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
kpg.initialize(rsaSpec);
// test generateKeyPair
KeyPair kpair = kpg.generateKeyPair();
if (kpair == null) {
throw new Exception("no keypair generated");
}
}
private void loadRSAKeys() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(512,RSAKeyGenParameterSpec.F4);
keyGen.initialize(spec);
_keyPairs = new KeyPair[KEYS_SIZE];
for (int i = 0; i < KEYS_SIZE; i++)
{
_keyPairs[i] = keyGen.genKeyPair();
}
}