AES 대칭 암호화의 간단한 예

2687 단어 java 암호화
긴 말 없이 코드에 직접 올리고 대칭 암호화는 키가 하나뿐입니다.그로 암호화하고, 그것으로 복호화하다.
package com.example.shirotest.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

public class AESKeyPairUtils {
    public static void main(String[] args) {
        String content = "www.baidu.com";
        String password = "123";
        System.out.println("    :" + content);

        //   
        byte[] encrypt = AESKeyPairUtils.encrypt(content, password);
        System.out.println("      :" + new String(encrypt));

        //   
        String msg = AESKeyPairUtils.decrypt(encrypt, password);
        System.out.println("      :" + new String(msg));
    }

    /**
     * AES     
     * @param content          
     * @param password        
     * @return      
     */
    public static byte[] encrypt(String content,String password){
        try {
            SecretKeySpec secretKeySpec = getSecretKeySpec(password);
            Cipher cipher = Cipher.getInstance("AES");//     
            cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
            byte[] bytes = cipher.doFinal(content.getBytes("UTF-8"));
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(byte[] content,String password){
        String msg = "";
        try {
            SecretKeySpec secretKeySpec = getSecretKeySpec(password);
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);
            byte[] bytes = cipher.doFinal(content);
            msg = new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    /**
     *   cipher
     * @param password   
     * @return
     */
    public static SecretKeySpec getSecretKeySpec(String password){
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128,new SecureRandom(password.getBytes()));
            SecretKey secretKey = keyGenerator.generateKey();
            System.out.println("secretkey:"+ Base64.encodeBase64String(secretKey.getEncoded()));
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(),"AES");
            return secretKeySpec;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

좋은 웹페이지 즐겨찾기