com.tcloud.bee.key.server.service.impl.KeyManageServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.tcloud.bee.key.server.service.impl.KeyManageServiceImpl.java

Source

/**
 * Copyright 2013 Trend Micro Incorporated
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tcloud.bee.key.server.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import org.apache.commons.codec.binary.Hex;
import org.apache.hadoop.io.crypto.bee.BeeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.tcloud.bee.key.server.restful.Param;
import com.tcloud.bee.key.server.service.KeyManageService;

/**
 * 
 * @author kyle
 *
 */
@Configuration
@PropertySource("classpath:app-config.properties")
@Service("KeyManageService")
public class KeyManageServiceImpl implements KeyManageService {
    final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    Environment env;

    @Override
    public QueryResult cleanKeyfiles() {
        logger.info("Remove file folder:" + env.getProperty("keyfile.path"));
        BeeConstants.ResponseStatus status = BeeConstants.ResponseStatus.SUCCESS;
        File keyfilefolder = new File(env.getProperty("keyfile.path"));
        if (keyfilefolder.exists()) {
            File[] files = keyfilefolder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (!file.delete()) {
                        status = BeeConstants.ResponseStatus.FAIL;
                    }
                }
            }
        }
        return new QueryResult(status, "", null);
    }

    @Override
    public QueryResult getHexkey(String keyName, String userName) throws FileNotFoundException, IOException {
        logger.info("User is trying to get Hexkey string. userName:" + userName + ", keyName:" + keyName);
        File keyfile = new File(env.getProperty("keyfile.path") + keyName);
        if (!keyfile.exists()) {
            logger.info("keyName \"" + keyName + "\" not exist.");
            //return BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_NOT_FOUND);
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_NOT_FOUND), null);
        }

        Properties prop = new Properties();
        prop.load(new FileInputStream(keyfile));
        String owner = prop.getProperty("owner");
        String usersString = prop.getProperty("users");
        List<String> users = Arrays.asList(usersString.split(","));

        if (!owner.equals(userName) && !users.contains(userName)) {
            logger.info("You(" + userName + ") are not the owner of key(" + keyName + ").");
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_NOT_OWNER), null);
        }

        String hexkey = prop.getProperty("hexkey");
        if (hexkey == null || hexkey.isEmpty()) {
            logger.info("hexkey of key(" + keyName + ") is null in keyfile.");
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYFILE_INVALID), null);
        }

        return new QueryResult(BeeConstants.ResponseStatus.SUCCESS, prop.getProperty("hexkey"), null);
    }

    @Override
    public QueryResult queryKeyInfo(String keyName, String userName) throws FileNotFoundException, IOException {
        logger.info("User is trying to get key Info. userName:" + userName + ", keyName:" + keyName);
        File keyfile = new File(env.getProperty("keyfile.path") + keyName);
        if (!keyfile.exists()) {
            logger.info("keyName \"" + keyName + "\" not exist.");
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_NOT_FOUND), null);
        }

        Properties prop = new Properties();
        prop.load(new FileInputStream(keyfile));
        String owner = prop.getProperty("owner");

        if (!owner.equals(userName)) {
            logger.info("You(" + userName + ") are not the owner of key(" + keyName + ").");
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_NOT_OWNER), null);
        }

        return new QueryResult(BeeConstants.ResponseStatus.SUCCESS, "", prop);
    }

    @Override
    public QueryResult createKey(Param param, String owner)
            throws NoSuchAlgorithmException, FileNotFoundException, IOException {
        logger.info("User is trying to create key. userName:" + owner + ", keyName:" + param.getKeyName());
        File newKeyfile = new File(env.getProperty("keyfile.path") + param.getKeyName());
        if (newKeyfile.exists()) {
            logger.info("keyName \"" + param.getKeyName() + "\" exists, please choose another keyName.");
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_EXISTS), null);
        }

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);
        SecretKey secretKey = keyGen.generateKey();
        String hexkey = Hex.encodeHexString(secretKey.getEncoded());

        Properties prop = new Properties();
        prop.setProperty("owner", owner);
        prop.setProperty("keyName", param.getKeyName());
        prop.setProperty("hexkey", hexkey);
        prop.setProperty("users", param.getUsers());

        File keyFileFolder = new File(env.getProperty("keyfile.path"));
        if (!keyFileFolder.exists()) {
            keyFileFolder.mkdirs();
            Runtime.getRuntime().exec("chmod 700 " + env.getProperty("keyfile.path"));
        }
        prop.store(new FileOutputStream(env.getProperty("keyfile.path") + param.getKeyName()), null);
        Runtime.getRuntime().exec("chmod 600 " + env.getProperty("keyfile.path") + param.getKeyName());
        logger.info("save keyfile \"{}\" to keyfile folder: {}", param.getKeyName(),
                env.getProperty("keyfile.path"));

        return new QueryResult(BeeConstants.ResponseStatus.SUCCESS, "Key(" + param.getKeyName() + ") created",
                null);
    }

    @Override
    public QueryResult deleteKey(String keyName, String userName) throws FileNotFoundException, IOException {
        logger.info("User is trying to delete key. userName:" + userName + ", keyName:" + keyName);
        File keyfile = new File(env.getProperty("keyfile.path") + keyName);
        if (!keyfile.exists()) {
            logger.info("keyName \"" + keyName + "\" not exist.");
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_NOT_FOUND), null);
        }

        Properties prop = new Properties();
        prop.load(new FileInputStream(keyfile));
        String owner = prop.getProperty("owner");

        if (!owner.equals(userName)) {
            logger.info("You(" + userName + ") are not the owner of key(" + keyName + ").");
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_NOT_OWNER), null);
        }

        if (keyfile.delete()) {
            return new QueryResult(BeeConstants.ResponseStatus.SUCCESS, "Key(" + keyName + ") deleted", null);
        } else {
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEY_NOT_DELETED), null);
        }
    }

    @Override
    public QueryResult updateKeyUsers(Param param, String userName) throws FileNotFoundException, IOException {
        logger.info("User is trying to update key users. userName:" + userName + ", keyName:" + param.getKeyName());
        File keyfile = new File(env.getProperty("keyfile.path") + param.getKeyName());
        if (!keyfile.exists()) {
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_NOT_FOUND), null);
        }

        Properties prop = new Properties();
        prop.load(new FileInputStream(keyfile));
        String owner = prop.getProperty("owner");

        if (!owner.equals(userName)) {
            logger.info("You(" + userName + ") are not the owner of key(" + param.getKeyName() + ").");
            return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_NOT_OWNER), null);
        }

        prop.setProperty("users", param.getUsers());
        prop.store(new FileOutputStream(env.getProperty("keyfile.path") + param.getKeyName()), null);
        logger.info("update keyfile \"{}\" of keyfile folder: {}", param.getKeyName(),
                env.getProperty("keyfile.path"));

        return new QueryResult(BeeConstants.ResponseStatus.SUCCESS,
                "User of Key(" + param.getKeyName() + ") updated", null);
    }
}