功能模块实战之发送验证注册信息的邮件

内容一:直接使用前面篇章抽象出来的MailService!~即类.方法 调用即可

内容二:邮件中用于验证注册合法性的链接中涉及的相关信息应当属于私密信息,故而应当对其加密传输。

AES和DES辅助类EncryptUtil.java


import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Map;

/**
 * 通用的AES加密解密工具
 */
public class EncryptUtil {

    private static final String AES_ALG         = "AES";

    private static final String charset         = "utf-8";

    //AES算法
    private static final String AES_CBC_PCK_ALG = "AES/CBC/PKCS5Padding";

    private static final byte[] AES_IV          = initIv(AES_CBC_PCK_ALG);

    /**
     * 加密
     * @param content
     * @param encryptType
     * @param encryptKey
     * @param charset
     * @return
     * @throws Exception
     */
    public static String encryptContent(String content, String encryptType, String encryptKey,String charset) throws Exception {
        if (AES_ALG.equals(encryptType)) {
            return aesEncrypt(content, encryptKey);
        } else {
            throw new Exception("当前不支持该算法类型:encrypeType=" + encryptType);
        }

    }

    /**
     * 解密
     * @param content
     * @param encryptType
     * @param encryptKey
     * @param charset
     * @return
     * @throws Exception
     */
    public static String decryptContent(String content, String encryptType, String encryptKey,String charset) throws Exception {
        if (AES_ALG.equals(encryptType)) {
            return aesDecrypt(content, encryptKey);
        } else {
            throw new Exception("当前不支持该算法类型:encrypeType=" + encryptType);
        }

    }

    /**
     * AES加密
     * @param content
     * @param aesKey
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content, String aesKey)throws Exception {
        try {
            Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);

            IvParameterSpec iv = new IvParameterSpec(AES_IV);
            cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(aesKey.getBytes(), AES_ALG), iv);

            byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
            return new String(Base64.encodeBase64(encryptBytes));
        } catch (Exception e) {
            throw new Exception("AES加密失败:Aescontent = " + content + "; charset = " + charset, e);
        }
    }

    /**
     * AES解密
     * @param content 待解密串
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String content, String key)throws Exception {
        try {
            Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);
            IvParameterSpec iv = new IvParameterSpec(initIv(AES_CBC_PCK_ALG));
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(),
                    AES_ALG), iv);

            byte[] cleanBytes = cipher.doFinal(Base64.decodeBase64(content.getBytes()));
            return new String(cleanBytes, charset);
        } catch (Exception e) {
            throw new Exception("AES解密失败:Aescontent = " + content + "; charset = " + charset, e);
        }
    }

    /**
     * 初始向量的方法, 全部为0. 这里的写法适合于其它算法,针对AES算法的话,IV值一定是128位的(16字节).
     * @param fullAlg
     * @return
     * @throws GeneralSecurityException
     */
    private static byte[] initIv(String fullAlg) {
        try {
            Cipher cipher = Cipher.getInstance(fullAlg);
            int blockSize = cipher.getBlockSize();
            byte[] iv = new byte[blockSize];
            for (int i = 0; i < blockSize; ++i) {
                iv[i] = 0;
            }
            return iv;
        } catch (Exception e) {

            int blockSize = 16;
            byte[] iv = new byte[blockSize];
            for (int i = 0; i < blockSize; ++i) {
                iv[i] = 0;
            }
            return iv;
        }
    }

}
application.properties中(给定激活邮箱的主题,渲染模板的名称,以及激活链接的前置参数)
#用户注册模块
user.register.email.subject=欢迎注册-CSDN博客论坛
user.register.email.temp.file=mailTempRegister.ftl
user.register.email.validate.url=${project.domain.url.root}/user/validate?params=%s
encrypt.aes.alg.key=e2bd6cee47e0402db80862a09ff4d126
user.register.email.time=3600000
UsrService.java
    //用户注册
    @Transactional(rollbackFor = Exception.class)
    public void register(UsrDto usrDto) throws  Exception{
        //TODO:检查该邮箱账户是否已经存在
        if(usrMapper.countByEmail(usrDto.getEmail()) > 0){
            throw new RuntimeException("该邮箱账户已经存在,请进行更换!");
        }
        //TODO: 保存用户注册信息
        Usr entity = new Usr();
        BeanUtils.copyProperties(usrDto, entity);

        usrMapper.insertSelective(entity);
        Integer usrId = entity.getId();

        //TODO:发送一封邮件到用户注册的邮箱

        MailDto mailDto = new MailDto();
        mailDto.setSubject(env.getProperty("user.register.email.subject"));
        mailDto.setTos(new String[]{usrDto.getEmail()});

        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("mailTos", usrDto.getEmail());

        String encryptInfo = env.getProperty("user.register.email.validate.url");
        encryptInfo = String.format(encryptInfo, getEncryptValue(usrDto));
        dataMap.put("validateUrl", encryptInfo);

        int send = mailService.sendHTMLTemplateMailV2(mailDto, env.getProperty("user.register.email.temp.file"), dataMap);

        if(1 == send){
            MailEncrypt encrypt = new MailEncrypt(usrId, usrDto.getEmail(), encryptValue, DateTime.now().toDate());
            mailEncryptMapper.insertSelective(encrypt);
            System.out.println(" mailEncryptMapper.insertSelective(encrypt);");
        }
    }

    //根据用户信息获取加密后的字符串
    private String getEncryptValue(UsrDto dto) throws Exception{
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("name", dto.getName());
        dataMap.put("email",  dto.getEmail());
        dataMap.put("sendTime", DateTime.now().toDate());
        dataMap.put("nonceStr", RandomStringUtils.randomAlphabetic(10).toLowerCase());

        String tempStr = objectMapper.writeValueAsString(dataMap);
        return EncryptUtil.aesEncrypt(tempStr, env.getProperty("encrypt.aes.alg.key"));
    }

UserController.java

    @RequestMapping(value = "register", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public BaseResponse register(@RequestBody @Validated UsrDto usrDto, BindingResult result){
        String checkRes = ValidatorUtil.checkResult(result);
        if(StringUtils.isNotBlank(checkRes)){
            return new BaseResponse(StatusCode.InvalidParam.getCode(), checkRes);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try{
            usrService.register(usrDto);
            String res = String.format("用户注册成功,请前往注册的邮箱: %s 激活该账号!", usrDto.getEmail());
            response.setData(res);
        }catch (Exception e){
            log.info("用户Controller-用户注册-发生异常");
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }

结果 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值