|
| 1 | +/* |
| 2 | + * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. |
| 3 | + * <p> |
| 4 | + * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * <p> |
| 8 | + * http://www.gnu.org/licenses/lgpl.html |
| 9 | + * <p> |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package top.continew.starter.security.crypto.encryptor; |
| 18 | + |
| 19 | +import cn.hutool.extra.spring.SpringUtil; |
| 20 | +import org.springframework.security.crypto.password.PasswordEncoder; |
| 21 | +import top.continew.starter.security.crypto.autoconfigure.CryptoContext; |
| 22 | +import top.continew.starter.security.password.autoconfigure.PasswordEncoderProperties; |
| 23 | + |
| 24 | +/** |
| 25 | + * 密码编码器加/解密处理器 |
| 26 | + * |
| 27 | + * <p> |
| 28 | + * 使用前必须注入 {@link PasswordEncoder},此加密方式不可逆,适合于密码场景 |
| 29 | + * </p> |
| 30 | + * |
| 31 | + * @see PasswordEncoder |
| 32 | + * @see PasswordEncoderProperties |
| 33 | + * |
| 34 | + * @author Charles7c |
| 35 | + * @since 2.13.3 |
| 36 | + */ |
| 37 | +public class PasswordEncoderEncryptor extends AbstractEncryptor { |
| 38 | + |
| 39 | + private final PasswordEncoder passwordEncoder = SpringUtil.getBean(PasswordEncoder.class); |
| 40 | + private final PasswordEncoderProperties properties = SpringUtil.getBean(PasswordEncoderProperties.class); |
| 41 | + |
| 42 | + public PasswordEncoderEncryptor(CryptoContext context) { |
| 43 | + super(context); |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public String encrypt(String plaintext) { |
| 48 | + // 如果已经是加密格式,直接返回 |
| 49 | + if (properties.getAlgorithm().getPattern().matcher(plaintext).matches()) { |
| 50 | + return plaintext; |
| 51 | + } |
| 52 | + return passwordEncoder.encode(plaintext); |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + public String decrypt(String ciphertext) { |
| 57 | + return ciphertext; |
| 58 | + } |
| 59 | +} |
0 commit comments