org.iavante.sling.commons.services.impl.EncryptionServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for org.iavante.sling.commons.services.impl.EncryptionServiceImpl.java

Source

/*
 * Digital Assets Management
 * =========================
 * 
 * Copyright 2009 Fundacin Iavante
 * 
 * Authors: 
 *   Francisco Jos Moreno Llorca <packo@assamita.net>
 *   Francisco Jess Gonzlez Mata <chuspb@gmail.com>
 *   Juan Antonio Guzmn Hidalgo <juan@guzmanhidalgo.com>
 *   Daniel de la Cuesta Navarrete <cues7a@gmail.com>
 *   Manuel Jos Cobo Fernndez <ranrrias@gmail.com>
 *
 * Licensed under the EUPL, Version 1.1 or  as soon they will be approved by
 * the European Commission - subsequent versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://ec.europa.eu/idabc/eupl
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and 
 * limitations under the Licence.
 * 
 */

package org.iavante.sling.commons.services.impl;

import java.io.Serializable;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.KeyPairGenerator;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

import org.iavante.sling.commons.services.EncryptionService;
import org.iavante.sling.commons.services.PortalSetup;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class for encrypt and decrypt strings with RSA.
 * 
 * @scr.component
 * @scr.property name="service.description"
 *               value="IAVANTE - Encryption Service Impl"
 * @scr.property name="service.vendor" value="IAVANTE Foundation"
 * @scr.service interface="org.iavante.sling.commons.services.EncryptionService"
 */
public class EncryptionServiceImpl implements EncryptionService, Serializable {
    private static final long serialVersionUID = 1L;

    /** Key Pair */
    private KeyPair keyPair;

    /** Logger */
    private Logger log;

    /** @scr.reference */
    private PortalSetup portalSetup;

    /** RSA key size */
    private int defaultRsaKeySize = 2048;

    /** Encoding */
    private String defaultEncoding = "UTF-8";

    /** Internal properties */
    private Map<String, String> properties;

    /**
     * Load default properties from global configuration
     * 
     * @param context
     *          Component context
     */
    protected void activate(ComponentContext context) {
        this.properties = this.portalSetup.get_config_properties("/encryption");
        defaultRsaKeySize = new Integer(this.properties.get("default_rsa_key_size")).intValue();
        defaultEncoding = this.properties.get("default_encoding");
    }

    /**
     * Default constructor, generates a RSA KeyPair with default size
     */
    public EncryptionServiceImpl() {
        initialize();
    }

    /**
     * Initialize log and Key_Pair
     */
    private void initialize() {
        log = LoggerFactory.getLogger(getClass());
        if (log.isInfoEnabled())
            log.info("Encryption Object: " + this.toString());
        try {
            makeKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public int getRSA_Key_Size() {
        return defaultRsaKeySize;
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public PublicKey getPublicKey() {
        return keyPair.getPublic();
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String getPublicKeyAsString(String encoding) throws Exception {
        String encodingAux = defaultEncoding;
        if (encoding != null) {
            encodingAux = encoding;
        }
        return java.net.URLEncoder.encode(new String(Base64.encodeBase64(keyPair.getPublic().getEncoded())),
                encodingAux);
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String getEncoding() {
        return defaultEncoding;
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String encryptMessage(String message) throws Exception {
        return encryptMessage(message, getPublicKey(), defaultEncoding);
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String encryptMessage(String message, PublicKey key) throws Exception {
        return encryptMessage(message, key, defaultEncoding);
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String encryptMessage(String message, PublicKey key, String encoding) throws Exception {
        byte[] encryptedMessage;
        // Get an instance of the Cipher for RSA encryption/decryption
        Cipher c = Cipher.getInstance("RSA");
        // Initiate the Cipher, telling it that it is going to Encrypt, giving
        // it the public key
        c.init(Cipher.ENCRYPT_MODE, key);
        encryptedMessage = c.doFinal(message.getBytes(defaultEncoding));
        return java.net.URLEncoder.encode(new String(Base64.encodeBase64(encryptedMessage)), encoding);
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String encryptMessage(String message, String key) throws Exception {
        return encryptMessage(message, key, defaultEncoding);
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String encryptMessage(String message, String key, String encoding) throws Exception {
        String urlDecodedKey;
        byte[] encryptedMessage;
        urlDecodedKey = java.net.URLDecoder.decode(key, encoding);
        // Generate the public key from a String
        PublicKey pk = (PublicKey) KeyFactory.getInstance("RSA").generatePublic(
                new X509EncodedKeySpec(Base64.decodeBase64(urlDecodedKey.getBytes(defaultEncoding))));
        // Get an instance of the Cipher for RSA encryption/decryption
        Cipher c = Cipher.getInstance("RSA");
        // Initiate the Cipher, telling it that it is going to Encrypt, giving
        // it the public key
        c.init(Cipher.ENCRYPT_MODE, pk);
        // c.init(Cipher.ENCRYPT_MODE, extractInfo(key));
        encryptedMessage = c.doFinal(message.getBytes(defaultEncoding));
        return java.net.URLEncoder.encode(new String(Base64.encodeBase64(encryptedMessage)), encoding);
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String decryptMessage(String message) throws Exception {
        return decryptMessage(message, defaultEncoding);
    }

    /*
     * @see org.iavante.sling.commons.services.EncryptionService
     */
    public String decryptMessage(String message, String encoding) throws Exception {
        String urlDecodedMessage;
        byte[] decryptedMessage;
        urlDecodedMessage = java.net.URLDecoder.decode(message, encoding);
        // Get an instance of the Cipher for RSA encryption/decryption
        Cipher c = Cipher.getInstance("RSA");
        // Initiate the Cipher, telling it that it is going to Decrypt, giving
        // it the private key
        c.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
        decryptedMessage = c.doFinal(Base64.decodeBase64(urlDecodedMessage.getBytes(defaultEncoding)));
        return new String(decryptedMessage);
    }

    // --------------------- Internal ---------------------------
    /**
     * Make a keypair (public for encryption and private for decrypt) with
     * RSA_KeySize bits size
     * 
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    private void makeKey() throws NoSuchAlgorithmException, NoSuchProviderException {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        // Initialize the Key-Pair Generator
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        kpg.initialize(defaultRsaKeySize, random);
        keyPair = kpg.generateKeyPair();
    }

}