项目中 加密解密某些字段的问题汇总

来源:互联网 发布:黑巧克力 减肥 数据 编辑:程序博客网 时间:2024/05/23 00:07


最近在项目中用RSA给  数据库中某些字段加密解密,在测试 过程中   遇到几个问题 ,后来不断修改,特此记录。在项目中数据库用户表有些需要 加密的字段 

       如下代码      身份证号   护照号      银行卡号  需要加密。


一、刚开始打算在需要加密的字段 set方法里面加密,插入数据库,在get方法   返回解密后的字段     但是 代码写完之后,项目运行之后发现   数据库中的字段

      并没有加密       经过debug发现,  执行完set方法后  在插入数据库数据之前   会调用该字段的get方法 获取数据  插入数据库    这样加密后的数据   就这样

      在get方法里 解密后   插入 了数据库 ,   所以    只能再额外加   实体类中的属性      将 插入数据库用 的set方法    和   获取数据库中数据  get方法 

      分离,用两个  不同的属性来 对数据库中 同一 字段 进行 加密   解密 操作    代码如下

package com.jeeplus.modules.sys.entity;import java.util.Date;import java.util.List;import javax.validation.constraints.NotNull;import org.hibernate.validator.constraints.Email;import org.hibernate.validator.constraints.Length;import com.fasterxml.jackson.annotation.JsonFormat;import com.fasterxml.jackson.annotation.JsonIgnore;import com.google.common.collect.Lists;import com.jeeplus.common.config.Global;import com.jeeplus.common.persistence.DataEntity;import com.jeeplus.common.utils.Collections3;import com.jeeplus.common.utils.excel.annotation.ExcelField;import com.jeeplus.common.utils.excel.fieldtype.RoleListType;import com.jeeplus.common.utils.rsa.SecretUtils;/** * 用户Entity * @author jeeplus * @version 2013-12-05 */public class User extends DataEntity<User> {private static final long serialVersionUID = 1L;private Office company;// 归属公司private Office office;// 归属部门private String loginName;// 登录名private String password;// 密码private String no;// 员工编号private String name;// 姓名private String email;// 邮箱private String phone;// 电话private String mobile;// 手机private String userType;// 用户类型private String loginIp;// 最后登陆IPprivate Date loginDate;// 最后登陆日期private String loginFlag;// 是否允许登陆private String photo;// 头像private String qrCode;//二维码private String oldLoginName;// 原登录名private String newPassword;// 新密码private String sign;//签名private Date entryDate;// 入职日private Date regularDate;// 转正日期private Integer level;// 职务private Integer gender;// 性别private Integer old;// 年龄private String birthday;// 出生日期private Integer marriage;// 婚姻状况private String identity;// 身份证号private String encryptIdentity;// 加密身份证号private String graduateSchool;// 毕业院校private String specialty;// 专业private String education;// 学历private String address;// 住址private Date insuranceDate;// 加入社保月份private String insuranceNo;// 社保号private String accumulationNo;// 公积金号private String passportNo;// 护照号private String encryptPassportNo;// 加密护照号private String passportIssue;// 护照签发地private String passportValidityDate;// 护照有效期private String qualiCert;// 资格认证private String bankNo;// 银行卡号private String encryptBankNo;// 加密银行卡号private String accessNo;// 门禁卡尾号private Integer status;// 状态private Date quitDate;// 离职日private String quitReason;// 离职原因private String quitGo;// 离职去向private Integer personType;   //人员种类private String oldLoginIp;// 上次登陆IPprivate Date oldLoginDate;// 上次登陆日期private Role role;// 根据角色查询用户条件private List<Role> roleList = Lists.newArrayList(); // 拥有角色列表public User() {super();this.loginFlag = Global.YES;}public User(String id){super(id);}public User(String id, String loginName){super(id);this.loginName = loginName;}public User(Role role){super();this.role = role;}public String getPhoto() {return photo;}public void setPhoto(String photo) {this.photo = photo;}public String getLoginFlag() {return loginFlag;}public void setLoginFlag(String loginFlag) {this.loginFlag = loginFlag;}public String getId() {return id;}@JsonIgnore@NotNull(message="归属公司不能为空")@ExcelField(title="归属公司", align=2, sort=20)public Office getCompany() {return company;}public void setCompany(Office company) {this.company = company;}@JsonIgnore@NotNull(message="归属部门不能为空")@ExcelField(title="归属部门", align=2, sort=25)public Office getOffice() {return office;}public void setOffice(Office office) {this.office = office;}@NotNull(message="登录名不能为空")@Length(min=1, max=100, message="登录名长度必须介于 1 和 100 之间")@ExcelField(title="登录名", align=2, sort=30)public String getLoginName() {return loginName;}public void setLoginName(String loginName) {this.loginName = loginName;}@JsonIgnore@Length(min=1, max=100, message="密码长度必须介于 1 和 100 之间")public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@NotNull(message="姓名不能为空")@ExcelField(title="姓名", align=2, sort=40)public String getName() {return name;}public void setName(String name) {this.name = name;}@NotNull(message="工号不能为空")@Length(min=1, max=100, message="工号长度必须介于 1 和 100 之间")@ExcelField(title="工号", align=2, sort=45)public String getNo() {return no;}public void setNo(String no) {this.no = no;}@Email(message="邮箱格式不正确")@Length(min=0, max=200, message="邮箱长度必须介于 1 和 200 之间")@ExcelField(title="邮箱", align=1, sort=50)public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Length(min=0, max=200, message="电话长度必须介于 1 和 200 之间")@ExcelField(title="电话", align=2, sort=60)public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@NotNull(message="手机不能为空")@ExcelField(title="手机", align=2, sort=70)public String getMobile() {return mobile;}public void setMobile(String mobile) {this.mobile = mobile;}@ExcelField(title="备注", align=1, sort=900)public String getRemarks() {return remarks;}@NotNull(message="用户类型不能为空")@Length(min=0, max=100, message="用户类型长度必须介于 1 和 100 之间")@ExcelField(title="用户类型", align=2, sort=80, dictType="sys_user_type")public String getUserType() {return userType;}public void setUserType(String userType) {this.userType = userType;}@ExcelField(title="创建时间", type=0, align=1, sort=700)public Date getCreateDate() {return createDate;}@ExcelField(title="最后登录IP", type=1, align=1, sort=710)public String getLoginIp() {return loginIp;}public void setLoginIp(String loginIp) {this.loginIp = loginIp;}@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")@ExcelField(title="最后登录日期", type=1, align=1, sort=720)public Date getLoginDate() {return loginDate;}public void setLoginDate(Date loginDate) {this.loginDate = loginDate;}public String getOldLoginName() {return oldLoginName;}public void setOldLoginName(String oldLoginName) {this.oldLoginName = oldLoginName;}public String getNewPassword() {return newPassword;}public void setNewPassword(String newPassword) {this.newPassword = newPassword;}public String getOldLoginIp() {if (oldLoginIp == null){return loginIp;}return oldLoginIp;}public void setOldLoginIp(String oldLoginIp) {this.oldLoginIp = oldLoginIp;}@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")public Date getOldLoginDate() {if (oldLoginDate == null){return loginDate;}return oldLoginDate;}public void setOldLoginDate(Date oldLoginDate) {this.oldLoginDate = oldLoginDate;}public Role getRole() {return role;}public void setRole(Role role) {this.role = role;}@JsonIgnore@ExcelField(title="用户角色", align=1, sort=800, fieldType=RoleListType.class)public List<Role> getRoleList() {return roleList;}public void setRoleList(List<Role> roleList) {this.roleList = roleList;}@JsonIgnorepublic List<String> getRoleIdList() {List<String> roleIdList = Lists.newArrayList();for (Role role : roleList) {roleIdList.add(role.getId());}return roleIdList;}public void setRoleIdList(List<String> roleIdList) {roleList = Lists.newArrayList();for (String roleId : roleIdList) {Role role = new Role();role.setId(roleId);roleList.add(role);}}/** * 用户拥有的角色名称字符串, 多个角色名称用','分隔. */public String getRoleNames() {return Collections3.extractToString(roleList, "name", ",");}public boolean isAdmin(){return isAdmin(this.id);}public static boolean isAdmin(String id){return id != null && "1".equals(id);}@Overridepublic String toString() {return id;}public void setQrCode(String qrCode) {this.qrCode = qrCode;}public String getQrCode() {return qrCode;}/** * @param sign the sign to set */public void setSign(String sign) {this.sign = sign;}/** * @return the sign */public String getSign() {return sign;}@JsonFormat(pattern = "yyyy-MM-dd")@NotNull(message="入职日不能为空")@ExcelField(title="入职日", align=2, sort=100)public Date getEntryDate() {return entryDate;}public void setEntryDate(Date entryDate) {this.entryDate = entryDate;}@JsonFormat(pattern = "yyyy-MM-dd")@ExcelField(title="转正日期", align=2, sort=101)public Date getRegularDate() {return regularDate;}public void setRegularDate(Date regularDate) {this.regularDate = regularDate;}@NotNull(message="职务不能为空")@ExcelField(title="职务", dictType="job", align=2, sort=102)public Integer getLevel() {return level;}public void setLevel(Integer level) {this.level = level;}@NotNull(message="性别不能为空")@ExcelField(title="性别", dictType="sex", align=2, sort=103)public Integer getGender() {return gender;}public void setGender(Integer gender) {this.gender = gender;}@NotNull(message="年龄不能为空")@ExcelField(title="年龄", align=2, sort=104)public Integer getOld() {return old;}public void setOld(Integer old) {this.old = old;}@ExcelField(title="出生日期", align=2, sort=105)public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}@NotNull(message="婚姻状况不能为空")@ExcelField(title="婚姻状况", dictType="marry", align=2, sort=106)public Integer getMarriage() {return marriage;}public void setMarriage(Integer marriage) {this.marriage = marriage;}@NotNull(message="身份证号不能为空")@ExcelField(title="身份证号", align=2, sort=107)public String getIdentity() {return SecretUtils.decrypt(identity);}public void setIdentity(String identity) {this.identity = identity;}@ExcelField(title="毕业院校", align=2, sort=108)public String getGraduateSchool() {return graduateSchool;}public void setGraduateSchool(String graduateSchool) {this.graduateSchool = graduateSchool;}@ExcelField(title="专业", align=2, sort=109)public String getSpecialty() {return specialty;}public void setSpecialty(String specialty) {this.specialty = specialty;}@ExcelField(title="学历", align=2, sort=110)public String getEducation() {return education;}public void setEducation(String education) {this.education = education;}@ExcelField(title="住址", align=2, sort=111)public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@JsonFormat(pattern = "yyyy-MM")@ExcelField(title="加入社保月份", align=2, sort=112)public Date getInsuranceDate() {return insuranceDate;}public void setInsuranceDate(Date insuranceDate) {this.insuranceDate = insuranceDate;}@ExcelField(title="社保号", align=2, sort=113)public String getInsuranceNo() {return insuranceNo;}public void setInsuranceNo(String insuranceNo) {this.insuranceNo = insuranceNo;}@ExcelField(title="公积金号", align=2, sort=114)public String getAccumulationNo() {return accumulationNo;}public void setAccumulationNo(String accumulationNo) {this.accumulationNo = accumulationNo;}@ExcelField(title="护照号", align=2, sort=115)public String getPassportNo() {return SecretUtils.decrypt(passportNo);}public void setPassportNo(String passportNo) {this.passportNo = passportNo;}@ExcelField(title="护照签发地", align=2, sort=116)public String getPassportIssue() {return passportIssue;}public void setPassportIssue(String passportIssue) {this.passportIssue = passportIssue;}@ExcelField(title="护照有效期", align=2, sort=117)public String getPassportValidityDate() {return passportValidityDate;}public void setPassportValidityDate(String passportValidityDate) {this.passportValidityDate = passportValidityDate;}@ExcelField(title="资格认证", align=2, sort=118)public String getQualiCert() {return qualiCert;}public void setQualiCert(String qualiCert) {this.qualiCert = qualiCert;}@ExcelField(title="银行卡号", align=2, sort=119)public String getBankNo() {return SecretUtils.decrypt(bankNo);}public void setBankNo(String bankNo) {this.bankNo = bankNo;}@ExcelField(title="门禁卡尾号", align=2, sort=120)public String getAccessNo() {return accessNo;}public void setAccessNo(String accessNo) {this.accessNo = accessNo;}@NotNull(message="状态不能为空")@ExcelField(title="状态", dictType="status", align=2, sort=121)public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}@JsonFormat(pattern = "yyyy-MM-dd")@ExcelField(title="离职日", align=2, sort=122)public Date getQuitDate() {return quitDate;}public void setQuitDate(Date quitDate) {this.quitDate = quitDate;}@ExcelField(title="离职原因", align=2, sort=123)public String getQuitReason() {return quitReason;}public void setQuitReason(String quitReason) {this.quitReason = quitReason;}@ExcelField(title="离职去向", align=2, sort=124)public String getQuitGo() {return quitGo;}public void setQuitGo(String quitGo) {this.quitGo = quitGo;}@NotNull(message="人员类别不能为空")@ExcelField(title="人员类别", dictType="personType", align=2, sort=125)public Integer getPersonType() {return personType;}public void setPersonType(Integer personType) {this.personType = personType;}//---------加密部分--------------//public String getEncryptIdentity() {return encryptIdentity;}public void setEncryptIdentity(String encryptIdentity) {this.encryptIdentity = encryptIdentity;}public String getEncryptPassportNo() {return encryptPassportNo;}public void setEncryptPassportNo(String encryptPassportNo) {this.encryptPassportNo = encryptPassportNo;}public String getEncryptBankNo() {return encryptBankNo;}public void setEncryptBankNo(String encryptBankNo) {this.encryptBankNo = encryptBankNo;}}

mybatis的xml文件 修改如下    将insert   和 update  的字段稍稍改动 即可

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.jeeplus.modules.sys.dao.UserDao"><!-- <resultMap id="userResult" type="User"><id property="id" column="id" /><result property="company.id" column="company.id" /><result property="office.id" column="office.id" /><result property="loginName" column="login_name" /><result property="password" column="password" /><result property="no" column="no" /><result property="name" column="name" /><result property="email" column="email" /><result property="phone" column="phone" /><result property="mobile" column="mobile" /><result property="userType" column="user_type" /><result property="loginIp" column="login_ip" /><result property="loginDate" column="login_date" /><result property="remarks" column="remarks" /><result property="loginFlag" column="loginFlag" /><result property="photo" column="photo" /><result property="createBy.id" column="createBy.id" /><result property="createDate" column="create_date" /><result property="updateBy.id" column="updateBy.id" /><result property="updateDate" column="update_date" /><result property="company.name" column="company.name" /><result property="company.parentId" column="company.parentId" /><result property="company.parentIds" column="company.parentIds" /><result property="company.area.id" column="company.area.id" /><result property="company.area.name" column="company.area.name" /><result property="company.area.parentId" column="company.area.parentId" /><result property="company.area.parentIds" column="company.area.parentIds" /><result property="company.primaryPerson.id" column="company.primaryPerson.id" /><result property="company.primaryPerson.name" column="company.primaryPerson.name" /><result property="company.deputyPerson.id" column="company.deputyPerson.id" /><result property="company.deputyPerson.name" column="company.deputyPerson.name" /><result property="office.name" column="office.name" /><result property="office.parentId" column="office.parentId" /><result property="office.parentIds" column="office.parentIds" /><result property="office.area.id" column="office.area.id" /><result property="office.area.name" column="office.area.name" /><result property="office.area.parentId" column="office.area.parentId" /><result property="office.area.parentIds" column="office.area.parentIds" /><result property="office.primaryPerson.id" column="office.primaryPerson.id" /><result property="office.primaryPerson.name" column="office.primaryPerson.name" /><result property="office.deputyPerson.id" column="office.deputyPerson.id" /><result property="office.deputyPerson.name" column="office.deputyPerson.name" /><collection property="roleList" ofType="Role"><id property="id" column="roleList.id" /><result property="office.id" column="roleList.office.id" /><result property="name" column="roleList.name" /><result property="enname" column="roleList.enname" /><result property="roleType" column="roleList.roleType" /><result property="dataScope" column="roleList.dataScope" /><collection property="officeList" ofType="Office"><id property="id" column="roleList.officeList.id" /></collection></collection></resultMap> -->    <sql id="userColumns">                  a.id,    a.company_id AS "company.id",    a.office_id AS "office.id",    a.login_name,    a.password,    a.no,a.name,a.email,a.phone,a.mobile,a.user_type,a.login_ip,a.login_date,a.remarks,a.login_flag,a.photo,a.qrcode,a.sign,a.entry_date,a.regular_date,a.level,a.gender,a.old,a.birthday,a.marriage,a.identity,a.graduate_school,a.specialty,a.education,a.address,a.insurance_date,a.insurance_no,a.accumulation_no,a.passport_no,a.passport_issue,a.passport_validity_date,a.quali_cert,a.bank_no,a.access_no,a.status,a.quit_date,a.quit_reason,a.quit_go,a.person_type,a.create_by AS "createBy.id",a.create_date,a.update_by AS "updateBy.id",a.update_date,a.del_flag,    c.name AS "company.name",    c.parent_id AS "company.parent.id",    c.parent_ids AS "company.parentIds",    ca.id AS "company.area.id",    ca.name AS "company.area.name",    ca.parent_id AS "company.area.parent.id",    ca.parent_ids AS "company.area.parentIds",    o.name AS "office.name",    o.parent_id AS "office.parent.id",    o.parent_ids AS "office.parentIds",    oa.id AS "office.area.id",    oa.name AS "office.area.name",    oa.parent_id AS "office.area.parent.id",    oa.parent_ids AS "office.area.parentIds",    cu.id AS "company.primaryPerson.id",    cu.name AS "company.primaryPerson.name",    cu2.id AS "company.deputyPerson.id",    cu2.name AS "company.deputyPerson.name",    ou.id AS "office.primaryPerson.id",    ou.name AS "office.primaryPerson.name",    ou2.id AS "office.deputyPerson.id",    ou2.name AS "office.deputyPerson.name"<!-- ,        r.id AS "roleList.id",        r.office_id AS "roleList.office.id",        r.name AS "roleList.name",        r.enname AS "roleList.enname",        r.role_type AS "roleList.roleType",        r.data_scope AS "roleList.dataScope" -->    </sql>    <sql id="userJoins">LEFT JOIN sys_office c ON c.id = a.company_idLEFT JOIN sys_area ca ON ca.id = c.area_idLEFT JOIN sys_office o ON o.id = a.office_idLEFT JOIN sys_area oa ON oa.id = o.area_idLEFT JOIN sys_user cu ON cu.id = c.primary_personLEFT JOIN sys_user cu2 ON cu2.id = c.deputy_personLEFT JOIN sys_user ou ON ou.id = o.primary_personLEFT JOIN sys_user ou2 ON ou2.id = o.deputy_person<!-- LEFT JOIN sys_user_role ur ON ur.user_id = a.id        LEFT JOIN sys_role r ON r.id = ur.role_id -->    </sql><!-- 根据编号获得用户 --><select id="get" resultType="User">SELECT<include refid="userColumns"/><!-- ,ro.office_id AS "roleList.officeList.id" -->FROM sys_user a<include refid="userJoins"/><!-- LEFT JOIN sys_role_office ro ON ro.role_id = r.id -->WHERE a.id = #{id}</select><!-- 根据登录名查询用户 --><select id="getByLoginName" resultType="User" parameterType="User">SELECT<include refid="userColumns"/><!-- ,ro.office_id AS "roleList.officeList.id" -->FROM sys_user a<include refid="userJoins"/><!-- LEFT JOIN sys_role_office ro ON ro.role_id = r.id -->WHERE a.login_name = #{loginName} AND a.del_flag = #{DEL_FLAG_NORMAL}</select><!-- 根据入职年份查询用户列表 --><select id="findUserByYear" resultType="User">SELECT<include refid="userColumns"/>FROM sys_user a <include refid="userJoins"/><if test="startTime!= null and startTime!=''"><![CDATA[WHERE a.entry_date > #{startTime}]]></if><if test="endTime!= null and endTime != ''"><![CDATA[ and a.entry_date < #{endTime}]]></if></select><!-- 分页查询用户信息 --><select id="findList" resultType="User">SELECT<include refid="userColumns"/>FROM sys_user a<include refid="userJoins"/><if test="role != null and role.id != null and role.id != ''">JOIN sys_user_role ur ON ur.user_id = a.id AND ur.role_id = #{role.id}</if>WHERE a.del_flag = #{DEL_FLAG_NORMAL}<if test="company != null and company.id != null and company.id != ''">AND (c.id = #{company.id} OR c.parent_ids LIKE <if test="dbName == 'oracle'">'%,'||#{company.id}||',%')</if><if test="dbName == 'mysql'">CONCAT('%,', #{company.id}, ',%'))</if></if><if test="office != null and office.id != null and office.id != ''">AND (o.id = #{office.id} OR o.parent_ids LIKE <if test="dbName == 'oracle'">'%,'||#{office.id}||',%')</if><if test="dbName == 'mysql'">CONCAT('%,', #{office.id}, ',%'))</if></if><!-- 如果不是超级管理员,则不显示超级管理员用户 --><if test="!currentUser.admin">AND a.id != '1'</if><if test="loginName != null and loginName != ''">AND a.login_name like <if test="dbName == 'oracle'">'%'||#{loginName}||'%'</if><if test="dbName == 'mysql'">CONCAT('%', #{loginName}, '%')</if></if><if test="name != null and name != ''">AND a.name like <if test="dbName == 'oracle'">'%'||#{name}||'%'</if><if test="dbName == 'mysql'">CONCAT('%', #{name}, '%')</if></if><if test="personType != null and personType != ''">AND a.person_type = #{personType} </if><!-- 数据范围过滤 -->${sqlMap.dsf}<choose><when test="page !=null and page.orderBy != null and page.orderBy != ''">ORDER BY ${page.orderBy}</when><otherwise>ORDER BY c.code, o.code, a.name</otherwise></choose></select><!-- 根据部门查询用户信息 --><select id="findListByOffice" resultType="User">SELECT<include refid="userColumns"/>FROM sys_user a<include refid="userJoins"/>WHERE a.del_flag = #{DEL_FLAG_NORMAL}<if test="company != null and company.id != null and company.id != ''">AND c.id = #{company.id} </if><if test="office != null and office.id != null and office.id != ''">AND o.id = #{office.id} </if><if test="office == null">AND (o.id = ''  or o.id is null)</if><if test="loginName != null and loginName != ''">AND a.login_name like <if test="dbName == 'oracle'">'%'||#{loginName}||'%'</if><if test="dbName == 'mysql'">CONCAT('%', #{loginName}, '%')</if></if><if test="name != null and name != ''">AND a.name like <if test="dbName == 'oracle'">'%'||#{name}||'%'</if><if test="dbName == 'mysql'">CONCAT('%', #{name}, '%')</if></if><if test="personType != null and personType != ''">AND a.person_type = #{personType} </if><!-- 数据范围过滤 -->${sqlMap.dsf}<!-- 排序 -->ORDER BY  a.name</select><!-- 根据OfficeId获取用户(树查询用户时用) --><select id="findUserByOfficeId" resultType="User" useCache="true">SELECTa.id, a.name, a.login_nameFROM sys_user aWHERE a.del_flag = #{DEL_FLAG_NORMAL}AND a.office_id = #{office.id}ORDER BY a.name</select><!-- 查询全部用户 --><select id="findAllList" resultType="User">SELECT<include refid="userColumns"/>FROM sys_user a<include refid="userJoins"/>WHERE a.del_flag = #{DEL_FLAG_NORMAL}ORDER BY c.code, o.code, a.name</select><!-- 查询全部用户数目 --><select id="findAllCount" resultType="long">SELECTCOUNT(1)FROM sys_user aWHERE a.del_flag = #{DEL_FLAG_NORMAL}</select><!-- 插入用户 --><insert id="insert">INSERT INTO sys_user(id, company_id, office_id, login_name, password, no, name, email, phone, mobile, user_type,entry_date,regular_date,level,gender,old,birthday,marriage,identity,graduate_school,specialty,education,address,insurance_date,insurance_no,accumulation_no,passport_no,passport_issue,passport_validity_date,quali_cert,bank_no,access_no,status,quit_date,quit_reason,quit_go,person_type,create_by, create_date, update_by, update_date, remarks, login_flag, photo, qrcode,del_flag) VALUES (#{id}, #{company.id}, #{office.id}, #{loginName}, #{password}, #{no}, #{name}, #{email}, #{phone}, #{mobile}, #{userType}, #{entryDate},#{regularDate},#{level},#{gender},#{old},#{birthday},#{marriage},#{encryptIdentity},#{graduateSchool},#{specialty},#{education},#{address},#{insuranceDate},#{insuranceNo},#{accumulationNo},#{encryptPassportNo},#{passportIssue},#{passportValidityDate},#{qualiCert},#{encryptBankNo},#{accessNo},#{status},#{quitDate},#{quitReason},#{quitGo},#{personType},#{createBy.id}, #{createDate}, #{updateBy.id}, #{updateDate}, #{remarks}, #{loginFlag}, #{photo}, #{qrCode},#{delFlag})</insert><!-- 更新用户 --><update id="update">UPDATE sys_user SET company_id = #{company.id}, office_id = #{office.id}, login_name = #{loginName}, password = #{password}, no = #{no}, name = #{name}, email = #{email}, phone = #{phone}, mobile = #{mobile}, user_type = #{userType}, entry_date = #{entryDate},regular_date = #{regularDate},level = #{level},gender = #{gender},old = #{old},birthday = #{birthday},marriage = #{marriage},identity = #{encryptIdentity},graduate_school = #{graduateSchool},specialty = #{specialty},education = #{education},address = #{address},insurance_date = #{insuranceDate},insurance_no = #{insuranceNo},accumulation_no = #{accumulationNo},passport_no = #{encryptPassportNo},passport_issue = #{passportIssue},passport_validity_date = #{passportValidityDate},quali_cert = #{qualiCert},bank_no = #{encryptBankNo},access_no = #{accessNo},status = #{status},quit_date = #{quitDate},quit_reason = #{quitReason},quit_go = #{quitGo},person_type = #{personType},update_by = #{updateBy.id}, update_date = #{updateDate}, remarks = #{remarks},login_flag = #{loginFlag},photo = #{photo},qrcode = #{qrCode}WHERE id = #{id}</update><!-- 删除用户和角色关联表数据 --><delete id="deleteUserRole">DELETE FROM sys_user_role WHERE user_id = #{id}</delete><!-- 插入用户和角色关联表数据 --><insert id="insertUserRole">INSERT INTO sys_user_role(user_id, role_id)<foreach collection="roleList" item="role" separator=" union all ">SELECT #{id}, #{role.id} FROM dual</foreach></insert><!-- 更新用户信息  --><update id="updateUserInfo">UPDATE sys_user SET name = #{name},email = #{email}, phone = #{phone}, mobile = #{mobile}, update_by = #{updateBy.id}, update_date = #{updateDate}, remarks = #{remarks},photo = #{photo},qrcode = #{qrCode},sign = #{sign}WHERE id = #{id}</update><!-- 更新用户密码 --><update id="updatePasswordById">UPDATE sys_user SET password = #{password} WHERE id = #{id}</update><!-- 更新登录信息,如登录IP、登录时间 --><update id="updateLoginInfo">UPDATE sys_user SET login_ip = #{loginIp}, login_Date = #{loginDate} WHERE id = #{id}</update><!-- 物理删除用户 --><update id="delete">DELETE FROM sys_user WHERE id = #{id}</update><!-- 逻辑删除用户 --><update id="deleteByLogic">UPDATE sys_user SET del_flag = #{DEL_FLAG_DELETE}WHERE id = #{id}</update><!-- 根据实体名称和字段名称和字段值获取唯一记录 --><select id="findUniqueByProperty"  resultType="User" statementType="STATEMENT">select * from sys_user where ${propertyName} = '${value}'</select><!-- 添加好友 --><insert id="insertFriend">INSERT INTO sys_user_friend(id, userId, friendId) VALUES (#{id}, #{userId}, #{friendId})</insert><!-- 根据用户id和好友id获取唯一记录 --><select id="findFriend" resultType="User">SELECT*FROM sys_user aLEFT JOIN sys_user_friend p ON p.userId = a.idWHERE p.userId = #{userId} and p.friendId = #{friendId}</select><!-- 删除好友 --><select id="deleteFriend">DELETE FROM sys_user_friend  WHERE userId = #{userId} and friendId = #{friendId}</select><!-- 查询我的好友列表 --><select id="findFriends"  resultType="User">SELECT<include refid="userColumns"/><!-- ,ro.office_id AS "roleList.officeList.id" -->FROM sys_user a<include refid="userJoins"/>LEFT JOIN sys_user_friend p ON p.friendId = a.idWHERE  p.userId = #{id}</select><!-- 根据条件检索用户,添加到好友列表 --><select id="searchUsers"  resultType="User">SELECT<include refid="userColumns"/><!-- ,ro.office_id AS "roleList.officeList.id" -->FROM sys_user a  <include refid="userJoins"/><if test="name != null and name != ''">WHERE  a.name like <if test="dbName == 'oracle'">'%'||#{name}||'%'</if><if test="dbName == 'mysql'">CONCAT('%', #{name}, '%')</if></if></select></mapper>


当然   在service方法 里  插入数据库操作之前   还要  加  几段 代码

@Transactional(readOnly = false)public void saveUser(User user) {user.setEncryptIdentity(SecretUtils.encrypt(user.getIdentity()));user.setEncryptPassportNo(SecretUtils.encrypt(user.getPassportNo()));user.setEncryptBankNo(SecretUtils.encrypt(user.getBankNo()));if (StringUtils.isBlank(user.getId())){user.preInsert();userDao.insert(user);}else{// 清除原用户机构用户缓存User oldUser = userDao.get(user.getId());if (oldUser.getOffice() != null && oldUser.getOffice().getId() != null){CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + oldUser.getOffice().getId());}// 更新用户数据user.preUpdate();userDao.update(user);}if (StringUtils.isNotBlank(user.getId())){// 更新用户与角色关联userDao.deleteUserRole(user);if (user.getRoleList() != null && user.getRoleList().size() > 0){userDao.insertUserRole(user);}else{throw new ServiceException(user.getLoginName() + "没有设置角色!");}// 清除用户缓存UserUtils.clearCache(user);//// 清除权限缓存//systemRealm.clearAllCachedAuthorizationInfo();}}

第一个版本的三个工具类  如下:

package com.jeeplus.common.utils.rsa;import it.sauronsoftware.base64.Base64;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;/** *//** * <p> * BASE64编码解码工具包 * </p> * <p> * 依赖javabase64-1.3.1.jar * </p> *  * @author IceWee * @date 2012-5-19 * @version 1.0 */public class Base64Utils {    /** *//**     * 文件读取缓冲区大小     */    private static final int CACHE_SIZE = 1024;        /** *//**     * <p>     * BASE64字符串解码为二进制数据     * </p>     *      * @param base64     * @return     * @throws Exception     */    public static byte[] decode(String base64) throws Exception {        return Base64.decode(base64.getBytes());    }        /** *//**     * <p>     * 二进制数据编码为BASE64字符串     * </p>     *      * @param bytes     * @return     * @throws Exception     */    public static String encode(byte[] bytes) throws Exception {        return new String(Base64.encode(bytes));    }        /** *//**     * <p>     * 将文件编码为BASE64字符串     * </p>     * <p>     * 大文件慎用,可能会导致内存溢出     * </p>     *      * @param filePath 文件绝对路径     * @return     * @throws Exception     */    public static String encodeFile(String filePath) throws Exception {        byte[] bytes = fileToByte(filePath);        return encode(bytes);    }        /** *//**     * <p>     * BASE64字符串转回文件     * </p>     *      * @param filePath 文件绝对路径     * @param base64 编码字符串     * @throws Exception     */    public static void decodeToFile(String filePath, String base64) throws Exception {        byte[] bytes = decode(base64);        byteArrayToFile(bytes, filePath);    }        /** *//**     * <p>     * 文件转换为二进制数组     * </p>     *      * @param filePath 文件路径     * @return     * @throws Exception     */    public static byte[] fileToByte(String filePath) throws Exception {        byte[] data = new byte[0];        File file = new File(filePath);        if (file.exists()) {            FileInputStream in = new FileInputStream(file);            ByteArrayOutputStream out = new ByteArrayOutputStream(2048);            byte[] cache = new byte[CACHE_SIZE];            int nRead = 0;            while ((nRead = in.read(cache)) != -1) {                out.write(cache, 0, nRead);                out.flush();            }            out.close();            in.close();            data = out.toByteArray();         }        return data;    }        /** *//**     * <p>     * 二进制数据写文件     * </p>     *      * @param bytes 二进制数据     * @param filePath 文件生成目录     */    public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {        InputStream in = new ByteArrayInputStream(bytes);           File destFile = new File(filePath);        if (!destFile.getParentFile().exists()) {            destFile.getParentFile().mkdirs();        }        destFile.createNewFile();        OutputStream out = new FileOutputStream(destFile);        byte[] cache = new byte[CACHE_SIZE];        int nRead = 0;        while ((nRead = in.read(cache)) != -1) {               out.write(cache, 0, nRead);            out.flush();        }        out.close();        in.close();    }        }

package com.jeeplus.common.utils.rsa;import java.io.ByteArrayOutputStream;import java.security.Key;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.PrivateKey;import java.security.PublicKey;import java.security.Signature;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.HashMap;import java.util.Map;import javax.crypto.Cipher;/** *//** * <p> * RSA公钥/私钥/签名工具包 * </p> * <p> * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman) * </p> * <p> * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/> * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/> * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全 * </p> *  * @author IceWee * @date 2012-4-26 * @version 1.0 */public class RSAUtils {    /** *//**     * 加密算法RSA     */    public static final String KEY_ALGORITHM = "RSA";        /** *//**     * 签名算法     */    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";    /** *//**     * 获取公钥的key     */    private static final String PUBLIC_KEY = "RSAPublicKey";        /** *//**     * 获取私钥的key     */    private static final String PRIVATE_KEY = "RSAPrivateKey";        /** *//**     * RSA最大加密明文大小     */    private static final int MAX_ENCRYPT_BLOCK = 117;        /** *//**     * RSA最大解密密文大小     */    private static final int MAX_DECRYPT_BLOCK = 128;    /** *//**     * <p>     * 生成密钥对(公钥和私钥)     * </p>     *      * @return     * @throws Exception     */    public static Map<String, Object> genKeyPair() throws Exception {        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);        keyPairGen.initialize(1024);        KeyPair keyPair = keyPairGen.generateKeyPair();        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();        Map<String, Object> keyMap = new HashMap<String, Object>(2);        keyMap.put(PUBLIC_KEY, publicKey);        keyMap.put(PRIVATE_KEY, privateKey);        return keyMap;    }        /** *//**     * <p>     * 用私钥对信息生成数字签名     * </p>     *      * @param data 已加密数据     * @param privateKey 私钥(BASE64编码)     *      * @return     * @throws Exception     */    public static String sign(byte[] data, String privateKey) throws Exception {        byte[] keyBytes = Base64Utils.decode(privateKey);        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);        signature.initSign(privateK);        signature.update(data);        return Base64Utils.encode(signature.sign());    }    /** *//**     * <p>     * 校验数字签名     * </p>     *      * @param data 已加密数据     * @param publicKey 公钥(BASE64编码)     * @param sign 数字签名     *      * @return     * @throws Exception     *      */    public static boolean verify(byte[] data, String publicKey, String sign)            throws Exception {        byte[] keyBytes = Base64Utils.decode(publicKey);        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);        PublicKey publicK = keyFactory.generatePublic(keySpec);        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);        signature.initVerify(publicK);        signature.update(data);        return signature.verify(Base64Utils.decode(sign));    }    /** *//**     * <P>     * 私钥解密     * </p>     *      * @param encryptedData 已加密数据     * @param privateKey 私钥(BASE64编码)     * @return     * @throws Exception     */    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)            throws Exception {        byte[] keyBytes = Base64Utils.decode(privateKey);        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());        cipher.init(Cipher.DECRYPT_MODE, privateK);        int inputLen = encryptedData.length;        ByteArrayOutputStream out = new ByteArrayOutputStream();        int offSet = 0;        byte[] cache;        int i = 0;        // 对数据分段解密        while (inputLen - offSet > 0) {            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);            } else {                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);            }            out.write(cache, 0, cache.length);            i++;            offSet = i * MAX_DECRYPT_BLOCK;        }        byte[] decryptedData = out.toByteArray();        out.close();        return decryptedData;    }    /** *//**     * <p>     * 公钥解密     * </p>     *      * @param encryptedData 已加密数据     * @param publicKey 公钥(BASE64编码)     * @return     * @throws Exception     */    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)            throws Exception {        byte[] keyBytes = Base64Utils.decode(publicKey);        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);        Key publicK = keyFactory.generatePublic(x509KeySpec);        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());        cipher.init(Cipher.DECRYPT_MODE, publicK);        int inputLen = encryptedData.length;        ByteArrayOutputStream out = new ByteArrayOutputStream();        int offSet = 0;        byte[] cache;        int i = 0;        // 对数据分段解密        while (inputLen - offSet > 0) {            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);            } else {                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);            }            out.write(cache, 0, cache.length);            i++;            offSet = i * MAX_DECRYPT_BLOCK;        }        byte[] decryptedData = out.toByteArray();        out.close();        return decryptedData;    }    /** *//**     * <p>     * 公钥加密     * </p>     *      * @param data 源数据     * @param publicKey 公钥(BASE64编码)     * @return     * @throws Exception     */    public static byte[] encryptByPublicKey(byte[] data, String publicKey)            throws Exception {        byte[] keyBytes = Base64Utils.decode(publicKey);        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);        Key publicK = keyFactory.generatePublic(x509KeySpec);        // 对数据加密        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());        cipher.init(Cipher.ENCRYPT_MODE, publicK);        int inputLen = data.length;        ByteArrayOutputStream out = new ByteArrayOutputStream();        int offSet = 0;        byte[] cache;        int i = 0;        // 对数据分段加密        while (inputLen - offSet > 0) {            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);            } else {                cache = cipher.doFinal(data, offSet, inputLen - offSet);            }            out.write(cache, 0, cache.length);            i++;            offSet = i * MAX_ENCRYPT_BLOCK;        }        byte[] encryptedData = out.toByteArray();        out.close();        return encryptedData;    }    /** *//**     * <p>     * 私钥加密     * </p>     *      * @param data 源数据     * @param privateKey 私钥(BASE64编码)     * @return     * @throws Exception     */    public static byte[] encryptByPrivateKey(byte[] data, String privateKey)            throws Exception {        byte[] keyBytes = Base64Utils.decode(privateKey);        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());        cipher.init(Cipher.ENCRYPT_MODE, privateK);        int inputLen = data.length;        ByteArrayOutputStream out = new ByteArrayOutputStream();        int offSet = 0;        byte[] cache;        int i = 0;        // 对数据分段加密        while (inputLen - offSet > 0) {            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);            } else {                cache = cipher.doFinal(data, offSet, inputLen - offSet);            }            out.write(cache, 0, cache.length);            i++;            offSet = i * MAX_ENCRYPT_BLOCK;        }        byte[] encryptedData = out.toByteArray();        out.close();        return encryptedData;    }    /** *//**     * <p>     * 获取私钥     * </p>     *      * @param keyMap 密钥对     * @return     * @throws Exception     */    public static String getPrivateKey(Map<String, Object> keyMap)            throws Exception {        Key key = (Key) keyMap.get(PRIVATE_KEY);        return Base64Utils.encode(key.getEncoded());    }    /** *//**     * <p>     * 获取公钥     * </p>     *      * @param keyMap 密钥对     * @return     * @throws Exception     */    public static String getPublicKey(Map<String, Object> keyMap)            throws Exception {        Key key = (Key) keyMap.get(PUBLIC_KEY);        return Base64Utils.encode(key.getEncoded());    }}

package com.jeeplus.common.utils.rsa;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.Map;import java.util.Properties;import com.jeeplus.common.utils.StringUtils;public class SecretUtils {private static String publicKey;private static String privateKey;static{Properties prop = new Properties();try {String path = SecretUtils.class.getClassLoader().getResource("/rsakey.properties").getPath();        File file = new File(path);        InputStream inStream = new FileInputStream(file);        prop.load(inStream);        if(!prop.containsKey("publicKey") || !prop.containsKey("privateKey")){        Map<String, Object> keyMap = RSAUtils.genKeyPair();        OutputStream oFile = new FileOutputStream(file);        if(!prop.containsKey("publicKey")){        publicKey = RSAUtils.getPublicKey(keyMap);        prop.setProperty("publicKey", publicKey);        privateKey = prop.getProperty("privateKey");        }        if(!prop.containsKey("privateKey")){        privateKey = RSAUtils.getPrivateKey(keyMap);        prop.setProperty("privateKey", privateKey);        publicKey = prop.getProperty("publicKey");        }        prop.store(oFile, null);                oFile.close();        }else{        publicKey = prop.getProperty("publicKey");        privateKey = prop.getProperty("privateKey");        }} catch (Exception e) {e.printStackTrace();}}   /**    * 公钥加密    * @param source    * @return    */    public static String encrypt(String source){    String result = "";    try {    if(StringUtils.isNotBlank(source)){        byte[] data = source.getBytes();            byte[] decodedData = RSAUtils.encryptByPublicKey(data, publicKey);            StringBuffer str = new StringBuffer();            for(byte b : decodedData){                str.append(b).append(" ");                }            result = str.toString();    }} catch (Exception e) {e.printStackTrace();}    return result;    }        /**     * 私钥解密     * @param source     * @return     */    public static String decrypt(String source){    String result = "";    try {    if(StringUtils.isNotBlank(source)){    String[] strArr = source.toString().split(" ");    if(strArr.length == 1){    return source;    }        byte[] clone = new byte[strArr.length];                for (int i = 0; i < strArr.length; i++) {                clone[i] = Byte.parseByte(strArr[i]);                }            byte[] encodedData = RSAUtils.decryptByPrivateKey(clone, privateKey);            result = new String(encodedData);    }} catch (Exception e) {e.printStackTrace();}    return result;    }    }

这样  就将 公钥  和 私钥    存入properties配置文件  虽然  这样可以 将  数据库中的   字段加密 解密了         但是 这时会遇到第二个问题

二、 在页面上   如果 有通过name来模糊匹配查找  数据库数据         但是数据库中 name字段 都是加密 后的乱码,而 搜索框 中数据  为 手输 。

         这样   就不能正确 查找到  数据  如果 我们 把手输的数据加密  后 再  查找  也可以 ,但是   不能 实现 模糊匹配了,因为“张飞”  和“张” 的加密后的字符串

         是一点不同的      所以这里 也有问题         后来 干脆   name就不加密  了  

第三个问题 :    

三 ,由于 这个工具类 调用 一次 生成 一次   公钥  和 私钥   所以在  tomcat 服务器  启动  一次生成一次公钥  私钥   这样 后面的 私钥 就不能   解密  前面公钥加密 的

    数据库 数据了         这时  控制台  报错如下:

javax.crypto.BadPaddingException: Decryption errorat sun.security.rsa.RSAPadding.unpadV15(Unknown Source)at sun.security.rsa.RSAPadding.unpad(Unknown Source)at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)at javax.crypto.Cipher.doFinal(Cipher.java:2145)at com.jeeplus.common.utils.rsa.RSAUtils.decryptByPrivateKey(RSAUtils.java:164)at com.jeeplus.common.utils.rsa.SecretUtils.decrypt(SecretUtils.java:88)at com.jeeplus.modules.sys.entity.User.getBankNo(User.java:561)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)at java.lang.reflect.Method.invoke(Unknown Source)

所以   这 说明  项目中的   RSA加密解密 的公钥 私钥  必须 一次生成  不能 修改         否则 后面 生成的私钥  不能 解密 前面 公钥  加密 的数据

这样   key就不能存在 rsaKey.properties中    只能 插入数据库中 并且 不能修改       

 所以    工具类   就得  修改            未完  待续........

继续呵呵 

在数据库中创建  表    用来保存key

-- ------------------------------ Table structure for `rsa_key`-- ----------------------------DROP TABLE IF EXISTS `rsa_key`;CREATE TABLE `rsa_key` (  `id` varchar(64) NOT NULL COMMENT '主键',  `public_key` varchar(500) DEFAULT NULL COMMENT '公钥',  `private_key` varchar(500) DEFAULT NULL COMMENT '私钥',  `create_by` varchar(64) DEFAULT NULL COMMENT '创建者',  `create_date` datetime DEFAULT NULL COMMENT '创建时间',  `update_by` varchar(64) DEFAULT NULL COMMENT '更新者',  `update_date` datetime DEFAULT NULL COMMENT '更新时间',  `remarks` varchar(255) DEFAULT NULL COMMENT '备注信息',  `del_flag` varchar(64) DEFAULT NULL COMMENT '逻辑删除标记(0:显示;1:隐藏)',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='RSA加密';-- ------------------------------ Records of rsa_key-- ----------------------------INSERT INTO `rsa_key` VALUES ('rsakey', null, null, '1', '2017-05-25 11:28:29', '1', '2017-05-25 11:28:29', null, '0');

工具类修改如下         只需要修改SecreUtils这一个工具类就好    

package com.jeeplus.common.utils.rsa;import java.util.Map;import com.jeeplus.common.utils.SpringContextHolder;import com.jeeplus.common.utils.StringUtils;import com.jeeplus.modules.rgssys.dao.RSAKeyDao;import com.jeeplus.modules.rgssys.entity.RSAKey;public class SecretUtils {private static RSAKeyDao keyDao = SpringContextHolder.getBean(RSAKeyDao.class);/*static{try {Properties prop = new Properties();String path = SecretUtils.class.getClassLoader().getResource("/rsakey.properties").getPath();        File file = new File(path);        InputStream inStream = new FileInputStream(file);        prop.load(inStream);if(!prop.containsKey("publicKey") || !prop.containsKey("privateKey")){        Map<String, Object> keyMap = RSAUtils.genKeyPair();        OutputStream oFile = new FileOutputStream(file);        if(!prop.containsKey("publicKey")){        publicKey = RSAUtils.getPublicKey(keyMap);        prop.setProperty("publicKey", publicKey);        privateKey = prop.getProperty("privateKey");        }        if(!prop.containsKey("privateKey")){        privateKey = RSAUtils.getPrivateKey(keyMap);        prop.setProperty("privateKey", privateKey);        publicKey = prop.getProperty("publicKey");        }        prop.store(oFile, null);                oFile.close();        }else{        publicKey = prop.getProperty("publicKey");        privateKey = prop.getProperty("privateKey");        }} catch (Exception e) {e.printStackTrace();}}*/   /**    * 公钥加密    * @param source    * @return    */    public static String encrypt(String source){    String result = "";    try {    if(StringUtils.isNotBlank(source)){    RSAKey rsaKey = keyDao.get("rsakey");    if(StringUtils.isBlank(rsaKey.getPublicKey()) || StringUtils.isBlank(rsaKey.getPrivateKey())){    Map<String, Object> keyMap = RSAUtils.genKeyPair();    String publicKey = RSAUtils.getPublicKey(keyMap);    String privateKey = RSAUtils.getPrivateKey(keyMap);    rsaKey.setPublicKey(publicKey);    rsaKey.setPrivateKey(privateKey);    keyDao.update(rsaKey);    }        byte[] data = source.getBytes();            byte[] decodedData = RSAUtils.encryptByPublicKey(data, rsaKey.getPublicKey());            StringBuffer str = new StringBuffer();            for(byte b : decodedData){                str.append(b).append(" ");                }            result = str.toString();    }} catch (Exception e) {e.printStackTrace();}    return result;    }        /**     * 私钥解密     * @param source     * @return     */    public static String decrypt(String source){    String result = "";    try {    if(StringUtils.isNotBlank(source)){    RSAKey rsaKey = keyDao.get("rsakey");    if(StringUtils.isBlank(rsaKey.getPublicKey()) || StringUtils.isBlank(rsaKey.getPrivateKey())){    Map<String, Object> keyMap = RSAUtils.genKeyPair();    String publicKey = RSAUtils.getPublicKey(keyMap);    String privateKey = RSAUtils.getPrivateKey(keyMap);    rsaKey.setPublicKey(publicKey);    rsaKey.setPrivateKey(privateKey);    keyDao.update(rsaKey);    }    String[] strArr = source.toString().split(" ");    if(strArr.length == 1){    return source;    }        byte[] clone = new byte[strArr.length];                for (int i = 0; i < strArr.length; i++) {                clone[i] = Byte.parseByte(strArr[i]);                }            byte[] encodedData = RSAUtils.decryptByPrivateKey(clone, rsaKey.getPrivateKey());            result = new String(encodedData);    }} catch (Exception e) {e.printStackTrace();}    return result;    }    }


private static RSAKeyDao keyDao = SpringContextHolder.getBean(RSAKeyDao.class);

这段代码调用的类为

 package com.jeeplus.common.utils;import java.net.HttpURLConnection;import java.net.URL;import java.util.Date;import org.apache.commons.lang3.Validate;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.DisposableBean;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.context.annotation.Lazy;import org.springframework.stereotype.Service;import com.jeeplus.common.config.Global;/** * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext. *  * @author Zaric * @date 2013-5-29 下午1:25:40 */@Service@Lazy(false)public class SpringContextHolder implements ApplicationContextAware, DisposableBean {private static ApplicationContext applicationContext = null;private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);/** * 取得存储在静态变量中的ApplicationContext. */public static ApplicationContext getApplicationContext() {assertContextInjected();return applicationContext;}/** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */@SuppressWarnings("unchecked")public static <T> T getBean(String name) {assertContextInjected();return (T) applicationContext.getBean(name);}/** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */public static <T> T getBean(Class<T> requiredType) {assertContextInjected();return applicationContext.getBean(requiredType);}/** * 清除SpringContextHolder中的ApplicationContext为Null. */public static void clearHolder() {if (logger.isDebugEnabled()){logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);}applicationContext = null;}/** * 实现ApplicationContextAware接口, 注入Context到静态变量中. */@Overridepublic void setApplicationContext(ApplicationContext applicationContext) {SpringContextHolder.applicationContext = applicationContext;}/** * 实现DisposableBean接口, 在Context关闭时清理静态变量. */@Overridepublic void destroy() throws Exception {SpringContextHolder.clearHolder();}/** * 检查ApplicationContext不为空. */private static void assertContextInjected() {Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");}}
第四个问题:
获取  keyDao    只能用这个方法      private static RSAKeyDao keyDao = SpringContextHolder.getBean(RSAKeyDao.class);

如果这样写

@Autowired

private static RSAKeyDao keyDao ;       

自动加载不上       一是  springMVC配置只扫描   Controller           二是 自动加载  不能用static修饰 这个Bean                 会报空指针 错误。

完结...............................

欢迎指正鄙视鄙视鄙视

最后再把    dao层贴上

package com.jeeplus.modules.rgssys.entity;import com.jeeplus.common.persistence.DataEntity;import com.jeeplus.common.utils.excel.annotation.ExcelField;/** * RSA加密Entity * @author  * @version 2017-05-25 */public class RSAKey extends DataEntity<RSAKey> {private static final long serialVersionUID = 1L;private String publicKey;// 公钥private String privateKey;// 私钥public RSAKey() {super();}public RSAKey(String id){super(id);}@ExcelField(title="公钥", align=2, sort=1)public String getPublicKey() {return publicKey;}public void setPublicKey(String publicKey) {this.publicKey = publicKey;}@ExcelField(title="私钥", align=2, sort=2)public String getPrivateKey() {return privateKey;}public void setPrivateKey(String privateKey) {this.privateKey = privateKey;}}

package com.jeeplus.modules.rgssys.dao;import com.jeeplus.common.persistence.CrudDao;import com.jeeplus.common.persistence.annotation.MyBatisDao;import com.jeeplus.modules.rgssys.entity.RSAKey;/** * RSA加密DAO接口 * @author * @version 2017-05-25 */@MyBatisDaopublic interface RSAKeyDao extends CrudDao<RSAKey> {}

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.jeeplus.modules.rgssys.dao.RSAKeyDao">    <sql id="rSAKeyColumns">a.id AS "id",a.public_key AS "publicKey",a.private_key AS "privateKey",a.create_by AS "createBy.id",a.create_date AS "createDate",a.update_by AS "updateBy.id",a.update_date AS "updateDate",a.remarks AS "remarks",a.del_flag AS "delFlag"</sql><sql id="rSAKeyJoins"></sql>    <select id="get" resultType="RSAKey" >SELECT <include refid="rSAKeyColumns"/>FROM rsa_key a<include refid="rSAKeyJoins"/>WHERE a.id = #{id}</select><select id="findList" resultType="RSAKey" >SELECT <include refid="rSAKeyColumns"/>FROM rsa_key a<include refid="rSAKeyJoins"/><where>a.del_flag = #{DEL_FLAG_NORMAL}</where><choose><when test="page !=null and page.orderBy != null and page.orderBy != ''">ORDER BY ${page.orderBy}</when><otherwise>ORDER BY a.update_date DESC</otherwise></choose></select><select id="findAllList" resultType="RSAKey" >SELECT <include refid="rSAKeyColumns"/>FROM rsa_key a<include refid="rSAKeyJoins"/><where>a.del_flag = #{DEL_FLAG_NORMAL}</where><choose><when test="page !=null and page.orderBy != null and page.orderBy != ''">ORDER BY ${page.orderBy}</when><otherwise>ORDER BY a.update_date DESC</otherwise></choose></select><insert id="insert">INSERT INTO rsa_key(id,public_key,private_key,create_by,create_date,update_by,update_date,remarks,del_flag) VALUES (#{id},#{publicKey},#{privateKey},#{createBy.id},#{createDate},#{updateBy.id},#{updateDate},#{remarks},#{delFlag})</insert><update id="update">UPDATE rsa_key SET public_key = #{publicKey},private_key = #{privateKey},update_by = #{updateBy.id},update_date = #{updateDate},remarks = #{remarks}WHERE id = #{id}</update><!--物理删除--><update id="delete">DELETE FROM rsa_keyWHERE id = #{id}</update><!--逻辑删除--><update id="deleteByLogic">UPDATE rsa_key SET del_flag = #{DEL_FLAG_DELETE}WHERE id = #{id}</update><!-- 根据实体名称和字段名称和字段值获取唯一记录 --><select id="findUniqueByProperty" resultType="RSAKey" statementType="STATEMENT">select * FROM rsa_key  where ${propertyName} = '${value}'</select></mapper>