zoukankan      html  css  js  c++  java
  • 将用户输入的信息加密,解密

    加密过程与解密过程使用的密匙是同一个。

    涉及的类:

    1,javax.crypto.KeyGenerator:   public class KeyGenerator  extends Object  ,此类提供(对称)密钥生成器的功能。密钥生成器是使用此类的某个 getInstance 类方法构造的。

      第一步: 获取密匙生成器的具体方法:public static final KeyGenerator getInstance(String algorithm)  throws NoSuchAlgorithmException:为指定算法生成一个 KeyGenerator 对象。如果默认提供程序包提供所请求密钥生成器的实现,则返回包含该实现的 KeyGenerator 实例。如果默认提供程序包中不存在请求的密钥生成器,则搜索其他提供程序包。

    参数:algorithm - 所请求的密钥算法的标准名称。

    Algorithm NameDescription
    AES Key generator for use with the AES algorithm.
    ARCFOUR Key generator for use with the ARCFOUR (RC4) algorithm.
    Blowfish Key generator for use with the Blowfish algorithm.
    DES Key generator for use with the DES algorithm.
    DESede Key generator for use with the DESede (triple-DES) algorithm.
    HmacMD5 Key generator for use with the HmacMD5 algorithm.
    HmacSHA1
    HmacSHA224
    HmacSHA256
    HmacSHA384
    HmacSHA512
    Keys generator for use with the various flavors of the HmacSHA algorithms.
    RC2 Key generator for use with the RC2 algorithm.

    第二步:初始化密匙生成器的长度:public final void init(int keysize) ,初始化此密钥生成器,使其具有确定的密钥长度

    参数:keysize - 密钥长度。这是特定于算法的一种规格,是按位数指定的。

    第三步:生成一个密匙:public final SecretKey generateKey() ,返回新的密匙

    3.2:得到密钥字节码:byte[] getEncoded(),返回基本编码格式的密钥,如果此密钥不支持编码,则返回 null。 

    涉及的类2:javax.crypto  Cipher:public class Cipher extends Object,此类提供了针对加密和解密的密码 cipher 功能。它构成了JCE框架的核心。为创建 Cipher 对象,应用程序调用 Cipher 的 getInstance 方法并将请求的转换 名称(转换始终包括加密算法的名称(例如,DES),后面可能跟有一个反馈模式和填充方案)传递给它。作为可选项,也可以指定提供程序的名称。 

    第四步:创建密码器:public static final Cipher getInstance(String transformation)throws NoSuchAlgorithmException,NoSuchPaddingException,生成一个指定转换的Cipher对象

    参数:transformation - 转换的名称

    Algorithm NameDescription
    AES

    Advanced Encryption Standard as specified by NIST in FIPS 197. Also known as the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits.

    To use the AES cipher with only one valid key size, use the format AES_<n>, where <n> can be 128, 192, or 256.

    AESWrap

    The AES key wrapping algorithm as described in RFC 3394.

    To use the AESWrap cipher with only one valid key size, use the format AESWrap_<n>, where <n> can be 128, 192, or 256.

    ARCFOUR A stream cipher believed to be fully interoperable with the RC4 cipher developed by Ron Rivest. For more information, see K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm 'Arcfour'", Internet Draft (expired), draft-kaukonen-cipher-arcfour-03.txt.
    Blowfish The Blowfish block cipher designed by Bruce Schneier.
    DES The Digital Encryption Standard as described in FIPS PUB 46-3.
    DESede Triple DES Encryption (also known as DES-EDE, 3DES, or Triple-DES). Data is encrypted using the DES algorithm three separate times. It is first encrypted using the first subkey, then decrypted with the second subkey, and encrypted with the third subkey.
    DESedeWrap The DESede key wrapping algorithm as described in RFC 3217 .
    ECIES Elliptic Curve Integrated Encryption Scheme
    PBEWith<digest>And<encryption> PBEWith<prf>And<encryption> The password-based encryption algorithm found in (PKCS5), using the specified message digest (<digest>) or pseudo-random function (<prf>) and encryption algorithm (<encryption>). Examples:
    RC2 Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc.
    RC4 Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. (See note prior for ARCFOUR.)
    RC5 Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc.
    RSA The RSA encryption algorithm as defined in PKCS #1

    加密过程:

    第五步:初始化密码器:public final void init(int opmode,Key key) throws InvalidKeyException ,用密钥初始化此 cipher。,参数填Cipher.ENCRYPT_MODE

    参数:opmode - 此 cipher 的操作模式(其为如下之一:ENCRYPT_MODEDECRYPT_MODEWRAP_MODEUNWRAP_MODEkey - 密钥 

    参数常量 代表含义
    DECRYPT_MODE                用于将密码初始化为解密模式的常数
    ENCRYPT_MODE                         用于将密码初始化为加密模式的常量。
    WRAP_MODE 用于将密码初始化为密钥包装模式的常量
    UNWRAP_MODE 用于初始化密码到密钥展开模式的常量

    5.2:将要加密的内容转编码为UTF8存入byte[]类型的对象中

    第六步:开始加密:public final byte[] doFinal(byte[] input) throws IllegalBlockSizeExceptionBadPaddingException ,按单部分操作加密或解密数据,或者结束一个多部分操作。数据被加密还是解密取决于此 cipher 的初始化方式。参数:要加密的内容对应的byte[]类型的字节码。

    6.2:将加密后的byte[]类型数据转为String类型数据即为加密后的密文

    解密过程:

    第七步:初始化密码器:public final void init(int opmode,Key key) throws InvalidKeyException ,用密钥初始化此 cipher。,参数填Cipher.DECRYPT_MODE

    7.2:将要解密的内容转编码为UTF8存入byte[]类型的对象中

    第八步:开始解密:public final byte[] doFinal(byte[] input) throws IllegalBlockSizeExceptionBadPaddingException ,按单部分操作加密或解密数据,或者结束一个多部分操作。数据被加密还是解密取决于此 cipher 的初始化方式。参数:要解密的内容对应的byte[]类型的字节码

    8.2:将解密后的byte[]类型数据转为String类型数据即为解密后的明文

    运行类:

    package com.lq.test;
    
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) 
        {
            String massage=null;
            JiaMi jiami=new JiaMi();
            JieMi jiemi=new JieMi();
            System.out.println("请输入要加密的内容:
    ");
            Scanner scn=new Scanner(System.in);
            massage=scn.next();
            while(true)
            {
                  System.out.println(".................................
    "+
                               "............请选择操作...........
    "+
                               "...........1,将输入的内容加密....
    "+
                               "...........2,将之前的密文转为明文
    "+
                               ".................................
    ");
            
                int i=scn.nextInt();
                switch (i) 
                {
                case 1:  
                    jiami.Jiami(massage);                
                    break;
                case 2:
                    byte[] miwenbyte=jiami.Jiami(massage);
                    jiemi.Jiemi(miwenbyte);
                    
                    break;
                default:
                    break;
                }
            }
            
        }
    
    }

    加密:

    package com.lq.test;
    
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    
    public class JiaMi 
    {
       public static SecretKey key;
       public static byte[] keybyte;
    public byte[] Jiami(String massege)
       {
           
           String cipherType = "DESede"; //加密类型
           String miwen=null;
           try {
               KeyGenerator keygen=KeyGenerator.getInstance(cipherType);  //获取密匙生成器
               keygen.init(112);   //初始化密钥生成器,不同的加密算法其密钥长度可能不同
               key=keygen.generateKey();   //生成密匙
               keybyte=key.getEncoded();
               System.out.println("密匙是:");
               for(int i=0;i<keybyte.length;i++)
               {
                   System.out.println(keybyte[i]+",");
               }
               System.out.println("");
               Cipher cp=Cipher.getInstance(cipherType);  //创建密码器
               cp.init(Cipher.ENCRYPT_MODE,key);   //初始化密码器
               System.out.println("要加密的内容是:"+massege);
               byte[] massagebyte=massege.getBytes("UTF8");
               System.out.println("要加密的内容对应的字节码:");
               for(int i=0;i<massagebyte.length;i++)
               {
                   System.out.println(massagebyte[i]+",");
               }
               System.out.println("");
               // 开始加密
               byte[] miwenbyte=cp.doFinal(massagebyte);
               System.out.println("加密后对应的字节码:");
               for(int i=0;i<miwenbyte.length;i++)
               {
                   System.out.println(miwenbyte[i]+",");
               }
               System.out.println("");
               miwen=new String(miwenbyte);
               System.out.println("加密后的密文为:");
               System.out.println(miwen);        
               return miwenbyte;
           }
           catch(Exception e)
           {
               e.printStackTrace();
               return null;
           }
       }
    }

    解密:

    package com.lq.test;
    
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    
    public class JieMi 
    {
        public void Jiemi(byte[] miwenbyte)
        {
            JiaMi jiami=new JiaMi();
            String minwen=null;
            String cipherType = "DESede";
            try {
                KeyGenerator keygen=KeyGenerator.getInstance(cipherType);  //获取密匙生成器
                keygen.init(112);   //初始化密钥生成器,不同的加密算法其密钥长度可能不同
                SecretKey key=jiami.key;   //生成密匙
                byte[] keybyte=jiami.keybyte;
                System.out.println("密匙是:");
                for(int i=0;i<keybyte.length;i++)
                {
                    System.out.println(keybyte[i]+",");
                }
                System.out.println("");
                Cipher cp=Cipher.getInstance(cipherType);  //创建密码器
                cp.init(Cipher.DECRYPT_MODE, key);
                byte[] minwenbyte=cp.doFinal(miwenbyte);
                System.out.println("解密后明文对应的字节码:");
                for(int i=0;i<minwenbyte.length;i++)
                {
                    System.out.println(minwenbyte[i]+",");
                }
                System.out.println("");
                minwen=new String(minwenbyte);
                System.out.println("解密后的明文为:"+minwen);
                System.out.println("");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    [LeetCode179]Largest Number
    [LeetCode27]Remove Element
    [LeetCode238]Product of Array Except Self
    [LeetCode169]Majority Element求一个数组中出现次数大于n/2的数
    [LeetCode202]Happy Number判断一个数是不是happy number
    [LeetCode283]Move Zeros将一个数组中为0的元素移至数组末尾
    [LeetCode136]Single Number寻找一个数组里只出现一次的数
    iOS 9: UIStackView入门
    优化UITableViewCell高度计算的那些事
    AutoLayout深入浅出五[UITableView动态高度]
  • 原文地址:https://www.cnblogs.com/lq13035130506/p/11727953.html
Copyright © 2011-2022 走看看