org.apigw.commons.crypto.Encrypter.java Source code

Java tutorial

Introduction

Here is the source code for org.apigw.commons.crypto.Encrypter.java

Source

/**
 *   Copyright 2013 Stockholm County Council
 *
 *   This file is part of APIGW
 *
 *   APIGW is free software; you can redistribute it and/or modify
 *   it under the terms of version 2.1 of the GNU Lesser General Public
 *   License as published by the Free Software Foundation.
 *
 *   APIGW is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with APIGW; if not, write to the
 *   Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 *   Boston, MA 02111-1307  USA
 *
 */
package org.apigw.commons.crypto;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Encrypt strings with a public key
 * 
 * @author albert
 *
 */
@Component
public class Encrypter extends ApigwCrypto {

    public Encrypter() {
        log = LoggerFactory.getLogger(Encrypter.class);
    }

    /**
     * 
     * @param message A string to encrypt
     * @return An encrypted (AES) and base64 encoded string
     * @throws java.lang.RuntimeException
     */
    public String encrypt(String message) throws RuntimeException {
        log.debug("About to encrypt a message");
        if (message == null) {
            log.trace("incoming message is null, returning null");
            return null;
        }
        if (useEncryption) {
            try {
                SecretKeySpec skeySpec = getSecretKeySpec();
                IvParameterSpec ivParameterSpec = getIvParameterSpec();
                Cipher encryptCipher = getCipher();
                encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
                byte[] encrypted = encryptCipher.doFinal(message.getBytes("utf8"));
                final String encryptedMessage = new String(Base64.encodeBase64(encrypted), "utf8");
                log.debug("Message encrypted: {}", encryptedMessage);
                return encryptedMessage;
            } catch (Exception e) {
                log.error("Caught an error while encrypting", e);
                throw new RuntimeException(e);
            }
        } else {
            log.debug("Encryption is disabled, will not encrypt message");
            return message;
        }
    }

}