Java tutorial
/** * 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; /** * Decrypt strings with a private key. * * @author albert * */ @Component public class Decrypter extends ApigwCrypto { public Decrypter() { log = LoggerFactory.getLogger(Decrypter.class); } /** * * @param encrypted An AES encrypted and Base64 encoded string * @return * @throws java.lang.RuntimeException */ public String decrypt(String encrypted) throws RuntimeException { log.debug("About to decrypt the string: {}", encrypted); if (encrypted == null) { log.trace("incoming message is null, returning null"); return null; } if (useEncryption) { try { byte[] encryptedBytes = Base64.decodeBase64(encrypted.getBytes("utf8")); SecretKeySpec skeySpec = getSecretKeySpec(); IvParameterSpec ivParameterSpec = getIvParameterSpec(); Cipher decryptCipher = getCipher(); decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec); byte[] decrypted = decryptCipher.doFinal(encryptedBytes); log.debug("Message decrypted."); return new String(decrypted, "utf8"); } catch (Exception e) { log.error("Caught an error while decrypting", e); throw new RuntimeException(e); } } else { log.debug("Encryption is disabled, will not decrypt message"); return encrypted; } } }