001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket.core.util.crypt; 018 019import org.apache.wicket.util.crypt.ICrypt; 020import org.slf4j.Logger; 021import org.slf4j.LoggerFactory; 022 023import java.nio.charset.StandardCharsets; 024import java.security.GeneralSecurityException; 025import java.util.Base64; 026 027 028/** 029 * Base class for JCE based ICrypt implementations. 030 * 031 */ 032public abstract class AbstractJceCrypt implements ICrypt 033{ 034 /** Log. */ 035 private static final Logger log = LoggerFactory.getLogger(AbstractJceCrypt.class); 036 037 /** 038 * Decrypts a string into a string. 039 * 040 * @param text 041 * text to decrypt 042 * @return the decrypted text 043 */ 044 @Override 045 public final String decryptUrlSafe(final String text) 046 { 047 try 048 { 049 byte[] decoded = java.util.Base64.getUrlDecoder().decode(text); 050 return new String(decrypt(decoded), StandardCharsets.UTF_8); 051 } 052 catch (Exception ex) 053 { 054 log.debug("Error decoding text: {}", text, ex); 055 return null; 056 } 057 } 058 059 /** 060 * Encrypt a string into a string using URL safe Base64 encoding. 061 * 062 * @param plainText 063 * text to encrypt 064 * @return encrypted string 065 */ 066 @Override 067 public final String encryptUrlSafe(final String plainText) 068 { 069 byte[] encrypted = encrypt(plainText.getBytes(StandardCharsets.UTF_8)); 070 Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); 071 byte[] encoded = encoder.encode(encrypted); 072 return new String(encoded, StandardCharsets.UTF_8); 073 } 074 075 /** 076 * Decrypts an encrypted byte array. 077 * 078 * @param encrypted 079 * byte array to decrypt 080 * @return the decrypted text 081 */ 082 abstract protected byte[] decrypt(final byte[] encrypted); 083 084 085 /** 086 * Encrypts the given text into a byte array. 087 * 088 * @param plainBytes 089 * text to encrypt 090 * @return the string encrypted 091 */ 092 abstract protected byte[] encrypt(final byte[] plainBytes); 093 094 095 @Override 096 public final void setKey(String key) 097 { 098 throw new UnsupportedOperationException("This method has been deprecated in ICrypt and will be removed."); 099 } 100}