下面列出了怎么用java.security.interfaces.RSAPrivateKey的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testSignedJwt() throws Exception {
final String subject = "user-1";
final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
final KeyPair pair = keyGen.generateKeyPair();
final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null);
final KnoxConfiguration configuration = getConfiguration(publicKey);
final KnoxService service = new KnoxService(configuration);
Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()));
}
public Jwt getExampleJWTToken() {
final ZonedDateTime soon = ZonedDateTime.now().plusDays(365);
final String jwtToken = "{\n" +
" \"aud\": [\n" +
" \"https://api.otto.de/api-authorization\"\n" +
" ],\n" +
" \"exp\": " + soon.toInstant().getEpochSecond() + ",\n" +
" \"user_name\": \"3d44bbc24614e28edd094bc54ef0497809717af5\",\n" +
" \"jti\": \"3cee521d-96a7-4d82-b726-7e02355f3a55\",\n" +
" \"client_id\": \"fe0661e5a99e4d43bd3496cc6c58025f\",\n" +
" \"scope\": [\n" +
" \"hello.read\"\n" +
" ]\n" +
"}";
final RsaSigner rsaSigner = new RsaSigner((RSAPrivateKey) keyPair.getPrivate());
return JwtHelper.encode(jwtToken, rsaSigner);
}
@Test
public void shouldNotOverwriteKeyIdIfAddedFromRSAAlgorithms() throws Exception {
RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA");
RSAKeyProvider provider = mock(RSAKeyProvider.class);
when(provider.getPrivateKeyId()).thenReturn("my-key-id");
when(provider.getPrivateKey()).thenReturn(privateKey);
String signed = JWTCreator.init()
.withKeyId("real-key-id")
.sign(Algorithm.RSA256(provider));
assertThat(signed, is(notNullValue()));
String[] parts = signed.split("\\.");
String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8);
assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id"));
}
public static PaillierKeyPair convertToPaillier(final KeyPair rsaKeyPair)
throws InvalidKeySpecException, NoSuchAlgorithmException {
// Get keys
final RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) rsaKeyPair.getPrivate();
final RSAPublicKey rsaPublicKey = (RSAPublicKey) rsaKeyPair.getPublic();
// Get fields
final BigInteger n = rsaPublicKey.getModulus(); // treat as 'n'
final BigInteger g = rsaPublicKey.getPublicExponent(); // treat as 'g'
final BigInteger lambda = rsaPrivateKey.getPrivateExponent(); // treat as 'lambda'
// Convert them back to Paillier keys
final PaillierPrivateKey privKey = new PaillierPrivateKey(lambda, n);
final PaillierPublicKey pubKey = new PaillierPublicKey(n, g);
// Convert to key pair
return new PaillierKeyPair(pubKey, privKey);
}
/**
* RSA私钥解密
*
* @param decryptStr Base64 编码的加密字符串
* @return 明文
*/
@Override
public String decrypt(String decryptStr){
String outStr = null;
try {
//64位解码加密后的字符串
byte[] inputByte = Base64.getDecoder().decode(decryptStr.getBytes(CHARSET_NAME));
//私钥
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(RSA).generatePrivate(new PKCS8EncodedKeySpec(privateCodeByte));
//RSA解密
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, priKey);
outStr = new String(cipher.doFinal(inputByte));
} catch (Exception e) {
log.error("RSA解密失败",e);
}
return outStr;
}
/**
* 随机生成密钥对
* @throws NoSuchAlgorithmException
*/
public static void genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
String publicKeyString = new String(Hex.encode(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Hex.encode((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
//0表示公钥
System.out.println("公钥 16进制:"+publicKeyString);
//1表示私钥
System.out.println("私钥 16进制:"+privateKeyString);
}
public static RSAPrivateKey getRSAPrivateKey(String encodedModulus,
String encodedPublicExponent,
String encodedPrivateExponent,
String encodedPrimeP,
String encodedPrimeQ,
String encodedPrimeExpP,
String encodedPrimeExpQ,
String encodedCrtCoefficient) {
//CHECKSTYLE:ON
try {
return getRSAPrivateKey(CryptoUtils.decodeSequence(encodedModulus),
CryptoUtils.decodeSequence(encodedPublicExponent),
CryptoUtils.decodeSequence(encodedPrivateExponent),
CryptoUtils.decodeSequence(encodedPrimeP),
CryptoUtils.decodeSequence(encodedPrimeQ),
CryptoUtils.decodeSequence(encodedPrimeExpP),
CryptoUtils.decodeSequence(encodedPrimeExpQ),
CryptoUtils.decodeSequence(encodedCrtCoefficient));
} catch (Exception ex) {
throw new SecurityException(ex);
}
}
@Test(expected = InvalidAuthenticationException.class)
public void testInvalidAudience() throws Exception {
final String subject = "user-1";
final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
final KeyPair pair = keyGen.generateKeyPair();
final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, "incorrect-audience", expiration);
final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null);
final KnoxConfiguration configuration = getConfiguration(publicKey);
final KnoxService service = new KnoxService(configuration);
Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()));
}
@Test
public void testToPrivateRsaKeyWithoutE() throws Exception {
RSAPrivateKey privateKey1 =
(RSAPrivateKey)KeyManagementUtils.loadPrivateKey("org/apache/cxf/rs/security/jose/jws/alice.jks",
"password",
"alice",
"password",
null);
JsonWebKey jwk1 = JwkUtils.fromRSAPrivateKey(privateKey1, KeyAlgorithm.RSA_OAEP_256.getJwaName());
assertNotNull(jwk1.getProperty(JsonWebKey.RSA_PUBLIC_EXP));
jwk1.asMap().remove(JsonWebKey.RSA_PUBLIC_EXP);
try {
JwkUtils.toRSAPrivateKey(jwk1);
fail("JWK without the public exponent can not be converted to RSAPrivateKey");
} catch (JoseException ex) {
// expected
}
}
@SuppressWarnings("unchecked")
@Test
public void shouldFailToAuthenticateUsingJWKIfKeyIdDoesNotMatch() throws Exception {
JwkProvider jwkProvider = mock(JwkProvider.class);
KeyPair keyPair = RSAKeyPair();
when(jwkProvider.get(eq("key-id"))).thenThrow(SigningKeyNotFoundException.class);
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("test-audience")
.withIssuer("test-issuer")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(AuthenticationServiceException.class);
exception.expectMessage("Could not retrieve jwks from issuer");
exception.expectCause(Matchers.<Throwable>instanceOf(SigningKeyNotFoundException.class));
provider.authenticate(authentication);
}
private static String encrypt(byte[] keyBytes, String plainText)
throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = factory.generatePrivate(spec);
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
} catch (InvalidKeyException e) {
//For IBM JDK
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, fakePublicKey);
}
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
return Base64.byteArrayToBase64(encryptedBytes);
}
/**
* 初始化密钥
*
* @return Map 密钥对儿 Map
* @throws Exception
*/
public static Map<String, Object> initKey() throws Exception {
// 实例化密钥对儿生成器
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
// 初始化密钥对儿生成器
keyPairGen.initialize(KEY_SIZE);
// 生成密钥对儿
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 封装密钥
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
@SuppressWarnings("unchecked")
@Test
public void shouldFailToAuthenticateUsingJWKIfPublicKeyIsInvalid() throws Exception {
Jwk jwk = mock(Jwk.class);
JwkProvider jwkProvider = mock(JwkProvider.class);
KeyPair keyPair = RSAKeyPair();
when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
when(jwk.getPublicKey()).thenThrow(InvalidPublicKeyException.class);
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("test-audience")
.withIssuer("test-issuer")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(AuthenticationServiceException.class);
exception.expectMessage("Could not retrieve public key from issuer");
exception.expectCause(Matchers.<Throwable>instanceOf(InvalidPublicKeyException.class));
provider.authenticate(authentication);
}
public boolean testDecryptWithGluuDecrypter(String jwe) {
try {
JWK jwk = JWK.parse(recipientJwkJson);
RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();
JweDecrypterImpl decrypter = new JweDecrypterImpl(rsaPrivateKey);
decrypter.setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.RSA_OAEP);
decrypter.setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.A128GCM);
final String decryptedPayload = decrypter.decrypt(jwe).getClaims().toJsonString().toString();
System.out.println("Gluu decrypt succeed: " + decryptedPayload);
if (isJsonEqual(decryptedPayload, PAYLOAD)) {
return true;
}
} catch (Exception e) {
System.out.println("Gluu decrypt failed: " + e.getMessage());
e.printStackTrace();
}
return false;
}
private static Key[] manipulateKey(int type, Key key)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
KeyFactory kf = KeyFactory.getInstance(KEYALG, PROVIDER);
switch (type) {
case PUBLIC_KEY:
return new Key[]{
kf.generatePublic(kf.getKeySpec(key, RSAPublicKeySpec.class)),
kf.generatePublic(new X509EncodedKeySpec(key.getEncoded())),
kf.generatePublic(new RSAPublicKeySpec(
((RSAPublicKey) key).getModulus(),
((RSAPublicKey) key).getPublicExponent()))
};
case PRIVATE_KEY:
return new Key[]{
kf.generatePrivate(kf.getKeySpec(key,
RSAPrivateKeySpec.class)),
kf.generatePrivate(new PKCS8EncodedKeySpec(
key.getEncoded())),
kf.generatePrivate(new RSAPrivateKeySpec(((RSAPrivateKey) key).getModulus(),
((RSAPrivateKey) key).getPrivateExponent()))
};
}
throw new RuntimeException("We shouldn't reach here");
}
private static String[] commonKey(int size) throws NoSuchAlgorithmException {
String [] keys = new String[2];
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
keyPairGenerator.initialize(size);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
keys[0] = Base64.byteArrayToBase64(rsaPrivateKey.getEncoded());
// 公钥
keys[1] = Base64.byteArrayToBase64(rsaPublicKey.getEncoded());
return keys;
}
@Test
public void testEncryptDecryptRSA15WrapA128CBCHS256() throws Exception {
final String specPlainText = "Live long and prosper.";
RSAPublicKey publicKey = CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED_A1,
RSA_PUBLIC_EXPONENT_ENCODED_A1);
KeyEncryptionProvider keyEncryption = new RSAKeyEncryptionAlgorithm(publicKey,
KeyAlgorithm.RSA1_5);
JweEncryptionProvider encryption = new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256,
CONTENT_ENCRYPTION_KEY_A3,
INIT_VECTOR_A3,
keyEncryption);
String jweContent = encryption.encrypt(specPlainText.getBytes(StandardCharsets.UTF_8), null);
RSAPrivateKey privateKey = CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED_A1,
RSA_PRIVATE_EXPONENT_ENCODED_A1);
KeyDecryptionProvider keyDecryption = new RSAKeyDecryptionAlgorithm(privateKey,
KeyAlgorithm.RSA1_5);
JweDecryptionProvider decryption = new AesCbcHmacJweDecryption(keyDecryption);
String decryptedText = decryption.decrypt(jweContent).getContentText();
assertEquals(specPlainText, decryptedText);
}
public static String createToken(KeyPair keyPair, String issuer, Date issuedAt, Date expiresAt, String level)
throws NoSuchAlgorithmException,
NoSuchProviderException,
DynamicLogLevelException {
Algorithm rsa256 = Algorithm.RSA256((RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate());
if (ALLOWED_DYNAMIC_LOGLEVELS.contains(level)) {
return JWT.create().withIssuer(issuer).//
withIssuedAt(issuedAt). //
withExpiresAt(expiresAt).//
withClaim("level", level).sign(rsa256);
} else {
throw new DynamicLogLevelException("Dynamic Log-Level [" + level +
"] provided in header is not valid. Allowed Values are " +
ALLOWED_DYNAMIC_LOGLEVELS.toString());
}
}
public static void main(String[] args) throws Exception {
int keySize = RAS_KEY_SIZE;
if (args.length > 0) keySize = Integer.parseInt(args[0]);
if (keySize < RAS_KEY_SIZE) keySize = RAS_KEY_SIZE;
Pair<RSAPublicKey, RSAPrivateKey> pair = RSAUtils.genKeyPair(keySize);
//生成公钥和私钥
RSAPublicKey publicKey = pair.key;
RSAPrivateKey privateKey = pair.value;
System.out.println("key generate success!");
System.out.println("privateKey=" + RSAUtils.encodeBase64(privateKey));
System.out.println("publicKey=" + RSAUtils.encodeBase64(publicKey));
//明文
byte[] ming = "这是一段测试文字。。。。".getBytes(Constants.UTF_8);
System.out.println("明文:" + new String(ming, Constants.UTF_8));
//加密后的密文
byte[] mi = RSAUtils.encryptByPublicKey(ming, publicKey);
System.out.println("密文:" + new String(mi, Constants.UTF_8));
//解密后的明文
ming = RSAUtils.decryptByPrivateKey(mi, privateKey);
System.out.println("解密:" + new String(ming, Constants.UTF_8));
}
public static String createTokenRSA( PrivateKey privateKey, String claimJson )
{
try
{
JWSSigner signer = new RSASSASigner( ( RSAPrivateKey ) privateKey );
Payload pl = new Payload( claimJson );
JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );
jwsObject.sign( signer );
return jwsObject.serialize();
}
catch ( Exception e )
{
LOG.error( "Error creating RSA token", e.getMessage() );
return "";
}
}
/**
* 得到私钥
*
* @param privateKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
// 通过PKCS#8编码的Key指令获得私钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
return key;
}
@Before
public void init() {
try {
dailyPrivateKey = (RSAPrivateKey) RSAUtils.decodePrivateKey(daily_privateKey);
dailyPublicKey = (RSAPublicKey) RSAUtils.decodePublicKey(daily_publicKey);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 私钥加密
*
* @param data
* @param privateKey
* @return
*/
public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* Builds RSAKey with generated key pair
*
* @param jwtTokenDTO JWT Token info object
* @param keyPairGenerator keyPairGenerator
* @return RSAKey built RSA Key which can be used to sign
*/
private RSAKey generateRSAKey(JWTTokenInfoDTO jwtTokenDTO, KeyPairGenerator keyPairGenerator) {
KeyPair keyPair = keyPairGenerator.generateKeyPair();
jwtTokenDTO.setGeneratedKeyPair(keyPair);
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAKey.Builder builder = new RSAKey.Builder(publicKey)
.privateKey(privateKey);
RSAKey rsaKey = builder.keyID(jwtTokenDTO.getToken()).build();
jwtTokenDTO.setRsaKey(rsaKey);
return rsaKey;
}
protected void engineInitSign(
PrivateKey privateKey,
SecureRandom random)
throws InvalidKeyException
{
if (!(privateKey instanceof RSAPrivateKey))
{
throw new InvalidKeyException("Supplied key is not a RSAPrivateKey instance");
}
pss = new org.ripple.bouncycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength, trailer);
pss.init(true, new ParametersWithRandom(RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey), random));
}
@Test
public void testGetPrivateKeyAsKeyPair() {
KeyPair b1024_dsa = KeyTestUtil.getPrivateKeyAsKeyPair("b1024", "id_dsa", null);
assertNotNull("b1024_dsa should not be null", b1024_dsa);
assertTrue("b1024_dsa should have a DSAPublicKey", b1024_dsa.getPublic() instanceof DSAPublicKey);
assertTrue("b1024_dsa should have a DSAPrivateKey", b1024_dsa.getPrivate() instanceof DSAPrivateKey);
KeyPair b1024_rsa = KeyTestUtil.getPrivateKeyAsKeyPair("b1024", "id_rsa", null);
assertNotNull("b1024_rsa should not be null", b1024_rsa);
assertTrue("b1024_rsa should have a RSAPublicKey", b1024_rsa.getPublic() instanceof RSAPublicKey);
assertTrue("b1024_rsa should have a RSAPrivateKey", b1024_rsa.getPrivate() instanceof RSAPrivateKey);
KeyPair b2048_rsa = KeyTestUtil.getPrivateKeyAsKeyPair("b2048", "id_rsa", null);
assertNotNull("b2048_rsa should not be null", b2048_rsa);
assertTrue("b2048_rsa should have a RSAPublicKey", b2048_rsa.getPublic() instanceof RSAPublicKey);
assertTrue("b2048_rsa should have a RSAPrivateKey", b2048_rsa.getPrivate() instanceof RSAPrivateKey);
KeyPair b4096_rsa = KeyTestUtil.getPrivateKeyAsKeyPair("b4096", "id_rsa", null);
assertNotNull("b4096_rsa should not be null", b4096_rsa);
assertTrue("b4096_rsa should have a RSAPublicKey", b4096_rsa.getPublic() instanceof RSAPublicKey);
assertTrue("b4096_rsa should have a RSAPrivateKey", b4096_rsa.getPrivate() instanceof RSAPrivateKey);
KeyPair withpass_dsa = KeyTestUtil.getPrivateKeyAsKeyPair("withpass", "id_dsa", "dummydummy");
assertNotNull("withpass_dsa should not be null", withpass_dsa);
assertTrue("withpass_dsa should have a DSAPublicKey", withpass_dsa.getPublic() instanceof DSAPublicKey);
assertTrue("withpass_dsa should have a DSAPrivateKey", withpass_dsa.getPrivate() instanceof DSAPrivateKey);
KeyPair withpass_rsa = KeyTestUtil.getPrivateKeyAsKeyPair("withpass", "id_rsa", "dummydummy");
assertNotNull("withpass_rsa should not be null", withpass_rsa);
assertTrue("withpass_rsa should have a RSAPublicKey", withpass_rsa.getPublic() instanceof RSAPublicKey);
assertTrue("withpass_rsa should have a RSAPrivateKey", withpass_rsa.getPrivate() instanceof RSAPrivateKey);
}
private KeyPair generateKeyPair() {
try {
KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate();
RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic();
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(), privateSeed.getPrivateExponent());
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(), publicSeed.getPublicExponent());
return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static RsaPrivateKeyDef from(RSAPrivateKey key) {
if (key instanceof RSAMultiPrimePrivateCrtKey) {
return from((RSAMultiPrimePrivateCrtKey) key);
} else if (key instanceof RSAPrivateCrtKey) {
return from((RSAPrivateCrtKey) key);
} else {
return new RsaPrivateKeyDef(key.getModulus(), key.getPrivateExponent(), key);
}
}
/**
* 生成密钥对(公钥和私钥)
*
* @return 生成密钥对(公钥和私钥)数据集合 PUBLIC_KEY,PRIVATE_KEY
*/
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(EncryptConstants.ENCRYPT_TYPE_RSA);
keyPairGen.initialize(INITIALIZE_LENGTH);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = Maps.newHashMap();
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 私钥解密
*
* @param data data
* @param privateKey privateKey
* @return xxx
*/
public static byte[] decryptByPrivateKey(byte[] data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_PADDING);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//模长
int key_len = privateKey.getModulus().bitLength() / 8;
//如果密文长度大于模长则要分组解密
return doFinal(cipher, data, key_len);
} catch (Exception e) {
ClientConfig.I.getLogger().e(e, "decryptByPrivateKey ex");
}
return Constants.EMPTY_BYTES;
}