use of java.security.spec.RSAPrivateKeySpec in project santuario-java by apache.
the class TestUtils method getPrivateKey.
public static PrivateKey getPrivateKey(String algo, int keysize) throws InvalidKeySpecException, NoSuchAlgorithmException {
KeyFactory kf = KeyFactory.getInstance(algo);
KeySpec kspec;
if (algo.equalsIgnoreCase("DSA")) {
if (keysize == 1024) {
kspec = new DSAPrivateKeySpec(new BigInteger(DSA_X), new BigInteger(DSA_P), new BigInteger(DSA_Q), new BigInteger(DSA_G));
} else if (keysize == 2048) {
kspec = new DSAPrivateKeySpec(new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P), new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));
} else {
throw new RuntimeException("Unsupported keysize:" + keysize);
}
} else if (algo.equalsIgnoreCase("RSA")) {
if (keysize == 512) {
kspec = new RSAPrivateKeySpec(new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV));
} else {
throw new RuntimeException("Unsupported keysize:" + keysize);
}
} else {
throw new RuntimeException("Unsupported key algorithm " + algo);
}
return kf.generatePrivate(kspec);
}
use of java.security.spec.RSAPrivateKeySpec in project i2p.i2p by i2p.
the class SigUtil method toJavaRSAKey.
/**
* As of 0.9.31, if pk is a RSASigningPrivateCrtKey,
* this will return a RSAPrivateCrtKey.
*/
public static RSAPrivateKey toJavaRSAKey(SigningPrivateKey pk) throws GeneralSecurityException {
if (pk instanceof RSASigningPrivateCrtKey)
return ((RSASigningPrivateCrtKey) pk).toJavaKey();
KeyFactory kf = KeyFactory.getInstance("RSA");
// private key is modulus (pubkey) + exponent
BigInteger[] nd = split(pk.getData());
// modulus exponent
KeySpec ks = new RSAPrivateKeySpec(nd[0], nd[1]);
return (RSAPrivateKey) kf.generatePrivate(ks);
}
use of java.security.spec.RSAPrivateKeySpec in project druid by alibaba.
the class ConfigTools method decrypt.
public static String decrypt(PublicKey publicKey, String cipherText) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
try {
cipher.init(Cipher.DECRYPT_MODE, publicKey);
} catch (InvalidKeyException e) {
// 因为 IBM JDK 不支持私钥加密, 公钥解密, 所以要反转公私钥
// 也就是说对于解密, 可以通过公钥的参数伪造一个私钥对象欺骗 IBM JDK
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
// It is a stateful object. so we need to get new one.
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
}
if (cipherText == null || cipherText.length() == 0) {
return cipherText;
}
byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
byte[] plainBytes = cipher.doFinal(cipherBytes);
return new String(plainBytes);
}
Aggregations