Example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

List of usage examples for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec.

Prototype

public X509EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new X509EncodedKeySpec with the given encoded key.

Usage

From source file:tech.beshu.ror.acl.blocks.rules.impl.JwtAuthSyncRule.java

@Override
public CompletableFuture<RuleExitResult> match(__old_RequestContext rc) {
    Optional<String> token = Optional.of(rc.getHeaders()).map(m -> m.get(settings.getHeaderName()))
            .flatMap(JwtAuthSyncRule::extractToken);

    /*/*from www .j av a 2 s.  com*/
      JWT ALGO    FAMILY
      =======================
      NONE        None
            
      HS256       HMAC
      HS384       HMAC
      HS512       HMAC
            
      RS256       RSA
      RS384       RSA
      RS512       RSA
      PS256       RSA
      PS384       RSA
      PS512       RSA
            
      ES256       EC
      ES384       EC
      ES512       EC
    */

    if (!token.isPresent()) {
        logger.debug("Authorization header is missing or does not contain a bearer token");
        return CompletableFuture.completedFuture(NO_MATCH);
    }

    try {

        JwtParser parser = Jwts.parser();

        // Defaulting to HMAC for backward compatibility
        String algoFamily = settings.getAlgo().map(String::toUpperCase).orElse("HMAC");
        if (settings.getKey() == null) {
            algoFamily = "NONE";
        }

        if (!"NONE".equals(algoFamily)) {

            if ("RSA".equals(algoFamily)) {
                try {
                    byte[] keyBytes = Base64.decodeBase64(settings.getKey());
                    KeyFactory kf = KeyFactory.getInstance("RSA");
                    PublicKey pubKey = kf.generatePublic(new X509EncodedKeySpec(keyBytes));
                    parser.setSigningKey(pubKey);
                } catch (GeneralSecurityException gso) {
                    throw new RuntimeException(gso);
                }
            }

            else if ("EC".equals(algoFamily)) {
                try {
                    byte[] keyBytes = Base64.decodeBase64(settings.getKey());
                    KeyFactory kf = KeyFactory.getInstance("EC");
                    PublicKey pubKey = kf.generatePublic(new X509EncodedKeySpec(keyBytes));
                    parser.setSigningKey(pubKey);
                } catch (GeneralSecurityException gso) {
                    throw new RuntimeException(gso);
                }
            }

            else if ("HMAC".equals(algoFamily)) {
                parser.setSigningKey(settings.getKey());
            } else {
                throw new RuntimeException("unrecognised algorithm family " + algoFamily
                        + ". Should be either of: HMAC, EC, RSA, NONE");
            }
        }

        Claims jws;
        if (settings.getKey() != null) {
            jws = parser.parseClaimsJws(token.get()).getBody();
        } else {
            String[] ar = token.get().split("\\.");
            if (ar.length < 2) {
                // token is not a valid JWT
                return CompletableFuture.completedFuture(NO_MATCH);
            }
            String tokenNoSig = ar[0] + "." + ar[1] + ".";
            jws = parser.parseClaimsJwt(tokenNoSig).getBody();
        }

        Claims finalJws = jws;
        Optional<String> user = settings.getUserClaim().map(claim -> finalJws.get(claim, String.class));
        if (settings.getUserClaim().isPresent())
            if (!user.isPresent()) {
                return CompletableFuture.completedFuture(NO_MATCH);
            } else {
                rc.setLoggedInUser(new LoggedUser(user.get()));
            }

        Optional<Set<String>> roles = this.extractRoles(jws);
        if (settings.getRolesClaim().isPresent() && !roles.isPresent()) {
            return CompletableFuture.completedFuture(NO_MATCH);
        }
        if (!settings.getRoles().isEmpty()) {
            if (!roles.isPresent()) {
                return CompletableFuture.completedFuture(NO_MATCH);
            } else {
                Set<String> r = roles.get();
                if (r.isEmpty() || Sets.intersection(r, settings.getRoles()).isEmpty())
                    return CompletableFuture.completedFuture(NO_MATCH);
            }
        }

        if (settings.getExternalValidator().isPresent()) {
            return httpClient.authenticate("x", token.get()).thenApply(resp -> resp ? MATCH : NO_MATCH);
        }
        return CompletableFuture.completedFuture(MATCH);

    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException e) {
        return CompletableFuture.completedFuture(NO_MATCH);
    }
}

From source file:bftsmart.reconfiguration.util.RSAKeyLoaderO.java

private PublicKey getPublicKeyFromString(String key) throws Exception {

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

    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(key));

    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    return publicKey;

}

From source file:de.alpharogroup.crypto.key.reader.PublicKeyReader.java

/**
 * Read public key./*  w w w  .ja va  2s. com*/
 *
 * @param publicKeyBytes
 *            the public key bytes
 * @param provider
 *            the provider
 * @param algorithm
 *            the algorithm for the {@link KeyFactory}
 * @return the public key
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PublicKey readPublicKey(final byte[] publicKeyBytes, final String provider,
        final String algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
    final KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    final PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}

From source file:com.jinhe.tss.framework.license.LicenseManager.java

/**
 * <pre>/*from   w  w  w.j  a v  a2  s .c  om*/
 * ?license??
 * ?Mac??????
 * ???????
 * </pre>
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.macAddress;
    if (!EasyUtils.isNullOrEmpty(macAddress)) {
        String curMacAddress = MacAddress.getMacAddress();
        if (!macAddress.equals(curMacAddress)) {
            return false;
        }
    }

    File keyFile = new File(LicenseFactory.PUBLIC_KEY_FILE);
    String publicKey = FileHelper.readFile(keyFile).trim();

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance(LicenseFactory.KEY_ALGORITHM);
    java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance(LicenseFactory.KEY_ALGORITHM);
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.licenseSignature));
}

From source file:com.mycompany.bankinterface.crypto.Signer.java

public boolean isVerified(String clearText, String signature, String signerPublicKey) throws SignerException {

    boolean isVerified = false;

    byte[] signerPublicKeyBytes = Base64.decodeBase64(signerPublicKey);
    byte[] signatureAsBytes = Base64.decodeBase64(signature);

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(signerPublicKeyBytes);
    KeyFactory keyFactory;//  ww  w.  j a  v  a 2  s  . c  om

    try {
        keyFactory = KeyFactory.getInstance(PUBLIC_KEY_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Failed to create key factory", ex);
    }

    PublicKey pubKey;

    try {
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException ex) {
        throw new SignerException("Failed to create public key", ex);
    }

    Signature dsa;

    try {
        dsa = Signature.getInstance(SIGNER_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Could not get signing instance", ex);
    }

    try {
        dsa.initVerify(pubKey);
        dsa.update(clearText.getBytes());
        isVerified = dsa.verify(signatureAsBytes);

    } catch (InvalidKeyException | SignatureException ex) {
        throw new SignerException("Could not verify data", ex);
    }

    return isVerified;
}

From source file:tv.ouya.sample.game.OptionsActivity.java

/**
 * Called when the activity is first created.
 *//*from   ww  w  .j  av  a  2  s . c  om*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.options);

    levelToRadioButton = new HashMap<Options.Level, RadioButton>();
    levelToRadioButton.put(FREEDOM, ((RadioButton) findViewById(R.id.radio_freedom)));
    levelToRadioButton.put(ALLEYWAY, ((RadioButton) findViewById(R.id.radio_alleyway)));
    levelToRadioButton.put(BOXY, ((RadioButton) findViewById(R.id.radio_boxy)));

    try {
        InputStream inputStream = getResources().openRawResource(R.raw.key);
        applicationKey = new byte[inputStream.available()];
        inputStream.read(applicationKey);
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Create a reverse map
    radioButtonToLevel = new HashMap<RadioButton, Options.Level>();
    for (Options.Level level : levelToRadioButton.keySet()) {
        radioButtonToLevel.put(levelToRadioButton.get(level), level);
    }

    // Initialize the UI
    processReceipts(null);
    toggleProgressIndicator(true);

    mOuyaFacade = OuyaFacade.getInstance();
    mOuyaFacade.init(this, DEVELOPER_ID);

    String prevSelectedLevel = mOuyaFacade.getGameData(PREV_SELECTED_LEVEL_KEY);
    if (prevSelectedLevel != null) {
        Options.Level prevLevel = Options.Level.valueOf(prevSelectedLevel);
        Options.getInstance().setLevel(prevLevel);
    }

    levelToRadioButton.get(Options.getInstance().getLevel()).setChecked(true);

    Button quit = (Button) findViewById(R.id.back_button);
    quit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(applicationKey);
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        mPublicKey = keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to create encryption key", e);
    }
}

From source file:org.javaweb.utils.RSAUtils.java

/**
 * RSA???/* w  w  w  .  ja  v  a2s  .c o  m*/
 *
 * @param data ?
 * @param key  
 * @param sign ??Base64
 * @return
 * @throws Exception
 */
public static boolean verify(byte[] data, Key key, String sign) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);

    return signature.verify(Base64.decodeBase64(sign));
}

From source file:net.padlocksoftware.padlock.KeyManager.java

/**
 * Import a Padlock 2.x (DSA based) KeyPair from an InputStream.  The stream is
 * assumed to have been previously exported in a supported format using the
 * exportKeyPair methods.//ww  w . j  a va2s.  com
 * @param stream The KeyPair stream to import.
 * @return The DSA KeyPair contained in the specified file.
 * @throws java.io.IOException If file is missing or contain invalid data.
 * @since 2.0
 */
public static KeyPair importKeyPair(InputStream stream) throws IOException {
    if (stream == null)
        throw new IllegalArgumentException("Stream cannot be null");

    KeyPair pair = null;
    Properties p = new Properties();
    p.load(stream);
    stream.close();
    String pri = p.getProperty("private");
    String pub = p.getProperty("public");

    if (pri == null || pub == null) {
        throw new IOException("Stream data is invalid");
    }

    // Load the keys
    try {

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Hex.decodeHex(pri.toCharArray()));
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Hex.decodeHex(pub.toCharArray()));
        PublicKey publicKey = keyFactory.generatePublic(pubSpec);

        pair = new KeyPair(publicKey, privateKey);
    } catch (Exception e) {
        throw new RuntimeException("Invalid stream: " + e.getMessage());
    }

    return pair;
}

From source file:org.slc.sli.bulk.extract.files.ExtractFileTest.java

/**
 * Runs before JUnit tests and does the initiation work for the tests.
 * @throws IOException// www. j a v a2 s.c o m
 *          if an I/O error occurred
 * @throws NoSuchFieldException
 *          if a field is not found
 */
@Before
public void init() throws Exception {
    Map<String, PublicKey> appKey = new HashMap<String, PublicKey>();
    X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(PUBLIC_KEY));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey publicKey = kf.generatePublic(spec);

    SecurityEventUtil securityEventUtil = Mockito.mock(SecurityEventUtil.class);
    SecurityEvent event = createSE();
    Mockito.when(securityEventUtil.createSecurityEvent(Mockito.anyString(), Mockito.anyString(),
            Mockito.eq(LogLevelType.TYPE_INFO), Mockito.anyString(), Mockito.any(BEMessageCode.class),
            Mockito.anyString())).thenReturn(event);
    Mockito.when(securityEventUtil.createSecurityEvent(Mockito.anyString(), Mockito.anyString(),
            Mockito.eq(LogLevelType.TYPE_ERROR), Mockito.any(BEMessageCode.class))).thenReturn(event);

    appKey.put(testApp, publicKey);
    archiveFile = new ExtractFile(new File("./"), FILE_NAME, clientKeys, securityEventUtil);
    archiveFile.setClientKeys(appKey);

    File parentDir = (File) PrivateAccessor.getField(archiveFile, "tempDir");

    ManifestFile metaFile = new ManifestFile(parentDir);
    metaFile.generateMetaFile(new DateTime());
    Assert.assertTrue(metaFile.getFile() != null);
    Assert.assertTrue(metaFile.getFile().getName() != null);
    PrivateAccessor.setField(archiveFile, "manifestFile", metaFile);

    Map<String, JsonFileWriter> files = new HashMap<String, JsonFileWriter>();
    File studentFile = File.createTempFile("student", ".json.gz", parentDir);
    String fileNamePrefix = studentFile.getName().substring(0, studentFile.getName().indexOf(".json.gz"));
    JsonFileWriter studentExtractFile = new JsonFileWriter(parentDir, fileNamePrefix);
    PrivateAccessor.setField(studentExtractFile, "file", studentFile);

    files.put("student", studentExtractFile);
    PrivateAccessor.setField(archiveFile, "dataFiles", files);
}

From source file:org.diorite.impl.auth.yggdrasil.YggdrasilSessionService.java

public YggdrasilSessionService(final Proxy proxy, final String clientToken) {
    this.proxy = proxy;
    this.clientToken = clientToken;
    try {/*from w  ww  . ja  v  a2s .  c  o m*/
        //noinspection HardcodedFileSeparator
        final KeySpec spec = new X509EncodedKeySpec(IOUtils.toByteArray(
                YggdrasilSessionService.class.getResourceAsStream("/yggdrasil_session_pubkey.der")));
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        this.publicKey = keyFactory.generatePublic(spec);
    } catch (final Exception e) {
        //noinspection HardcodedFileSeparator
        throw new Error("Missing/invalid yggdrasil public key!");
    }
}