Example usage for java.security AlgorithmParameters init

List of usage examples for java.security AlgorithmParameters init

Introduction

In this page you can find the example usage for java.security AlgorithmParameters init.

Prototype

public final void init(byte[] params) throws IOException 

Source Link

Document

Imports the specified parameters and decodes them according to the primary decoding format for parameters.

Usage

From source file:com.slamd.admin.AdminServlet.java

/**
 * Generates page content based on an MD5-digest of the query string.
 *
 * @param  requestInfo   The state information for this request.
 * @param  digestString  The base64-encoded MD5 digest of the query string to
 *                       use to generate the page.
 *//*  w ww .ja v  a  2 s  . c  o m*/
static void generatePageFromMD5(RequestInfo requestInfo, String digestString) {
    try {
        String dataFile = Constants.MD5_CONTENT_BASE_PATH + '/' + digestString;
        InputStream inputStream = slamdServer.getClass().getClassLoader().getResourceAsStream(dataFile);

        byte[] salt = { 0, 0, 0, 0, 0, 0, 0, 0 };
        char[] queryChars = requestInfo.request.getQueryString().toCharArray();
        int iterations = 1000;
        String cipherName = "PBEWithMD5AndDES";
        StringBuilder htmlBody = requestInfo.htmlBody;

        AlgorithmParameters algorithmParams = AlgorithmParameters.getInstance(cipherName);
        algorithmParams.init(new PBEParameterSpec(salt, iterations));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(cipherName);
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(queryChars));
        Cipher cipher = Cipher.getInstance(cipherName);
        cipher.init(Cipher.DECRYPT_MODE, key, algorithmParams);

        int bytesIn;
        int bytesOut;
        byte[] inBuffer = new byte[4096];
        byte[] outBuffer = new byte[8192];
        while ((bytesIn = inputStream.read(inBuffer)) > 0) {
            bytesOut = cipher.update(inBuffer, 0, bytesIn, outBuffer);
            htmlBody.append(new String(outBuffer, 0, bytesOut));
        }

        htmlBody.append(new String(cipher.doFinal()));
        inputStream.close();
    } catch (Exception e) {
        requestInfo.htmlBody.append(JobClass.stackTraceToString(e));
    }
}

From source file:org.alfresco.encryption.AbstractEncryptor.java

/**
 * {@inheritDoc}/*w ww  .  j  a v a  2 s.c  o m*/
 */
@Override
public AlgorithmParameters decodeAlgorithmParameters(byte[] encoded) {
    try {
        AlgorithmParameters p = null;
        String algorithm = "DESede";
        if (getCipherProvider() != null) {
            p = AlgorithmParameters.getInstance(algorithm, getCipherProvider());
        } else {
            p = AlgorithmParameters.getInstance(algorithm);
        }
        p.init(encoded);
        return p;
    } catch (Exception e) {
        throw new AlfrescoRuntimeException("", e);
    }
}

From source file:org.eclipse.leshan.server.demo.LeshanServerDemo.java

public static void createAndStartServer(int webPort, String localAddress, int localPort,
        String secureLocalAddress, int secureLocalPort, String redisUrl) throws Exception {
    // Prepare LWM2M server
    LeshanServerBuilder builder = new LeshanServerBuilder();
    builder.setLocalAddress(localAddress, localPort);
    builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
    builder.setEncoder(new DefaultLwM2mNodeEncoder());
    LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder();
    builder.setDecoder(decoder);/*from www  .j  a  v a 2s  .co m*/

    // connect to redis if needed
    Pool<Jedis> jedis = null;
    if (redisUrl != null) {
        // TODO: support sentinel pool and make pool configurable
        jedis = new JedisPool(new URI(redisUrl));
    }

    // Get public and private server key
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    try {
        // Get point values
        byte[] publicX = Hex
                .decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray());
        byte[] publicY = Hex
                .decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray());
        byte[] privateS = Hex
                .decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray());

        // Get Elliptic Curve Parameter spec for secp256r1
        AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
        algoParameters.init(new ECGenParameterSpec("secp256r1"));
        ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

        // Create key specs
        KeySpec publicKeySpec = new ECPublicKeySpec(
                new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), parameterSpec);
        KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);

        // Get keys
        publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
        privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
        builder.setPublicKey(publicKey);
        builder.setPrivateKey(privateKey);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) {
        LOG.error("Unable to initialize RPK.", e);
        System.exit(-1);
    }

    // Define model provider
    LwM2mModelProvider modelProvider = new StandardModelProvider();
    builder.setObjectModelProvider(modelProvider);

    // Set securityStore & registrationStore
    EditableSecurityStore securityStore;
    if (jedis == null) {
        // use file persistence
        securityStore = new FileSecurityStore();
    } else {
        // use Redis Store
        securityStore = new RedisSecurityStore(jedis);
        builder.setRegistrationStore(new RedisRegistrationStore(jedis));
    }
    builder.setSecurityStore(securityStore);

    // Create and start LWM2M server
    LeshanServer lwServer = builder.build();

    // Now prepare Jetty
    Server server = new Server(webPort);
    WebAppContext root = new WebAppContext();
    root.setContextPath("/");
    root.setResourceBase(LeshanServerDemo.class.getClassLoader().getResource("webapp").toExternalForm());
    root.setParentLoaderPriority(true);
    server.setHandler(root);

    // Create Servlet
    EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecureAddress().getPort());
    ServletHolder eventServletHolder = new ServletHolder(eventServlet);
    root.addServlet(eventServletHolder, "/event/*");

    ServletHolder clientServletHolder = new ServletHolder(
            new ClientServlet(lwServer, lwServer.getSecureAddress().getPort()));
    root.addServlet(clientServletHolder, "/api/clients/*");

    ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(securityStore, publicKey));
    root.addServlet(securityServletHolder, "/api/security/*");

    ServletHolder objectSpecServletHolder = new ServletHolder(
            new ObjectSpecServlet(lwServer.getModelProvider()));
    root.addServlet(objectSpecServletHolder, "/api/objectspecs/*");

    // Start Jetty & Leshan
    lwServer.start();
    server.start();
    LOG.info("Web server started at {}.", server.getURI());
}

From source file:org.eclipse.leshan.standalone.servlet.json.SecurityDeserializer.java

@Override
public SecurityInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json == null) {
        return null;
    }//  w ww. ja  va 2 s.c  o m

    SecurityInfo info = null;

    if (json.isJsonObject()) {
        JsonObject object = (JsonObject) json;

        String endpoint = null;
        if (object.has("endpoint")) {
            endpoint = object.get("endpoint").getAsString();
        } else {
            throw new JsonParseException("Missing endpoint");
        }

        JsonObject psk = (JsonObject) object.get("psk");
        JsonObject rpk = (JsonObject) object.get("rpk");
        if (psk != null) {
            // PSK Deserialization
            String identity = null;
            if (psk.has("identity")) {
                identity = psk.get("identity").getAsString();
            } else {
                throw new JsonParseException("Missing PSK identity");
            }
            byte[] key;
            try {
                key = Hex.decodeHex(psk.get("key").getAsString().toCharArray());
            } catch (DecoderException e) {
                throw new JsonParseException(e);
            }

            info = SecurityInfo.newPreSharedKeyInfo(endpoint, identity, key);
        } else if (rpk != null) {
            PublicKey key;
            try {
                byte[] x = Hex.decodeHex(rpk.get("x").getAsString().toCharArray());
                byte[] y = Hex.decodeHex(rpk.get("y").getAsString().toCharArray());
                String params = rpk.get("params").getAsString();

                AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
                algoParameters.init(new ECGenParameterSpec(params));
                ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

                KeySpec keySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)),
                        parameterSpec);

                key = KeyFactory.getInstance("EC").generatePublic(keySpec);
            } catch (DecoderException | InvalidKeySpecException | NoSuchAlgorithmException
                    | InvalidParameterSpecException e) {
                throw new JsonParseException("Invalid security info content", e);
            }
            info = SecurityInfo.newRawPublicKeyInfo(endpoint, key);
        } else {
            throw new JsonParseException("Invalid security info content");
        }
    }

    return info;
}