对数据库用户名和密码加密

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fhf2424045058/article/details/84869975
package com.ai.util;

import java.security.Key;
import java.security.SecureRandom;
import java.util.Scanner;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Encoder;

public class EnUPUtils {
	private static Key key;
	private static String KEY_STR = "myKeyRyanCai";// 密钥
	private static String CHARSETNAME = "UTF-8";// 编码
	private static String ALGORITHM = "DES";// 加密类型
	static {
		try {
			KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
			generator.init(new SecureRandom(KEY_STR.getBytes()));
			key = generator.generateKey();
			generator = null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) {
		String username = "用户名";
		input(username);
		String psw = "密码";
		input(psw);
	}

	public static void input(String str){
		BASE64Encoder base64encoder = new BASE64Encoder();
		byte[] doFinal;
		
			System.out.println("请输入"+str+":");
			Scanner scan=new Scanner(System.in);
			String inputstr=scan.nextLine();
			
			System.out.println("需要加密的"+str+"是:"+inputstr);
			try {
				byte[] bytes = inputstr.getBytes(CHARSETNAME);
				Cipher cipher = Cipher.getInstance(ALGORITHM);
				cipher.init(Cipher.ENCRYPT_MODE, key);
				doFinal = cipher.doFinal(bytes);
				System.out.println(inputstr+"经过加密后,"+str+"是:"+base64encoder.encode(doFinal));
			} catch (Exception e) {
				throw new RuntimeException(e);
			}	
		
		
	}
}

在这里插入图片描述

还有一种加密的API,但是需要外部的jar包,不是java自带的,所以不方便,需要引入外部的commons-codec-1.9.jar,在cmd无法使用,java代码是:

package com.ai.util;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;

public class base64utils {
	public static void main(String[] args) {
		String str = "Hello World";   
        String str2 = base64utils.base64encode(str);  
        System.out.println(str2);  
        String str1 = base64utils.base64decode(str2);  
        System.out.println(str1); 
	}
	 public static String base64encode(String message) {  
	        try {  
	            byte[] encodeBase64 = Base64.encodeBase64(message.getBytes("UTF-8"));  
	            System.out.println("加密:Result:" + new String(encodeBase64));  
	            return new String(encodeBase64);  
	        } catch (UnsupportedEncodingException e) {  
	            throw new RuntimeException();  
	        }  
	  
	    }  
	      
	    public static String base64decode(String message) {  
	        byte[] encodeBase64 = Base64.decodeBase64(message);  
	        System.out.println("解密:Result:" + new String(encodeBase64));  
	        return new String(encodeBase64);  
	  
	    }  
}

错误:无法编译

在这里插入图片描述

所以采用第一种方法

猜你喜欢

转载自blog.csdn.net/fhf2424045058/article/details/84869975