ZEncryptionServiceImpl.java :  » Web-Framework » ztemplates » org » ztemplates » web » impl » Java Open Source

Java Open Source » Web Framework » ztemplates 
ztemplates » org » ztemplates » web » impl » ZEncryptionServiceImpl.java
/*
 * Copyright 2007 Gerd Ziegler (www.gerdziegler.de)
 * 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.
 * 07.01.2007
 * @author www.gerdziegler.de
 */
package org.ztemplates.web.impl;

import javax.servlet.ServletContext;

import org.ztemplates.actions.util.ZEncrypter;
import org.ztemplates.web.ZIEncryptionService;
import org.ztemplates.web.ZIServiceRepository;

public class ZEncryptionServiceImpl implements ZIEncryptionService
{
  private static final String ENCRYPT_PASSWORD_PARAM = "encryptPassword";

  private static final String ENCRYPT_SALT_PARAM = "encryptSalt";

  private byte[] salt;

  private String password;

  private ZEncrypter encrypter;


  public void init(ZIServiceRepository serviceRepository) throws Exception
  {
    final ServletContext servletContext = serviceRepository.getServletContext();
    password = servletContext.getInitParameter(ENCRYPT_PASSWORD_PARAM);
    String hex = servletContext.getInitParameter(ENCRYPT_SALT_PARAM);
    if (hex != null)
    {
      hex = hex.trim().toLowerCase();
      if (hex.length() != 16)
      {
        throw new RuntimeException(ENCRYPT_SALT_PARAM + " in web.xml must have length 16 and contain only the hex characters 0-1 and a-f");
      }

      salt = new byte[hex.length() / 2];
      for (int i = 0; i < salt.length; i++)
      {
        salt[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
      }
    }
    encrypter = new ZEncrypter(salt, password);
  }


  public String decrypt(String s) throws Exception
  {
    String ret = encrypter.decrypt(s);
    return ret;
  }


  public String encrypt(String s) throws Exception
  {
    String ret = encrypter.encrypt(s);
    return ret;
  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.