001/* 002 * HA-JDBC: High-Availability JDBC 003 * Copyright (C) 2012 Paul Ferraro 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Lesser General Public License as published by 007 * the Free Software Foundation, either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018package net.sf.hajdbc.codec.crypto; 019 020import java.security.GeneralSecurityException; 021import java.security.Key; 022import java.sql.SQLException; 023 024import javax.crypto.Cipher; 025 026import net.sf.hajdbc.codec.Codec; 027 028import org.apache.commons.codec.binary.Base64; 029 030/** 031 * Generic cryptographic codec. 032 * @author Paul Ferraro 033 */ 034public class CipherCodec implements Codec 035{ 036 private final Key key; 037 038 public CipherCodec(Key key) 039 { 040 this.key = key; 041 } 042 043 public Key getKey() 044 { 045 return this.key; 046 } 047 048 /** 049 * {@inheritDoc} 050 * @see net.sf.hajdbc.codec.Codec#decode(java.lang.String) 051 */ 052 @Override 053 public String decode(String value) throws SQLException 054 { 055 try 056 { 057 Cipher cipher = Cipher.getInstance(this.key.getAlgorithm()); 058 059 cipher.init(Cipher.DECRYPT_MODE, this.key); 060 061 return new String(cipher.doFinal(Base64.decodeBase64(value.getBytes()))); 062 } 063 catch (GeneralSecurityException e) 064 { 065 throw new SQLException(e); 066 } 067 } 068 069 /** 070 * {@inheritDoc} 071 * @see net.sf.hajdbc.codec.Codec#encode(java.lang.String) 072 */ 073 @Override 074 public String encode(String value) throws SQLException 075 { 076 try 077 { 078 Cipher cipher = Cipher.getInstance(this.key.getAlgorithm()); 079 080 cipher.init(Cipher.ENCRYPT_MODE, this.key); 081 082 return new String(Base64.encodeBase64(cipher.doFinal(value.getBytes()))); 083 } 084 catch (GeneralSecurityException e) 085 { 086 throw new SQLException(e); 087 } 088 } 089}