本文整理汇总了Java中java.security.interfaces.RSAKey类的典型用法代码示例。如果您正苦于以下问题:Java RSAKey类的具体用法?Java RSAKey怎么用?Java RSAKey使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RSAKey类属于java.security.interfaces包,在下文中一共展示了RSAKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: verify
import java.security.interfaces.RSAKey; //导入依赖的package包/类
public void verify() throws IOException, CertificateException {
PublicKey publicKey = loadPublicKey();
// Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
// cipher.init(Cipher.DECRYPT_MODE, publicKey);
// byte[] encryptedbytes = cipher.doFinal(Base64.getUrlDecoder().decode(signatureStr.getBytes()));
// String result = Base64.getUrlEncoder().encodeToString(encryptedbytes);
// System.out.println("---------------------------------");
// System.out.println(result);
// System.out.println(parts[0] + parts[1]);
//
// System.out.println("---------------------------------");
//TODO: possible decode without 3rd party library...
JWTVerifier verifier = JWT.require(Algorithm.RSA256((RSAKey) publicKey)).withIssuer(issuer).build();
DecodedJWT jwt = verifier.verify(token);
// System.out.println("DecodedJWT");
// System.out.println(jwt);
// System.out.println("---------------------------------");
}
示例2: getSuggestedSignatureAlgorithms
import java.security.interfaces.RSAKey; //导入依赖的package包/类
/**
* Gets the APK Signature Scheme v2 signature algorithms to be used for signing an APK using the
* provided key.
*
* @param minSdkVersion minimum API Level of the platform on which the APK may be installed (see
* AndroidManifest.xml minSdkVersion attribute).
*
* @throws InvalidKeyException if the provided key is not suitable for signing APKs using
* APK Signature Scheme v2
*/
public static List<SignatureAlgorithm> getSuggestedSignatureAlgorithms(
PublicKey signingKey, int minSdkVersion) throws InvalidKeyException {
String keyAlgorithm = signingKey.getAlgorithm();
if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
// Use RSASSA-PKCS1-v1_5 signature scheme instead of RSASSA-PSS to guarantee
// deterministic signatures which make life easier for OTA updates (fewer files
// changed when deterministic signature schemes are used).
// Pick a digest which is no weaker than the key.
int modulusLengthBits = ((RSAKey) signingKey).getModulus().bitLength();
if (modulusLengthBits <= 3072) {
// 3072-bit RSA is roughly 128-bit strong, meaning SHA-256 is a good fit.
return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA256);
} else {
// Keys longer than 3072 bit need to be paired with a stronger digest to avoid the
// digest being the weak link. SHA-512 is the next strongest supported digest.
return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA512);
}
} else if ("DSA".equalsIgnoreCase(keyAlgorithm)) {
// DSA is supported only with SHA-256.
return Collections.singletonList(SignatureAlgorithm.DSA_WITH_SHA256);
} else if ("EC".equalsIgnoreCase(keyAlgorithm)) {
// Pick a digest which is no weaker than the key.
int keySizeBits = ((ECKey) signingKey).getParams().getOrder().bitLength();
if (keySizeBits <= 256) {
// 256-bit Elliptic Curve is roughly 128-bit strong, meaning SHA-256 is a good fit.
return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA256);
} else {
// Keys longer than 256 bit need to be paired with a stronger digest to avoid the
// digest being the weak link. SHA-512 is the next strongest supported digest.
return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA512);
}
} else {
throw new InvalidKeyException("Unsupported key algorithm: " + keyAlgorithm);
}
}
示例3: specTest
import java.security.interfaces.RSAKey; //导入依赖的package包/类
/**
*
* @param kpair test key pair
* @param pubExponent expected public exponent.
* @return true if test passed. false if test failed.
*/
private static boolean specTest(KeyPair kpair, BigInteger pubExponent) {
boolean passed = true;
RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();
// test the getModulus method
if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
if (!priv.getModulus().equals(pub.getModulus())) {
System.err.println("priv.getModulus() = " + priv.getModulus());
System.err.println("pub.getModulus() = " + pub.getModulus());
passed = false;
}
if (!pubExponent.equals(pub.getPublicExponent())) {
System.err.println("pubExponent = " + pubExponent);
System.err.println("pub.getPublicExponent() = "
+ pub.getPublicExponent());
passed = false;
}
}
return passed;
}
示例4: shouldDoRSA256Signing
import java.security.interfaces.RSAKey; //导入依赖的package包/类
@Test
public void shouldDoRSA256Signing() throws Exception {
Algorithm algorithmSign = Algorithm.RSA256((RSAKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));
Algorithm algorithmVerify = Algorithm.RSA256((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"));
String jwtContent = String.format("%s.%s", RS256Header, auth0IssPayload);
byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
byte[] signatureBytes = algorithmSign.sign(contentBytes);
String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
String token = String.format("%s.%s", jwtContent, jwtSignature);
String expectedSignature = "ZB-Tr0vLtnf8I9fhSdSjU6HZei5xLYZQ6nZqM5O6Va0W9PgAqgRT7ShI9CjeYulRXPHvVmSl5EQuYuXdBzM0-H_3p_Nsl6tSMy4EyX2kkhEm6T0HhvarTh8CG0PCjn5p6FP5ZxWwhLcmRN70ItP6Z5MMO4CcJh1JrNxR4Fi4xQgt-CK2aVDMFXd-Br5yQiLVx1CX83w28OD9wssW3Rdltl5e66vCef0Ql6Q5I5e5F0nqGYT989a9fkNgLIx2F8k_az5x07BY59FV2SZg59nSiY7TZNjP8ot11Ew7HKRfPXOdh9eKRUVdhcxzqDePhyzKabU8TG5FP0SiWH5qVPfAgw";
assertThat(signatureBytes, is(notNullValue()));
assertThat(jwtSignature, is(expectedSignature));
JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithmVerify.verify(decoded, EncodeType.Base64);
}
示例5: shouldDoRSA384Signing
import java.security.interfaces.RSAKey; //导入依赖的package包/类
@Test
public void shouldDoRSA384Signing() throws Exception {
Algorithm algorithmSign = Algorithm.RSA384((RSAKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));
Algorithm algorithmVerify = Algorithm.RSA384((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"));
String jwtContent = String.format("%s.%s", RS384Header, auth0IssPayload);
byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
byte[] signatureBytes = algorithmSign.sign(contentBytes);
String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
String token = String.format("%s.%s", jwtContent, jwtSignature);
String expectedSignature = "Jx1PaTBnjd_U56MNjifFcY7w9ImDbseg0y8Ijr2pSiA1_wzQb_wy9undaWfzR5YqdIAXvjS8AGuZUAzIoTG4KMgOgdVyYDz3l2jzj6wI-lgqfR5hTy1w1ruMUQ4_wobpdxAiJ4fEbg8Mi_GljOiCO-P1HilxKnpiOJZidR8MQGwTInsf71tOUkK4x5UsdmUueuZbaU-CL5kPnRfXmJj9CcdxZbD9oMlbo23dwkP5BNMrS2LwGGzc9C_-ypxrBIOVilG3WZxcSmuG86LjcZbnL6LBEfph5NmKBgQav147uipb_7umBEr1m2dYiB_9u606n3bcoo3rnsYYK_Xfi1GAEQ";
assertThat(signatureBytes, is(notNullValue()));
assertThat(jwtSignature, is(expectedSignature));
JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithmVerify.verify(decoded, EncodeType.Base64);
}
示例6: shouldDoRSA512Signing
import java.security.interfaces.RSAKey; //导入依赖的package包/类
@Test
public void shouldDoRSA512Signing() throws Exception {
Algorithm algorithmSign = Algorithm.RSA512((RSAKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));
Algorithm algorithmVerify = Algorithm.RSA512((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"));
String jwtContent = String.format("%s.%s", RS512Header, auth0IssPayload);
byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
byte[] signatureBytes = algorithmSign.sign(contentBytes);
String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
String token = String.format("%s.%s", jwtContent, jwtSignature);
String expectedSignature = "THIPVYzNZ1Yo_dm0k1UELqV0txs3SzyMopCyHcLXOOdgYXF4MlGvBqu0CFvgSga72Sp5LpuC1Oesj40v_QDsp2GTGDeWnvvcv_eo-b0LPSpmT2h1Ibrmu-z70u2rKf28pkN-AJiMFqi8sit2kMIp1bwIVOovPvMTQKGFmova4Xwb3G526y_PeLlflW1h69hQTIVcI67ACEkAC-byjDnnYIklA-B4GWcggEoFwQRTdRjAUpifA6HOlvnBbZZlUd6KXwEydxVS-eh1odwPjB2_sfbyy5HnLsvNdaniiZQwX7QbwLNT4F72LctYdHHM1QCrID6bgfgYp9Ij9CRX__XDEA";
assertThat(signatureBytes, is(notNullValue()));
assertThat(jwtSignature, is(expectedSignature));
JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithmVerify.verify(decoded, EncodeType.Base64);
}
示例7: sign
import java.security.interfaces.RSAKey; //导入依赖的package包/类
private static byte[] sign() throws Exception {
RSAEngine rsa = new RSAEngine();
Digest dig = new SHA1Digest();
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivate(privateKeyFilename);
BigInteger big = ((RSAKey) privateKey).getModulus();
ISO9796d2Signer eng = new ISO9796d2Signer(rsa, dig, true);
RSAKeyParameters rsaPriv = new RSAKeyParameters(true, big, privateKey.getPrivateExponent());
eng.init(true, rsaPriv);
eng.update(message[0]);
eng.update(message, 1, message.length - 1);
byte[] signature = eng.generateSignature();
return signature;
}
示例8: specTest
import java.security.interfaces.RSAKey; //导入依赖的package包/类
/**
*
* @param kpair test key pair
* @param pubExponent expected public exponent.
* @return true if test passed. false if test failed.
*/
private static boolean specTest(KeyPair kpair, BigInteger pubExponent) {
boolean passed = true;
RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();
// test the getModulus method
if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
if (!priv.getModulus().equals(pub.getModulus())) {
System.out.println("priv.getModulus() = " + priv.getModulus());
System.out.println("pub.getModulus() = " + pub.getModulus());
passed = false;
}
if (!pubExponent.equals(pub.getPublicExponent())) {
System.out.println("pubExponent = " + pubExponent);
System.out.println("pub.getPublicExponent() = "
+ pub.getPublicExponent());
passed = false;
}
}
return passed;
}
示例9: verifyToken
import java.security.interfaces.RSAKey; //导入依赖的package包/类
private DecodedJWT verifyToken(String idToken) throws JwkException {
if (verifier != null) {
return verifier.verify(idToken);
}
if (algorithm != null) {
verifier = JWT.require(algorithm)
.withAudience(audience)
.withIssuer(issuer)
.build();
return verifier.verify(idToken);
}
String kid = JWT.decode(idToken).getKeyId();
PublicKey publicKey = jwkProvider.get(kid).getPublicKey();
return JWT.require(Algorithm.RSA256((RSAKey) publicKey))
.withAudience(audience)
.withIssuer(issuer)
.build()
.verify(idToken);
}
示例10: wrapJCAPrivateKeyForTLSStackOnly
import java.security.interfaces.RSAKey; //导入依赖的package包/类
/**
* Wraps the provided private key for use in the TLS/SSL stack only. Sign/decrypt operations
* using the key will be delegated to the {@code Signature}/{@code Cipher} implementation of the
* provider which accepts the key.
*/
static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey,
PublicKey publicKey) throws InvalidKeyException {
BigInteger modulus = null;
if (privateKey instanceof RSAKey) {
modulus = ((RSAKey) privateKey).getModulus();
} else if (publicKey instanceof RSAKey) {
modulus = ((RSAKey) publicKey).getModulus();
}
if (modulus == null) {
throw new InvalidKeyException("RSA modulus not available. Private: " + privateKey
+ ", public: " + publicKey);
}
return new OpenSSLKey(
NativeCrypto.getRSAPrivateKeyWrapper(privateKey, modulus.toByteArray()), true);
}
示例11: getKeyLength
import java.security.interfaces.RSAKey; //导入依赖的package包/类
/**
* Get the key size of a public key.
*
* @param pubKey The public key
* @return The key size, {@link #UNKNOWN_KEY_SIZE} if not known
*/
public static int getKeyLength(PublicKey pubKey)
{
if (pubKey instanceof RSAKey)
{
return ((RSAKey) pubKey).getModulus().bitLength();
}
else if (pubKey instanceof DSAKey)
{
return ((DSAKey) pubKey).getParams().getP().bitLength();
}
else if (pubKey instanceof DHKey)
{
return ((DHKey) pubKey).getParams().getP().bitLength();
}
else if (pubKey instanceof ECKey)
{
// TODO: how to get key size from these?
return UNKNOWN_KEY_SIZE;
}
LOG.warning("Don't know how to get key size from key " + pubKey);
return UNKNOWN_KEY_SIZE;
}
示例12: shouldFailToAuthenticateUsingInvalidJWK
import java.security.interfaces.RSAKey; //导入依赖的package包/类
@Test
public void shouldFailToAuthenticateUsingInvalidJWK() throws Exception {
Jwk jwk = mock(Jwk.class);
JwkProvider jwkProvider = mock(JwkProvider.class);
KeyPair keyPair1 = RSAKeyPair();
KeyPair keyPair2 = RSAKeyPair();
when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
when(jwk.getPublicKey()).thenReturn(keyPair1.getPublic());
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "issuer", "audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("audience")
.withIssuer("issuer")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256((RSAKey) keyPair2.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(BadCredentialsException.class);
exception.expectMessage("Not a valid token");
exception.expectCause(Matchers.<Throwable>instanceOf(SignatureVerificationException.class));
provider.authenticate(authentication);
}
示例13: shouldFailToAuthenticateUsingJWKIfMissingAudienceClaim
import java.security.interfaces.RSAKey; //导入依赖的package包/类
@Test
public void shouldFailToAuthenticateUsingJWKIfMissingAudienceClaim() 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()).thenReturn(keyPair.getPublic());
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "issuer", "audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withIssuer("issuer")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256((RSAKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(BadCredentialsException.class);
exception.expectMessage("Not a valid token");
exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class));
provider.authenticate(authentication);
}
示例14: shouldFailToAuthenticateUsingJWKIfMissingIssuerClaim
import java.security.interfaces.RSAKey; //导入依赖的package包/类
@Test
public void shouldFailToAuthenticateUsingJWKIfMissingIssuerClaim() 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()).thenReturn(keyPair.getPublic());
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "issuer", "audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("audience")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256((RSAKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(BadCredentialsException.class);
exception.expectMessage("Not a valid token");
exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class));
provider.authenticate(authentication);
}
示例15: shouldFailToAuthenticateUsingJWKIfMissingKeyIdClaim
import java.security.interfaces.RSAKey; //导入依赖的package包/类
@Test
public void shouldFailToAuthenticateUsingJWKIfMissingKeyIdClaim() 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()).thenReturn(keyPair.getPublic());
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "issuer", "audience");
String token = JWT.create()
.withAudience("some")
.withIssuer("issuer")
.sign(Algorithm.RSA256((RSAKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(BadCredentialsException.class);
exception.expectMessage("No kid found in jwt");
provider.authenticate(authentication);
}