数据摘要加密解密(四)

对RSA加密类进行实现,因RSA加密方式与抽取共性的加密方式不同,所以直接继承ISecurity安全接口,并将定义自有的方法,见程序

IRsaEncrypt接口:

 1 package com.xqrj.security;
2
3 import java.security.PrivateKey;
4 import java.security.PublicKey;
5 import java.security.cert.Certificate;
6
7 public interface IRsaEncrypt extends ISecurity {
8 /**
9 * 设置证书
10 * @param certificate 设置证书对象
11 * @return void
12 */
13 public void setCertificate(Certificate certificate);
14 /**
15 * 设置公钥
16 * @param publicKey 设置公钥对象
17 * @return void
18 */
19 public void setPublicKey(PublicKey publicKey);
20 /**
21 * 设置私钥
22 * @param privateKey 设置私钥对象
23 * @return void
24 */
25 public void setPrivateKey(PrivateKey privateKey);
26 }

RsaEncryptImpl加密抽象类,主要实现在此抽象类中

并在抽象类里定义了构造方法,可以对文件证书进行设置然后得到公钥和私钥,如不想实现此方法或公钥私钥分离,可用SET方法进行公钥和私钥属性的设置

  1 package com.xqrj.security.encrypt;
2
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.security.KeyStore;
7 import java.security.PrivateKey;
8 import java.security.PublicKey;
9 import java.security.cert.Certificate;
10 import java.util.Enumeration;
11
12 import javax.crypto.Cipher;
13 import javax.crypto.SecretKey;
14 import javax.crypto.spec.SecretKeySpec;
15
16 import com.xqrj.security.IRsaEncrypt;
17 import com.xqrj.util.PublicUtil;
18
19 public abstract class RsaEncryptImpl implements IRsaEncrypt {
20 protected String algorithm = "RSA";
21 protected int encodeMode = 0;
22 protected byte[] key;
23 /*
24 * 使用RSA算法(RSA,RSA/ECB/PKCS1Padding为117位,NoPadding为128位)
25 * RSA/ECB/PKCS1Padding的方式是按照PKCS1的标准.即输入数据长度小于等于密钥的位数/8-11
26 * 例如:1024位密钥,1024/8-11=117.不足的部分,程序会自动补齐.加密后的数据还是等于密钥的位数/8-11(8至11之间)
27 * 如果不指定,那么输入数据就必须等于密钥的位数/8
28 */
29 protected byte[] otherData = "RSA/ECB/PKCS1Padding".getBytes();
30
31 /** 服务器证书 */
32 protected Certificate certificate = null;
33 /** 服务器公钥 */
34 protected PublicKey publicKey = null;
35 /** 服务器私钥 */
36 protected PrivateKey privateKey = null;
37
38 public RsaEncryptImpl() {
39
40 }
41
42 public RsaEncryptImpl(String certFile,String certPass) {
43 FileInputStream fis = null;
44 FileOutputStream ois = null;
45 String KeyType = "PKCS12";
46 try {
47 KeyStore keyStore = KeyStore.getInstance(KeyType);
48 fis = new FileInputStream(certFile);
49 char[] password = null;
50 if ((null!=certPass) && !"".equals(certPass)) {
51 password = certPass.toCharArray();
52 }
53 keyStore.load(fis, password);
54 fis.close();
55 Enumeration enums = keyStore.aliases();
56 String keyAlias = null;
57 if (enums.hasMoreElements()) {
58 keyAlias = (String)enums.nextElement();
59 }
60
61 privateKey = (PrivateKey)keyStore.getKey(keyAlias, password);
62 certificate = keyStore.getCertificate(keyAlias);
63 publicKey = certificate.getPublicKey();
64 } catch (Exception e) {
65 e.printStackTrace();
66 } finally {
67 if (null!=ois) try {ois.close();} catch (IOException e) {e.printStackTrace();}
68 if (null!=fis) try {fis.close();} catch (IOException e) {e.printStackTrace();}
69 }
70 }
71
72 public byte[] buildData(byte[] buff) throws SecurityException {
73 try {
74 //获取证书取得公钥进行加密
75 if (null==publicKey) {
76 //证书为空判断公钥是否为空
77 if (null==certificate) {
78 throw new SecurityException("获取公钥失败,无法进行数据加密!");
79 } else {
80 this.publicKey = (PublicKey)certificate.getPublicKey();
81 }
82 }
83 //判断加密的数据长度不可以大于128
84 if (buff.length>128) {
85 throw new SecurityException("加密数据长度超过128位,无法进行数据加密!");
86 }
87 //Cipher对象实际完成加密操作
88 Cipher cipher = Cipher.getInstance(new String(otherData));
89 //用密匙初始化Cipher对象
90 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
91 //执行加密操作
92 byte[] data = cipher.doFinal(buff);
93
94 switch(encodeMode) {
95 case 1: //BASE64
96 return PublicUtil.getBase64Encode(data).getBytes();
97 case 2: //HEX
98 return new String(PublicUtil.bytesToHex(data)).getBytes();
99 default:
100 return data;
101 }
102 } catch(SecurityException e) {
103 throw new SecurityException(e.getMessage());
104 } catch(Exception e) {
105 e.printStackTrace();
106 throw new SecurityException("RsaEncrypt对数据加密时出错!");
107 }
108 }
109
110 public void setCertificate(Certificate certificate) {
111 this.certificate = certificate;
112 }
113
114 public void setPrivateKey(PrivateKey privateKey) {
115 this.privateKey = privateKey;
116 }
117
118 public void setPublicKey(PublicKey publicKey) {
119 this.publicKey = publicKey;
120 }
121
122 public void setAlgorithm(String algorithm) {
123 this.algorithm = algorithm;
124 }
125
126 public void setEncodeMode(int encodeMode) {
127 this.encodeMode = encodeMode;
128 }
129
130 public void setKey(byte[] key) {
131 this.key = key;
132 }
133
134 public void setOther(byte[] otherData) {
135 this.otherData = otherData;
136 }
137 }

RSA加密实现类,分为了两个:一个是公钥加密、一个是私钥加密,并在私钥加密中添加了添加了签名方法(签名方法并未进行抽象,只有私钥加密进行实现)

RsaPublicEncrypt公钥加密类:

 1 package com.xqrj.security.encrypt;
2
3 import java.security.PrivateKey;
4 import java.security.PublicKey;
5 import java.security.cert.Certificate;
6
7 import javax.crypto.Cipher;
8
9 import com.xqrj.util.PublicUtil;
10
11 public class RsaPublicEncrypt extends RsaEncryptImpl {
12 public RsaPublicEncrypt(String certFile, String certPass) {
13 super(certFile, certPass);
14 }
15 public byte[] buildData(byte[] buff) throws SecurityException {
16 try {
17 //获取证书取得公钥进行加密
18 if (null==publicKey) {
19 //证书为空判断公钥是否为空
20 if (null==certificate) {
21 throw new SecurityException("获取公钥失败,无法进行数据加密!");
22 } else {
23 this.publicKey = (PublicKey)certificate.getPublicKey();
24 }
25 }
26 //判断加密的数据长度不可以大于128
27 if (buff.length>128) {
28 throw new SecurityException("加密数据长度超过128位,无法进行数据加密!");
29 }
30 //Cipher对象实际完成加密操作
31 Cipher cipher = Cipher.getInstance(new String(otherData));
32 //用密匙初始化Cipher对象
33 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
34 //执行加密操作
35 byte[] data = cipher.doFinal(buff);
36
37 switch(encodeMode) {
38 case 1: //BASE64
39 return PublicUtil.getBase64Encode(data).getBytes();
40 case 2: //HEX
41 return new String(PublicUtil.bytesToHex(data)).getBytes();
42 default:
43 return data;
44 }
45 } catch(SecurityException e) {
46 throw new SecurityException(e.getMessage());
47 } catch(Exception e) {
48 e.printStackTrace();
49 throw new SecurityException("RsaPublicEncrypt对数据加密时出错!");
50 }
51 }
52 }

RsaPrivateEncrypt私钥加密类:

 1 package com.xqrj.security.encrypt;
2
3 import java.security.PrivateKey;
4 import java.security.PublicKey;
5 import java.security.Signature;
6 import java.security.cert.Certificate;
7
8 import javax.crypto.Cipher;
9
10 import com.xqrj.util.PublicUtil;
11
12 public class RsaPrivateEncrypt extends RsaEncryptImpl {
13 public RsaPrivateEncrypt(String certFile, String certPass) {
14 super(certFile, certPass);
15 }
16 public byte[] buildData(byte[] buff) throws SecurityException {
17 try {
18 //获取证书取得私钥进行加密
19 if (null==privateKey) {
20 throw new SecurityException("私钥对象为空,无法进行数据加密!");
21 }
22 //判断加密的数据长度不可以大于128
23 if (buff.length>128) {
24 throw new SecurityException("加密数据长度超过128位,无法进行数据加密!");
25 }
26 //Cipher对象实际完成加密操作
27 Cipher cipher = Cipher.getInstance(new String(otherData));
28 //用密匙初始化Cipher对象
29 cipher.init(Cipher.ENCRYPT_MODE, privateKey);
30 //执行加密操作
31 byte[] data = cipher.doFinal(buff);
32
33 switch(encodeMode) {
34 case 1: //BASE64
35 return PublicUtil.getBase64Encode(data).getBytes();
36 case 2: //HEX
37 return new String(PublicUtil.bytesToHex(data)).getBytes();
38 default:
39 return data;
40 }
41 } catch(SecurityException e) {
42 throw new SecurityException(e.getMessage());
43 } catch(Exception e) {
44 e.printStackTrace();
45 throw new SecurityException("RsaPrivateEncrypt对数据加密时出错!");
46 }
47 }
48 /**
49 * 生成签名数据
50 * @param buff 需要签名的数据
51 * @return byte[] 签名后的数据
52 */
53 public byte[] buildSignData(byte[] buff) throws SecurityException {
54 try {
55 //获取证书取得公钥进行加密
56 if (null==privateKey) {
57 throw new SecurityException("私钥对象为空,无法进行数据签名!");
58 }
59
60 //对数据进行签名
61 Signature signature = Signature.getInstance(this.algorithm);
62 signature.initSign(privateKey);
63 signature.update(buff);
64 byte[] data = signature.sign();
65
66 switch(encodeMode) {
67 case 1: //BASE64
68 return PublicUtil.getBase64Encode(data).getBytes();
69 case 2: //HEX
70 return new String(PublicUtil.bytesToHex(data)).getBytes();
71 default:
72 return data;
73 }
74 } catch(SecurityException e) {
75 throw new SecurityException(e.getMessage());
76 } catch(Exception e) {
77 e.printStackTrace();
78 throw new SecurityException("RsaPrivateEncrypt对数据加密时出错!");
79 }
80 }
81 }

SecurityTest测试类:

  1 package com.xqrj.security;
2
3 import java.security.Security;
4
5 import com.xqrj.security.decrypt.DesDecrypt;
6 import com.xqrj.security.decrypt.RsaPrivateDecrypt;
7 import com.xqrj.security.decrypt.RsaPublicDecrypt;
8 import com.xqrj.security.digest.DigestDigest;
9 import com.xqrj.security.encrypt.DesEncrypt;
10 import com.xqrj.security.encrypt.RsaPrivateEncrypt;
11 import com.xqrj.security.encrypt.RsaPublicEncrypt;
12
13 public class SecurityTest {
14 public static void main(String[] args) {
15 //需要加密的数据
16 byte[] buff = "abcdefgh12345678".getBytes();
17 //密钥KEY
18 String key = "";
19 //使用何种算法
20 String algorithm = "";
21 //其它数据
22 String other = "";
23 //数据编码(1:BASE64 2:HEX)
24 int encodeMode = 1;
25 //结果数据
26 byte[] resBuff = null;
27 try {
28 //*********************************************************************************
29 //摘要测试
30 DigestDigest digestEncrypt = new DigestDigest();
31 //MD2、MD5用HEX进行编码
32 digestEncrypt.setAlgorithm("MD2");
33 digestEncrypt.setEncodeMode(2);
34 resBuff = digestEncrypt.buildData(buff);
35 System.out.println("生成的MD2摘要数据:"+new String(resBuff));
36 digestEncrypt.setAlgorithm("MD5");
37 resBuff = digestEncrypt.buildData(buff);
38 System.out.println("生成的MD5摘要数据:"+new String(resBuff));
39 //SHA用BASE进行编码
40 digestEncrypt.setAlgorithm("SHA");
41 digestEncrypt.setEncodeMode(1);
42 resBuff = digestEncrypt.buildData(buff);
43 System.out.println("生成的SHA-1摘要数据:"+new String(resBuff));
44 digestEncrypt.setAlgorithm("SHA-256");
45 resBuff = digestEncrypt.buildData(buff);
46 System.out.println("生成的SHA-256摘要数据:"+new String(resBuff));
47 digestEncrypt.setAlgorithm("SHA-384");
48 resBuff = digestEncrypt.buildData(buff);
49 System.out.println("生成的SHA-384摘要数据:"+new String(resBuff));
50 digestEncrypt.setAlgorithm("SHA-512");
51 resBuff = digestEncrypt.buildData(buff);
52 System.out.println("生成的SHA-512摘要数据:"+new String(resBuff));
53 //*********************************************************************************
54 //DES测试(加密)
55 //添加新安全算法,如果用JCE就要把它添加进去
56 Security.addProvider(new com.sun.crypto.provider.SunJCE());
57 DesEncrypt desEncrypt = new DesEncrypt();
58 key = "11111111";
59 desEncrypt.setAlgorithm("DES");
60 desEncrypt.setKey(key.getBytes());
61 desEncrypt.setOther("DES/ECB/NoPadding".getBytes());
62 desEncrypt.setEncodeMode(2);
63 resBuff = desEncrypt.buildData(buff);
64 System.out.println("DES加密后的数据:"+new String(resBuff));
65 //*********************************************************************************
66 //3DES测试(加密)
67 key = "111111112222222211111111";
68 desEncrypt.setAlgorithm("DESede");
69 desEncrypt.setKey(key.getBytes());
70 desEncrypt.setOther("DESede/ECB/NoPadding".getBytes());
71 desEncrypt.setEncodeMode(2);
72 resBuff = desEncrypt.buildData(buff);
73 System.out.println("3DES加密后的数据:"+new String(resBuff));
74 //*********************************************************************************
75 //AES测试(加密)
76 key = "1111111122222222";
77 desEncrypt.setAlgorithm("AES");
78 desEncrypt.setKey(key.getBytes());
79 desEncrypt.setOther("AES/ECB/NoPadding".getBytes());
80 desEncrypt.setEncodeMode(2);
81 resBuff = desEncrypt.buildData(buff);
82 System.out.println("AES加密后的数据:"+new String(resBuff));
83 //*********************************************************************************
84 //RSA测试(加密)
85 buff = "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456".getBytes();
86 String certFile = "D://TestCert.pfx";
87 String certPass = "1111";
88
89 RsaPublicEncrypt rsaPublicEncrypt = new RsaPublicEncrypt(certFile,certPass);
90 RsaPrivateEncrypt rsaPrivateEncrypt = new RsaPrivateEncrypt(certFile,certPass);
91 rsaPublicEncrypt.setEncodeMode(2);
92 rsaPrivateEncrypt.setEncodeMode(2);
93 byte[] pubEncryptBuff = rsaPublicEncrypt.buildData(buff);
94 System.out.println("RSA公钥加密后的数据:"+new String(pubEncryptBuff));
95 byte[] priEncryptBuff = rsaPrivateEncrypt.buildData(buff);
96 System.out.println("RSA私钥加密后的数据:"+new String(priEncryptBuff));
97 rsaPrivateEncrypt.setAlgorithm("MD5withRSA");
98 byte[] signEncryptBuff = rsaPrivateEncrypt.buildSignData(buff);
99 System.out.println("RSA签名后的数据:"+new String(signEncryptBuff));
100 //*********************************************************************************
101 } catch(Exception e) {
102 e.printStackTrace();
103 }
104 }
105 }

想要实现的加密算法基本上就完成了,如在想实现其它算法,只需要实现接口即可,方式大同小异

转载于:https://www.cnblogs.com/ynjxxk/archive/2012/03/30/2424638.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值