Example usage for java.util Base64 getUrlDecoder

List of usage examples for java.util Base64 getUrlDecoder

Introduction

In this page you can find the example usage for java.util Base64 getUrlDecoder.

Prototype

public static Decoder getUrlDecoder() 

Source Link

Document

Returns a Decoder that decodes using the URL and Filename safe type base64 encoding scheme.

Usage

From source file:com.ibm.zurich.Main.java

public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
    Option help = new Option(HELP, "print this message");
    Option version = new Option(VERSION, "print the version information");

    Options options = new Options();

    Option useCurve = Option.builder(USECURVE).hasArg().argName("curve")
            .desc("Specify the BN Curve. Options: " + curveOptions()).build();
    Option isskeygen = Option.builder(IKEYGEN).numberOfArgs(3).argName("ipk><isk><RL")
            .desc("Generate Issuer key pair and empty revocation list and store it in files").build();
    Option join1 = Option.builder(JOIN1).numberOfArgs(3).argName("ipk><authsk><msg1")
            .desc("Create an authenticator secret key and perform the first step of the join protocol").build();
    Option join2 = Option.builder(JOIN2).numberOfArgs(4).argName("ipk><isk><msg1><msg2")
            .desc("Complete the join protocol").build();
    Option verify = Option.builder(VERIFY).numberOfArgs(5).argName("ipk><sig><krd><appId><RL")
            .desc("Verify a signature").build();
    Option sign = Option.builder(SIGN).numberOfArgs(6).argName("ipk><authsk><msg2><appId><krd><sig")
            .desc("create a signature").build();

    options.addOption(help);/*from   w w  w  .  ja v a  2  s.  c o m*/
    options.addOption(version);
    options.addOption(useCurve);
    options.addOption(isskeygen);
    options.addOption(sign);
    options.addOption(verify);
    options.addOption(join1);
    options.addOption(join2);

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new DefaultParser();

    //FIXME Choose a proper instantiation of SecureRandom depending on the platform
    SecureRandom random = new SecureRandom();
    Base64.Encoder encoder = Base64.getUrlEncoder();
    Base64.Decoder decoder = Base64.getUrlDecoder();
    try {
        CommandLine line = parser.parse(options, args);
        BNCurveInstantiation instantiation = null;
        BNCurve curve = null;
        if (line.hasOption(HELP) || line.getOptions().length == 0) {
            formatter.printHelp(USAGE, options);
        } else if (line.hasOption(VERSION)) {
            System.out.println("Version " + Main.class.getPackage().getImplementationVersion());
        } else if (line.hasOption(USECURVE)) {
            instantiation = BNCurveInstantiation.valueOf(line.getOptionValue(USECURVE));
            curve = new BNCurve(instantiation);
        } else {
            System.out.println("Specify the curve to use.");
            return;
        }

        if (line.hasOption(IKEYGEN)) {
            String[] optionValues = line.getOptionValues(IKEYGEN);

            // Create secret key
            IssuerSecretKey sk = Issuer.createIssuerKey(curve, random);

            // Store pk
            writeToFile((new IssuerPublicKey(curve, sk, random)).toJSON(curve), optionValues[0]);

            // Store sk
            writeToFile(sk.toJson(curve), optionValues[1]);

            // Create empty revocation list and store
            HashSet<BigInteger> rl = new HashSet<BigInteger>();
            writeToFile(Verifier.revocationListToJson(rl, curve), optionValues[2]);
        } else if (line.hasOption(SIGN)) {
            //("ipk><authsk><msg2><appId><krd><sig")

            String[] optionValues = line.getOptionValues(SIGN);
            IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));

            BigInteger authsk = curve.bigIntegerFromB(decoder.decode(readFromFile(optionValues[1])));
            JoinMessage2 msg2 = new JoinMessage2(curve, readStringFromFile(optionValues[2]));

            // setup a new authenticator
            Authenticator auth = new Authenticator(curve, ipk, authsk);
            auth.EcDaaJoin1(curve.getRandomModOrder(random));
            if (auth.EcDaaJoin2(msg2)) {
                EcDaaSignature sig = auth.EcDaaSign(optionValues[3]);

                // Write krd to file
                writeToFile(sig.krd, optionValues[4]);

                // Write signature to file
                writeToFile(sig.encode(curve), optionValues[5]);

                System.out.println("Signature written to " + optionValues[5]);
            } else {
                System.out.println("JoinMsg2 invalid");
            }
        } else if (line.hasOption(VERIFY)) {
            Verifier ver = new Verifier(curve);
            String[] optionValues = line.getOptionValues(VERIFY);
            String pkFile = optionValues[0];
            String sigFile = optionValues[1];
            String krdFile = optionValues[2];
            String appId = optionValues[3];
            String rlPath = optionValues[4];
            byte[] krd = Files.readAllBytes(Paths.get(krdFile));
            IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(pkFile));
            EcDaaSignature sig = new EcDaaSignature(Files.readAllBytes(Paths.get(sigFile)), krd, curve);
            boolean valid = ver.verify(sig, appId, pk,
                    Verifier.revocationListFromJson(readStringFromFile(rlPath), curve));
            System.out.println("Signature is " + (valid ? "valid." : "invalid."));
        } else if (line.hasOption(JOIN1)) {
            String[] optionValues = line.getOptionValues(JOIN1);
            IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));

            // Create authenticator key
            BigInteger sk = curve.getRandomModOrder(random);
            writeToFile(encoder.encodeToString(curve.bigIntegerToB(sk)), optionValues[1]);
            Authenticator auth = new Authenticator(curve, ipk, sk);
            JoinMessage1 msg1 = auth.EcDaaJoin1(curve.getRandomModOrder(random));
            writeToFile(msg1.toJson(curve), optionValues[2]);
        } else if (line.hasOption(JOIN2)) {
            String[] optionValues = line.getOptionValues(JOIN2);

            // create issuer with the specified key
            IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));
            IssuerSecretKey sk = new IssuerSecretKey(curve, readStringFromFile(optionValues[1]));
            Issuer iss = new Issuer(curve, sk, pk);

            JoinMessage1 msg1 = new JoinMessage1(curve, readStringFromFile(optionValues[2]));

            // Note that we do not check for nonce freshness.
            JoinMessage2 msg2 = iss.EcDaaIssuerJoin(msg1, false);
            if (msg2 == null) {
                System.out.println("Join message invalid.");
            } else {
                System.out.println("Join message valid, msg2 written to file.");
                writeToFile(msg2.toJson(curve), optionValues[3]);
            }
        }
    } catch (ParseException e) {
        System.out.println("Error parsing input.");
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.tomitribe.tribestream.registryng.security.oauth2.AccessTokenService.java

private String tryExtractingTheUser(final String accessToken) {
    try {// w w w . java2s. co  m
        final String[] segments = accessToken.split("\\.");
        if (segments.length != 3) {
            return null;
        }
        JsonNode node = mapper.readTree(Base64.getUrlDecoder().decode(segments[1]));
        for (final String part : configuration.getJwtUsernameAttribute().split("\\/")) {
            node = node.get(part);
            if (node == null) {
                return null;
            }
        }
        return ofNullable(node).filter(n -> n.getNodeType() == JsonNodeType.STRING).map(JsonNode::textValue)
                .orElse(null);
    } catch (final RuntimeException | IOException re) {
        return null;
    }
}

From source file:de.tor.tribes.io.TroopAmountElement.java

public TroopAmountElement loadFromBase64(String base64) {
    try {/*from w  w  w.j  a  v  a 2  s  .  co  m*/
        setDynamicAmount(new String(Base64.getUrlDecoder().decode(base64), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        logger.fatal("Wrong encoding", e);
        throw new RuntimeException("Unsupported encoding", e);
    } catch (IllegalArgumentException e) {
        //old format, set to 0
        setDynamicAmount("0");
    }
    return this;
}

From source file:org.codelibs.fess.helper.DocumentHelper.java

public String decodeSimilarDocHash(final String hash) {
    if (hash != null && hash.startsWith(SIMILAR_DOC_HASH_PREFIX)
            && hash.length() > SIMILAR_DOC_HASH_PREFIX.length()) {
        final byte[] decode = Base64.getUrlDecoder().decode(hash.substring(SIMILAR_DOC_HASH_PREFIX.length()));
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                new GZIPInputStream(new ByteArrayInputStream(decode)), Constants.UTF_8))) {
            return ReaderUtil.readText(reader);
        } catch (final IOException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to decode " + hash, e);
            }/*from   w ww  .j  a  v  a  2  s  . c o m*/
        }
    }
    return hash;
}

From source file:org.trellisldp.auth.oauth.JwksAuthenticator.java

private static Map<String, Key> buildKeys(final String location) {
    final Map<String, Key> keys = new HashMap<>();
    // TODO eventually, this will become part of the JJWT library
    final Deserializer<Map<String, List<Map<String, String>>>> deserializer = new JacksonDeserializer<>();
    final Map<String, List<Map<String, String>>> data = new HashMap<>();
    try (final InputStream input = new URL(location).openConnection().getInputStream()) {
        deserializer.deserialize(IOUtils.toByteArray(input)).forEach(data::put);
    } catch (final IOException ex) {
        LOGGER.error("Error fetching/parsing jwk document", ex);
    }/*from   w  w  w .ja  v  a  2 s.  co m*/

    for (final Map<String, String> jwk : data.getOrDefault("keys", emptyList())) {
        final BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(jwk.get("n")));
        final BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(jwk.get("e")));
        OAuthUtils.buildRSAPublicKey("RSA", modulus, exponent).ifPresent(key -> keys.put(jwk.get("kid"), key));
    }
    return keys;
}

From source file:org.zoxweb.shared.util.Base64Test.java

public static void main(String[] arg) {
    byte[] num = { 0, 1, 2 };

    String toConvert = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";

    System.out.println(toConvert.length());
    //System.out.println(SharedBase64.computeBase64ArraySize(num));
    System.out.println(new String(SharedBase64.encode(num)));

    long tsOld = System.nanoTime();
    byte[] oldBase64 = SharedBase64.encode(toConvert.getBytes());

    byte[] decodedBase64 = SharedBase64.decode(oldBase64);

    tsOld = System.nanoTime() - tsOld;
    System.out.println(oldBase64.length);
    System.out.println(new String(oldBase64));
    System.out.println(new String(decodedBase64));
    System.out.println(tsOld + "nanos");

    String[] testArray = { "1", "12", "123", "1234", "12345", "123456", "1234567", "12345678", "123456789",
            "1234567890", "a", "ab", "abc", "abcd", "abcde", "abcdef", "abcdefg", "abcdefgh", "abcdefghi",
            "abcdefghij", toConvert, "asure.", "sure.", "any carnal pleasure" };

    String partial = "naelmarwan";

    System.out.println("Length of Array: " + testArray.length);
    long tsJ, tsZW;
    byte[] sharedEncodedeBase64, sharedDecodedBase64, java64Encoded, java64Decodded;
    Encoder javaEncoder = java.util.Base64.getEncoder();
    Decoder javaDecoder = java.util.Base64.getDecoder();
    for (int i = 0; i < testArray.length; i++) {
        System.out.println(i + 1 + "." + "Original Value: " + testArray[i]);

        byte toEncode[] = testArray[i].getBytes();
        tsZW = System.nanoTime();
        sharedEncodedeBase64 = SharedBase64.encode(Base64Type.DEFAULT, toEncode, 0, toEncode.length);
        sharedDecodedBase64 = SharedBase64.decode(Base64Type.DEFAULT, sharedEncodedeBase64, 0,
                sharedEncodedeBase64.length);
        tsZW = System.nanoTime() - tsZW;

        tsZW = System.nanoTime();
        sharedEncodedeBase64 = SharedBase64.encode(Base64Type.DEFAULT, toEncode, 0, toEncode.length);
        sharedDecodedBase64 = SharedBase64.decode(Base64Type.DEFAULT, sharedEncodedeBase64, 0,
                sharedEncodedeBase64.length);
        tsZW = System.nanoTime() - tsZW;

        tsJ = System.nanoTime();//  w  w  w.  j  a  v  a  2s  . c  o  m
        java64Encoded = javaEncoder.encode(toEncode);//.encodeBase64(toEncode);
        java64Decodded = javaDecoder.decode(java64Encoded);
        tsJ = System.nanoTime() - tsJ;

        tsJ = System.nanoTime();
        java64Encoded = javaEncoder.encode(toEncode);//.encodeBase64(toEncode);
        java64Decodded = javaDecoder.decode(java64Encoded);
        tsJ = System.nanoTime() - tsJ;

        System.out.println(i + 1 + "." + "Encode Base64: " + new String(sharedEncodedeBase64) + ":\t\t"
                + Arrays.equals(sharedEncodedeBase64, java64Encoded));
        System.out.println(i + 1 + "." + "Decoded Base64: " + new String(sharedDecodedBase64) + ":\t\t"
                + Arrays.equals(sharedDecodedBase64, java64Decodded));
        System.out.println("zoxweb:" + tsZW + " java:" + tsJ + " delta:" + (tsJ - tsZW) + " factor:"
                + ((float) tsJ / (float) tsZW));
        System.out.println(tsZW + " nanos: " + testArray[i].equals(new String(sharedDecodedBase64)));
    }

    byte[] byteArray = new byte[256];

    for (int i = 0; i < byteArray.length; i++) {
        byteArray[i] = (byte) i;
    }

    byte[] byteArrayBase64 = SharedBase64.encode(byteArray);
    System.out.println(new String(byteArrayBase64));
    System.out
            .println("Original Array length:" + byteArray.length + " base 64 length:" + byteArrayBase64.length);
    byte[] byteArrayOriginal = SharedBase64.decode(byteArrayBase64);
    System.out.println(Arrays.equals(byteArray, byteArrayOriginal));

    System.out.println("BASE_64 length:" + SharedBase64.BASE_64.length + " REVERSE_BASE_64 length:"
            + SharedBase64.REVERSE_BASE_64.length);

    System.out.println("Partial test:" + new String(SharedBase64.encode(partial.getBytes(), 4, 6)) + ","
            + new String(SharedBase64.encode(partial.getBytes(), 1, 1)));
    byte fullname[] = SharedBase64.encode(partial.getBytes());
    System.out.println("Marwan " + new String(fullname));

    System.out.println("Equals:" + SharedUtil.slowEquals(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes(),
            SharedBase64.BASE_64));

    try {
        byte[] b64 = SharedBase64.encode("1234567890");
        String str = SharedStringUtil.toString(b64);
        System.out.println("1234567890 b64:" + str);
        System.out.println(SharedBase64.decodeAsString(Base64Type.DEFAULT, "MTIzNDU2Nzg5MA"));
        System.out.println(SharedBase64.decodeAsString(Base64Type.DEFAULT, "MTIzNDU2Nzg5MA="));

        b64 = SharedBase64.decode(str + "^");
    } catch (Exception e) {
        e.printStackTrace();
    }

    UUID uuid = UUID.randomUUID();

    byte[] uuidBytes = BytesValue.LONG.toBytes(null, 0, uuid.getMostSignificantBits(),
            uuid.getMostSignificantBits());
    String str = SharedStringUtil.toString(SharedBase64.encode(Base64Type.URL, uuidBytes));
    String str1 = Base64.getUrlEncoder().encodeToString(uuidBytes);
    System.out.println(str + " " + str1 + " " + str1.equals(str));

    byte[] b = SharedBase64.decode(Base64Type.URL, str);
    byte[] b1 = Base64.getUrlDecoder().decode(str);
    System.out.println(Arrays.equals(uuidBytes, b) + " " + Arrays.equals(uuidBytes, b1));
    str = SharedStringUtil.toString(SharedBase64.encode(Base64Type.URL, b));
    System.out.println(str);

    String base64URL = "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
    String plain = SharedBase64.decodeAsString(Base64Type.URL, base64URL);
    System.out.println(plain);
    System.out.println(SharedBase64.encodeAsString(Base64Type.URL, plain));
}