Java tutorial
/* * Copyright (C) 2016 Adam Huang <poisondog@gmail.com> * * 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. */ package poisondog.security; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import poisondog.core.Mission; /** * @author Adam Huang <poisondog@gmail.com> */ public class DecryptMission implements Mission<String> { private String mKey; private String mAlgorithm; public DecryptMission(String key) { this(key, "AES"); } public DecryptMission(String key, String algorrithm) { mKey = key; mAlgorithm = algorrithm; } @Override public String execute(String input) throws NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec skeySpec = new SecretKeySpec(mKey.getBytes(), mAlgorithm); try { Cipher cipher = Cipher.getInstance(mAlgorithm); byte[] decode = Base64.decodeBase64(input); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] original = cipher.doFinal(decode); return new String(original); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } }