zoukankan      html  css  js  c++  java
  • java安全对称加密

    加密不多说了,无非就是拿钥匙开门,现在先看看对称加密,就是一把锁,锁上门是这把钥匙,开门还是这把钥匙

    1 import javax.crypto.Cipher;
    2  import javax.crypto.KeyGenerator;
    3 import javax.crypto.SecretKey;
    4
    5 public class SecretKeyTest {
    6
    7 public static void main(String[] args) throws Exception {
    8
    9 // 加密类,只能通过类自带的getInstance静态方法获得对象
    10 Cipher cipher = Cipher.getInstance("AES");// 加密算法
    11
    12 // 创建一个密钥,可以看到SecretKey是个接口,通过KeyGenerator这个发生器获得
    13 SecretKey key = KeyGenerator.getInstance("AES").generateKey();
    14
    15 // 初始化为加密模式,密钥是刚才创建的密钥
    16 cipher.init(Cipher.ENCRYPT_MODE, key);
    17
    18 // update是加密缓冲区内容,这里方便配合输入流加密
    19 cipher.update("aaa".getBytes());
    20 cipher.update("bbb".getBytes());
    21
    22 // 取得加密后的结果
    23 byte[] eresults = cipher.doFinal();
    24 //这里是直接加密运算
    25 // byte[] eresults =cipher.doFinal("aaabbb".getBytes());
    26
    27 // 将加密的结果格式化为字符串
    28 String result = new String(eresults);
    29 System.out.println(result);
    30
    31 // 初始化为解密模式,密钥是加密时使用的key
    32 cipher.init(Cipher.DECRYPT_MODE, key);
    33
    34 // 取得解密后的结果
    35 byte[] dresults = cipher.doFinal(eresults);
    36 result = new String(dresults);
    37
    38 System.out.println(result);
    39 }
    40 }

    -----待续

  • 相关阅读:
    R语言修改vector、matrix、dataframe列名
    R语言获取数据框的行数
    R语言的which函数,针对没有符合条件的返回值为integer(0),之后如何判断
    ArrayList总结
    经常涉及到的技术
    今天开始写博客啦!(测试..)
    [摘转] JS 数组合并问题
    t_category
    在 MySql 的 update 语句中使用 case when else end
    JSP 取当前时间
  • 原文地址:https://www.cnblogs.com/hangxin1940/p/2059988.html
Copyright © 2011-2022 走看看