java.security.spec.RSAPublicKeySpec Java Examples

The following examples show how to use java.security.spec.RSAPublicKeySpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DOMKeyValue.java    From jdk8u_jdk with GNU General Public License v2.0 7 votes vote down vote up
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
 
Example #2
Source File: Encryption.java    From Wurst7 with GNU General Public License v3.0 7 votes vote down vote up
private KeyPair loadRsaKeys(Path publicFile, Path privateFile)
	throws GeneralSecurityException, ReflectiveOperationException,
	IOException
{
	KeyFactory factory = KeyFactory.getInstance("RSA");
	
	// load public key
	PublicKey publicKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(publicFile)))
	{
		publicKey = factory.generatePublic(new RSAPublicKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	// load private key
	PrivateKey privateKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(privateFile)))
	{
		privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	return new KeyPair(publicKey, privateKey);
}
 
Example #3
Source File: SimpleIngestManager.java    From snowflake-ingest-java with Apache License 2.0 7 votes vote down vote up
/**
 * generate key pair object from private key
 *
 * @param privateKey private key
 * @return a key pair object
 * @throws NoSuchAlgorithmException if can't create key factory by using
 *                                  RSA algorithm
 * @throws InvalidKeySpecException  if private key or public key is invalid
 */
private KeyPair createKeyPairFromPrivateKey(PrivateKey privateKey) throws
    NoSuchAlgorithmException, InvalidKeySpecException
{
  if(!(privateKey instanceof RSAPrivateCrtKey))
    throw new IllegalArgumentException("Input private key is not a RSA private key");

  KeyFactory kf = KeyFactory.getInstance("RSA");

  //generate public key from private key
  RSAPrivateCrtKey privk = (RSAPrivateCrtKey) privateKey;
  RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privk.getModulus(),
      privk.getPublicExponent());
  PublicKey publicK = kf.generatePublic(publicKeySpec);

  //create key pairs
  return new KeyPair(publicK, privateKey);
}
 
Example #4
Source File: MessageStatusCli.java    From protect with MIT License 6 votes vote down vote up
public static KeyPair convertFromPaillier(final PaillierKeyPair paillierKeyPair)
		throws InvalidKeySpecException, NoSuchAlgorithmException {
	// Get keys
	final PaillierPrivateKey paillierPrivateKey = paillierKeyPair.getPrivateKey();
	final PaillierPublicKey paillierPublicKey = paillierKeyPair.getPublicKey();

	// Get fields
	final BigInteger n = paillierPublicKey.getN(); // treat as 'N'
	final BigInteger e = paillierPublicKey.getG(); // treat as 'e'
	final BigInteger d = paillierPrivateKey.getLambda(); // treat as 'd'

	// Represent them as RSA keys
	final RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(n, d);
	final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(n, e);

	// Convert to key pair
	final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	final PublicKey rsaPublic = keyFactory.generatePublic(pubKeySpec);
	final PrivateKey rsaPrivate = keyFactory.generatePrivate(privKeySpec);

	return new KeyPair(rsaPublic, rsaPrivate);
}
 
Example #5
Source File: SimpleTokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Decode a JWK(S) encoded public key string to an RSA PublicKey
 * @param jwksValue - JWKS string value
 * @return RSAPublicKey from RSAPublicKeySpec
 */
public static RSAPublicKey decodeJWKSPublicKey(String jwksValue) throws Exception {
    JsonObject jwks = Json.createReader(new StringReader(jwksValue)).readObject();
    JsonArray keys = jwks.getJsonArray("keys");
    JsonObject jwk;
    if(keys != null) {
        jwk = keys.getJsonObject(0);
    }
    else {
        jwk = jwks;
    }
    String e = jwk.getString("e");
    String n = jwk.getString("n");

    byte[] ebytes = Base64.getUrlDecoder().decode(e);
    BigInteger publicExponent = new BigInteger(1, ebytes);
    byte[] nbytes = Base64.getUrlDecoder().decode(n);
    BigInteger modulus = new BigInteger(1, nbytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    return (RSAPublicKey)kf.generatePublic(rsaPublicKeySpec);
}
 
Example #6
Source File: JWKxPEMTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void generatePublicKeyFromJWKs() throws Exception {
    String jsonJwk = TokenUtils.readResource("/signer-keyset4k.jwk");
    System.out.printf("jwk: %s\n", jsonJwk);
    JsonObject jwks = Json.createReader(new StringReader(jsonJwk)).readObject();
    JsonArray keys = jwks.getJsonArray("keys");
    JsonObject jwk = keys.getJsonObject(0);
    String e = jwk.getString("e");
    String n = jwk.getString("n");

    byte[] ebytes = Base64.getUrlDecoder().decode(e);
    BigInteger publicExponent = new BigInteger(1, ebytes);
    byte[] nbytes = Base64.getUrlDecoder().decode(n);
    BigInteger modulus = new BigInteger(1, nbytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    PublicKey publicKey = kf.generatePublic(rsaPublicKeySpec);
    System.out.printf("publicKey=%s\n", publicKey);
    String pem = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
    System.out.printf("pem: %s\n", pem);
}
 
Example #7
Source File: JWTVerifier.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get the public key that is used to verify the JWT from the user service. We assume the key is
 * an RSA key.
 *
 * @throws NoSuchAlgorithmException
 */
private PublicKey getPublicKey()
    throws Base64Exception, InvalidKeySpecException, NoSuchAlgorithmException {
  String url =
      "https://" + libertyHostname + ":" + libertySslPort + "/jwt/ibm/api/jwtUserBuilder/jwk";
  Response response = processRequest(url, "GET", null, null);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());

  // Liberty returns the keys in an array.  We'll grab the first one (there
  // should only be one).
  JsonObject jwkResponse = toJsonObj(response.readEntity(String.class));
  JsonArray jwkArray = jwkResponse.getJsonArray("keys");
  JsonObject jwk = jwkArray.getJsonObject(0);
  BigInteger modulus = new BigInteger(1, Base64Utility.decode(jwk.getString("n"), true));
  BigInteger publicExponent = new BigInteger(1, Base64Utility.decode(jwk.getString("e"), true));
  return KeyFactory.getInstance("RSA")
      .generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
}
 
Example #8
Source File: CipherHelper.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
/**
 * from <type><space><base64data><space><comment> to public key
 */
private static PublicKey toPublicKey(String sshPublicKey)
    throws NoSuchAlgorithmException, InvalidKeySpecException {
    String[] line = sshPublicKey.trim().split(" ", 3);
    String type = line[0];
    String content = line[1];

    ByteBuffer buf = ByteBuffer.wrap(Base64.getDecoder().decode(content));

    // format of decoded content is: <type><keyparams>
    // where type and each param is a DER string
    String decodedType = new String(readDERString(buf));
    if (!decodedType.equals(type)) {
        throw new IllegalArgumentException("expected " + type + ", got " + decodedType);
    }

    if (type.equals("ssh-rsa")) {
        BigInteger e = new BigInteger(readDERString(buf));
        BigInteger y = new BigInteger(readDERString(buf));
        return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(y, e));
    }

    throw new InvalidKeySpecException("Unknown key type '" + type + "'");
}
 
Example #9
Source File: DOMKeyValue.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
 
Example #10
Source File: DOMKeyValue.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
 
Example #11
Source File: DOMKeyValue.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
 
Example #12
Source File: PEMDecoder.java    From fusionauth-jwt with Apache License 2.0 6 votes vote down vote up
private PEM decode_PKCS_1_Public(String encodedKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
  byte[] bytes = getKeyBytes(encodedKey, PKCS_1_PUBLIC_KEY_PREFIX, PKCS_1_PUBLIC_KEY_SUFFIX);
  DerValue[] sequence = new DerInputStream(bytes).getSequence();

  // DER Encoded PKCS#1 structure
  // ------------------------------------------------------
  // RSAPublicKey ::= SEQUENCE {
  //   modulus           INTEGER,  -- n
  //   publicExponent    INTEGER   -- e
  // }

  if (sequence.length != 2 || !sequence[0].tag.is(Tag.Integer) || !sequence[1].tag.is(Tag.Integer)) {
    // Expect the following format : [ Integer | Integer ]
    throw new InvalidKeyException("Could not build this PKCS#1 public key. Expecting values in the DER encoded sequence in the following format [ Integer | Integer ]");
  }

  BigInteger modulus = sequence[0].getBigInteger();
  BigInteger publicExponent = sequence[1].getBigInteger();
  return new PEM(KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent)));
}
 
Example #13
Source File: RsaKeyPairGen.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
public static void main( final String[] args ) throws Exception {
	final KeyPairGenerator kpGen = KeyPairGenerator.getInstance( "RSA" );
	kpGen.initialize( KEY_SIZE_BITS );
	final KeyPair kp = kpGen.generateKeyPair();
	
	final PublicKey  pubKey  = kp.getPublic();
	final PrivateKey privKey = kp.getPrivate();
    
	if ( DEBUG ) {
   		System.out.println( pubKey .getAlgorithm() + " " + pubKey .getFormat() + " " + pubKey .getEncoded().length );
   		System.out.println( privKey.getAlgorithm() + " " + privKey.getFormat() + " " + privKey.getEncoded().length );
	}
	
	final KeyFactory kf = KeyFactory.getInstance( "RSA" );
	final RSAPublicKeySpec  pubKeySpec  = kf.getKeySpec( pubKey , RSAPublicKeySpec .class );
	final RSAPrivateKeySpec privKeySpec = kf.getKeySpec( privKey, RSAPrivateKeySpec.class );
	
	if ( DEBUG ) {
		System.out.println( pubKeySpec .getModulus() + " " + pubKeySpec .getPublicExponent() );
		System.out.println( privKeySpec.getModulus() + " " + privKeySpec.getPrivateExponent() );
	}
	
	saveKey( pubKeySpec .getModulus(), pubKeySpec .getPublicExponent (), "w:/pubkey.rsa"  );
	saveKey( privKeySpec.getModulus(), privKeySpec.getPrivateExponent(), "w:/privkey.rsa" );
}
 
Example #14
Source File: KeyStoreKeyFactory.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
public KeyPair getKeyPair(String alias, char[] password) {
	try {
		synchronized (lock) {
			if (store == null) {
				synchronized (lock) {
					store = KeyStore.getInstance("jks");
					store.load(resource.getInputStream(), this.password);
				}
			}
		}
		RSAPrivateCrtKey key = (RSAPrivateCrtKey) store.getKey(alias, password);
		RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
		PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
		return new KeyPair(publicKey, key);
	}
	catch (Exception e) {
		throw new IllegalStateException("Cannot load keys from store: " + resource, e);
	}
}
 
Example #15
Source File: FakeBurpCertificateBuilder.java    From SAMLRaider with MIT License 6 votes vote down vote up
@Override
public void generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
	// https://github.com/bcgit/bc-java/blob/53d17ef99e30c6bd49e6eec9235e3eefca6a222d/pkix/src/test/java/org/bouncycastle/cert/test/CertTest.java
	RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
			"b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16));
	RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(new BigInteger(
			"b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger(
			"9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger(
			"c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger(
			"b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger(
			"b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));

	KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
	setPrivateKey(fact.generatePrivate(privKeySpec));
	setPublicKey(fact.generatePublic(pubKeySpec));
}
 
Example #16
Source File: DOMKeyValue.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
 
Example #17
Source File: DecryptUtil.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public 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"));
	String encryptedString = Base64.byteArrayToBase64(encryptedBytes);

	return encryptedString;
}
 
Example #18
Source File: RSA.java    From azeroth with Apache License 2.0 6 votes vote down vote up
/**
 * 从KeyStore获取公钥
 * @param location
 * @param alias
 * @param storeType
 * @param storePass
 * @param keyPass
 * @return
 */
public static PublicKey loadPublicKeyFromKeyStore(String location, String alias, String storeType, String storePass, String keyPass) {
    try {
        storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        keyPass = keyPass == null ? storePass : keyPass;
        KeyStore keyStore = KeyStore.getInstance(storeType);
        InputStream is = new FileInputStream(location);
        keyStore.load(is, storePass.toCharArray());

        RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
        RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
                key.getPublicExponent());
        PublicKey publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
        return publicKey;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: EmbeddedSftpServer.java    From java-examples with MIT License 6 votes vote down vote up
private PublicKey decodePublicKey() throws Exception {
    InputStream stream = new ClassPathResource("/keys/sftp_rsa.pub").getInputStream();
    byte[] decodeBuffer = Base64.decodeBase64(StreamUtils.copyToByteArray(stream));
    ByteBuffer bb = ByteBuffer.wrap(decodeBuffer);
    int len = bb.getInt();
    byte[] type = new byte[len];
    bb.get(type);
    if ("ssh-rsa".equals(new String(type))) {
        BigInteger e = decodeBigInt(bb);
        BigInteger m = decodeBigInt(bb);
        RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
        return KeyFactory.getInstance("RSA").generatePublic(spec);

    }
    else {
        throw new IllegalArgumentException("Only supports RSA");
    }
}
 
Example #20
Source File: EmbeddedSftpServer.java    From java-examples with MIT License 6 votes vote down vote up
private PublicKey decodePublicKey() throws Exception {
    InputStream stream = new ClassPathResource("/keys/sftp_rsa.pub").getInputStream();
    byte[] decodeBuffer = Base64.decodeBase64(StreamUtils.copyToByteArray(stream));
    ByteBuffer bb = ByteBuffer.wrap(decodeBuffer);
    int len = bb.getInt();
    byte[] type = new byte[len];
    bb.get(type);
    if ("ssh-rsa".equals(new String(type))) {
        BigInteger e = decodeBigInt(bb);
        BigInteger m = decodeBigInt(bb);
        RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
        return KeyFactory.getInstance("RSA").generatePublic(spec);

    }
    else {
        throw new IllegalArgumentException("Only supports RSA");
    }
}
 
Example #21
Source File: RsaSignatureTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
/**
 * Tests legacy signatures. In this context we use the term legacy signatures for signatures that
 * are not conforming to the PKCS #1 standard, but are sometimes generated by buggy signers. So
 * far this test considers both accepting and rejecting such signatures as valid behavior.
 *
 * <p>Currently we check for just one type of legacy signatures: i.e., a missing NULL parameter in
 * the ASN encoding of the hash. BouncyCastle and the SunJCE accept this signature, Conscrypt does
 * not.
 *
 * <p>Some references that support accepting this signature:
 * https://codereview.chromium.org/1690123002/
 * https://groups.google.com/a/chromium.org/forum/#!topic/chromium-reviews/Jo5S7HtEABI claims that
 * 7% of the responses in the Online Certificate Status Protocol (OCSP) miss the NULL parameter
 */
@Test
public void testLegacySignatures() throws Exception {
  RSAPublicKeySpec key = RSA_KEY1;
  String algorithm = ALGORITHM_KEY1;
  byte[] message = "Test".getBytes("UTF-8");
  Signature verifier = Signature.getInstance(algorithm);
  KeyFactory kf = KeyFactory.getInstance("RSA");
  PublicKey pub = kf.generatePublic(key);
  for (String signature : LEGACY_SIGNATURES_KEY1) {
    byte[] signatureBytes = TestUtil.hexToBytes(signature);
    verifier.initVerify(pub);
    verifier.update(message);
    boolean verified = false;
    try {
      verified = verifier.verify(signatureBytes);
    } catch (SignatureException ex) {
      verified = false;
    }
    if (verified) {
      System.out.println("Verfied legacy signature:" + signature);
    } else {
      System.out.println("Rejected legacy signature:" + signature);
    }
  }
}
 
Example #22
Source File: RSASigner.java    From oxAuth with MIT License 5 votes vote down vote up
@Override
public boolean validateSignature(String signingInput, String signature) throws SignatureException {
    if (getSignatureAlgorithm() == null) {
        throw new SignatureException("The signature algorithm is null");
    }
    if (rsaPublicKey == null) {
        throw new SignatureException("The RSA public key is null");
    }
    if (signingInput == null) {
        throw new SignatureException("The signing input is null");
    }

    try {
        byte[] sigBytes = Base64Util.base64urldecode(signature);
        byte[] sigInBytes = signingInput.getBytes(Util.UTF8_STRING_ENCODING);

        RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(
                rsaPublicKey.getModulus(),
                rsaPublicKey.getPublicExponent());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

        Signature sign = Signature.getInstance(getSignatureAlgorithm().getAlgorithm(), "BC");
        sign.initVerify(publicKey);
        sign.update(sigInBytes);

        return sign.verify(sigBytes);
    } catch (Exception e) {
        throw new SignatureException(e);
    }
}
 
Example #23
Source File: RSANoLimit.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    boolean result = true;
    Provider p = Security.getProvider("SunJCE");
    System.out.println("Testing provider " + p.getName() + "...");
    // Test#1: make sure Cipher.getMaxAllowedKeyLength returns the
    // correct value
    if (Cipher.getMaxAllowedKeyLength("RSA") != Integer.MAX_VALUE) {
        result = false;
        System.out.println("Test#1 failed");
    }
    // Test#2: try initializing RSA cipher with 4096 key
    String algo = "RSA";
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec
        (new BigInteger(MODULUS4096), new BigInteger(PUB4096));
    KeyFactory kf = KeyFactory.getInstance(algo);
    RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(pubKeySpec);

    Cipher c = Cipher.getInstance(algo + "/ECB/NoPadding", p);
    try {
        c.init(Cipher.ENCRYPT_MODE, pubKey);
    } catch (InvalidKeyException ike) {
        result = false;
        System.out.println("Test#2 failed");
        ike.printStackTrace();
    }

    if (result) {
        System.out.println("All tests passed!");
    } else {
        throw new Exception("One or more test failed!");
    }
}
 
Example #24
Source File: IosRSASignatureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testVerify_SHA384withRSA_Key_Success() throws Exception {
  if (supportedPlatform()) {
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(RSA_2048_modulus, RSA_2048_publicExponent);
    PublicKey pubKey = kf.generatePublic(keySpec);

    Signature sig = Signature.getInstance("SHA384withRSA");
    sig.initVerify(pubKey);
    sig.update(Vector2Data);

    assertTrue("Signature must match expected signature",
            sig.verify(SHA384withRSA_Vector2Signature));
  }
}
 
Example #25
Source File: KeyStoreManager.java    From ebics-java-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
public RSAPublicKey getPublicKey(BigInteger publicExponent, BigInteger modulus)
{
    try {
          return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
      } catch (InvalidKeySpecException | NoSuchAlgorithmException ex) {
          Logger.getLogger(KeyStoreManager.class.getName()).log(Level.SEVERE, null, ex);
          return null;
    }
}
 
Example #26
Source File: RSANoLimit.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    boolean result = true;
    Provider p = Security.getProvider("SunJCE");
    System.out.println("Testing provider " + p.getName() + "...");
    // Test#1: make sure Cipher.getMaxAllowedKeyLength returns the
    // correct value
    if (Cipher.getMaxAllowedKeyLength("RSA") != Integer.MAX_VALUE) {
        result = false;
        System.out.println("Test#1 failed");
    }
    // Test#2: try initializing RSA cipher with 4096 key
    String algo = "RSA";
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec
        (new BigInteger(MODULUS4096), new BigInteger(PUB4096));
    KeyFactory kf = KeyFactory.getInstance(algo);
    RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(pubKeySpec);

    Cipher c = Cipher.getInstance(algo + "/ECB/NoPadding", p);
    try {
        c.init(Cipher.ENCRYPT_MODE, pubKey);
    } catch (InvalidKeyException ike) {
        result = false;
        System.out.println("Test#2 failed");
        ike.printStackTrace();
    }

    if (result) {
        System.out.println("All tests passed!");
    } else {
        throw new Exception("One or more test failed!");
    }
}
 
Example #27
Source File: RSAUtils.java    From mpush with Apache License 2.0 5 votes vote down vote up
/**
 * 使用模和指数生成RSA公钥
 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,
 * 不同JDK默认的补位方式可能不同,如Android默认是RSA
 * /None/NoPadding】
 *
 * @param modulus  模
 * @param exponent 指数
 * @return 公钥
 */
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
    try {
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        LOGGER.error("getPublicKey ex modulus={}, exponent={}", modulus, exponent, e);
        throw new CryptoException("Get PublicKey ex", e);
    }
}
 
Example #28
Source File: RSANoLimit.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    boolean result = true;
    Provider p = Security.getProvider("SunJCE");
    System.out.println("Testing provider " + p.getName() + "...");
    // Test#1: make sure Cipher.getMaxAllowedKeyLength returns the
    // correct value
    if (Cipher.getMaxAllowedKeyLength("RSA") != Integer.MAX_VALUE) {
        result = false;
        System.out.println("Test#1 failed");
    }
    // Test#2: try initializing RSA cipher with 4096 key
    String algo = "RSA";
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec
        (new BigInteger(MODULUS4096), new BigInteger(PUB4096));
    KeyFactory kf = KeyFactory.getInstance(algo);
    RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(pubKeySpec);

    Cipher c = Cipher.getInstance(algo + "/ECB/NoPadding", p);
    try {
        c.init(Cipher.ENCRYPT_MODE, pubKey);
    } catch (InvalidKeyException ike) {
        result = false;
        System.out.println("Test#2 failed");
        ike.printStackTrace();
    }

    if (result) {
        System.out.println("All tests passed!");
    } else {
        throw new Exception("One or more test failed!");
    }
}
 
Example #29
Source File: GpgCryptoTest.java    From OpenPGP-Card with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void generateKey() throws CardException, NoSuchAlgorithmException,
                                 InvalidKeySpecException, SignatureException,
                                 InvalidKeyException {
  // Submit PW3
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x83, "31 32 33 34 35 36 37 38"));

  byte[] publicKeyData = receiveLong(
      card.sendAPDU(0, Gpg.CMD_GENERATE_ASYMETRIC, 0x80, 0, "B6 00", 0));
  TLVDer pk = TLVDer.GetNext(publicKeyData, 0);
  assertEquals(TLVDer.Status.OK, pk.status);
  assertEquals(0x7F49, pk.tag);

  TLVDer tlv = TLVDer.GetNext(pk.data, 0);
  assertEquals(TLVDer.Status.OK, tlv.status);
  assertEquals(0x82, tlv.tag);
  byte[] e = tlv.data;

  tlv = TLVDer.GetNext(pk.data, tlv.currentOffset);
  assertEquals(TLVDer.Status.OK, tlv.status);
  assertEquals(0x81, tlv.tag);
  byte[] modulus = tlv.data;
  assertEquals(2048 / 8, modulus.length);

  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x81, "31 32 33 34 35 36"));
  ResponseAPDU r = assertSW(0x9000, card.sendAPDU(0, Gpg.CMD_COMPUTE_PSO, 0x9E, 0x9A,
                                                  createSha1DigestInfo(signatureTestData), 256));
  assertEquals(2048 / 8, r.getData().length);
  Signature signature = Signature.getInstance("SHA1withRSA");
  KeyFactory keyMaker = KeyFactory.getInstance("RSA");
  RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(1, modulus),
                                                     new BigInteger(1, e));
  RSAPublicKey pubKey = (RSAPublicKey) keyMaker.generatePublic(pubKeySpec);
  signature.initVerify(pubKey);
  signature.update(toByteArray(signatureTestData));
  assertTrue(signature.verify(r.getData()));
}
 
Example #30
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
private static RSAPublicKey toJcaPublicKey(
        org.bouncycastle.asn1.pkcs.RSAPrivateKey rsaPrivateKey)
        throws GeneralSecurityException {
    RSAPublicKeySpec spec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(),
            rsaPrivateKey.getPublicExponent());
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(spec);

    return publicKey;
}