1、Java安全之秘密密钥-对称加密

在Java中,秘密密钥的抽象接口为javax.crypto.SecretKey,其算法类型为对称加密算法,对称加密算法的主要特点就是加密与解密用的是同一把密钥,对称加密算法主要有:DES,DESede,AES,Blowfish,RC2,RC4等。下面看一个使用例子:

[java]  view plain copy
  1. package com.xtayfjpk.security;  
  2.   
  3.   
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileOutputStream;  
  7. import java.io.ObjectInputStream;  
  8. import java.io.ObjectOutputStream;  
  9. import java.security.spec.KeySpec;  
  10.   
  11. import javax.crypto.Cipher;  
  12. import javax.crypto.KeyGenerator;  
  13. import javax.crypto.SecretKey;  
  14. import javax.crypto.SecretKeyFactory;  
  15. import javax.crypto.spec.DESKeySpec;  
  16.   
  17. import org.junit.Test;  
  18.   
  19. public class SecretKeyTest {  
  20.     //对称加密算法,Java默认支持的算法有:AES、ARCFOUR、Blowfish、DES、DESede、HmacMD5、  
  21.     //HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512、RC2  
  22.     private static final String ALGORITHM = "DES";  
  23.       
  24.     @Test  
  25.     public void testEncrypt() throws Exception {  
  26.         //获取加/解密器  
  27.         Cipher cipher = Cipher.getInstance(ALGORITHM);  
  28.         //生成秘密密钥  
  29.         SecretKey key = KeyGenerator.getInstance(ALGORITHM).generateKey();  
  30.         //将秘密写入文件中  
  31.         writeSecretKey("xtayfjpk.key", key, false);  
  32.         //加密时,必须初始化为加密模式  
  33.         cipher.init(Cipher.ENCRYPT_MODE, key);  
  34.           
  35.         String myInfo = "我的明文";  
  36.         //加密  
  37.         byte[] results = cipher.doFinal(myInfo.getBytes());  
  38.         writeFile("content.dat", results);  
  39.     }  
  40.       
  41.       
  42.       
  43.     @Test  
  44.     public void testDecrypt() throws Exception {  
  45.         //读取秘密密钥  
  46.         SecretKey key = readSecretKey("xtayfjpk.key"false);  
  47.         //读取加密后的数据  
  48.         byte[] contents = readFile("content.dat");  
  49.         Cipher cipher = Cipher.getInstance(ALGORITHM);  
  50.         //解密时,必须初始化为解密模式  
  51.         cipher.init(Cipher.DECRYPT_MODE, key);  
  52.         //解密,得到明文  
  53.         byte[] origins = cipher.doFinal(contents);  
  54.         System.out.println(new String(origins));  
  55.     }  
  56.       
  57.     /** 读取文件内容至字节数组中 **/  
  58.     public byte[] readFile(String path) throws Exception {  
  59.         FileInputStream cntInput = new FileInputStream(path);  
  60.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  61.         int b = -1;  
  62.         while((b=cntInput.read())!=-1) {  
  63.             baos.write(b);  
  64.         }  
  65.         cntInput.close();  
  66.         byte[] contents = baos.toByteArray();  
  67.         baos.close();  
  68.         return contents;  
  69.     }  
  70.       
  71.     /** 将二进制数据写入文件 **/  
  72.     public void writeFile(String path, byte[] content) throws Exception {  
  73.         FileOutputStream fos = new FileOutputStream(path);  
  74.         fos.write(content);  
  75.         fos.close();  
  76.     }  
  77.       
  78.     public SecretKey readSecretKey(String path, boolean encoded) throws Exception {  
  79.         if(encoded) {  
  80.             byte[] keyData = readFile(path);  
  81.             KeySpec keySpec = new DESKeySpec(keyData);  
  82.             //当读取秘密密钥编码数据时须使用此方式生成秘密密钥  
  83.             //Java文档中虽然明确说明SecretKeyFactory.getInstance支持AES算法,但事实上却不支持(JDK7)  
  84.             SecretKey key = SecretKeyFactory.getInstance(ALGORITHM).generateSecret(keySpec);  
  85.             return key;  
  86.         } else {  
  87.             FileInputStream fis = new FileInputStream(path);  
  88.             ObjectInputStream bis = new ObjectInputStream(fis);  
  89.             Object object = bis.readObject();  
  90.             bis.close();  
  91.             return (SecretKey) object;  
  92.         }  
  93.     }  
  94.       
  95.     /** 秘密密钥写入文件有两种方式,一是利用Java对象的序列化机制,二是获取其编码数据(字节数据)写入文件 **/  
  96.     public void writeSecretKey(String path, SecretKey secretKey, boolean encoded) throws Exception {  
  97.         FileOutputStream fos = new FileOutputStream(path);  
  98.         if(encoded) {  
  99.             fos.write(secretKey.getEncoded());  
  100.             fos.close();  
  101.         } else {  
  102.             ObjectOutputStream oos = new ObjectOutputStream(fos);  
  103.             oos.writeObject(secretKey);  
  104.             oos.close();  
  105.         }  
  106.     }  
  107. }  
 

使用秘密密钥时双方通信过程为,假设为甲乙双方,之前已商定好秘密密钥算法:
1.甲方构建密钥
2.由密钥构建者甲方将密钥公布给乙方
3.消息发送方使用密钥对数据进行加密
4.将加密后的数据发送给消息接收者
5.消息接收者使用密钥对数据进行解密,得到明文
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对称加密算法是一种常用的加密方式,它采用了一对,即公和私。公是公开的,可以任意分发,而私则只能由的所有者持有,用于解加密数据。常见的非对称加密算法包括RSA、DSA、ECC等。 下面是一个使用RSA算法实现非对称加密Java示例代码: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import javax.crypto.Cipher; public class RSAEncryptionExample { public static void main(String[] args) throws Exception { String input = "Hello World!"; KeyPair keyPair = generateRSAKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); byte[] encryptedData = rsaEncrypt(input.getBytes(), publicKey); byte[] decryptedData = rsaDecrypt(encryptedData, privateKey); System.out.println("Original data: " + input); System.out.println("Encrypted data: " + new String(encryptedData)); System.out.println("Decrypted data: " + new String(decryptedData)); } public static KeyPair generateRSAKeyPair() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); // key size KeyPair keyPair = generator.generateKeyPair(); return keyPair; } public static byte[] rsaEncrypt(byte[] data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedData = cipher.doFinal(data); return encryptedData; } public static byte[] rsaDecrypt(byte[] data, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedData = cipher.doFinal(data); return decryptedData; } } ``` 这个示例代码中,我们首先生成了一个RSA对,包括公和私。然后使用公对原始数据进行加密,得到加密后的数据。接着使用私加密后的数据进行解,得到原始数据。 需要注意的是,RSA算法使用的长度越长,安全性就越高,但加解的速度也越慢。在实际应用中,需要根据实际需求和环境选择合适的长度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值