Java实现RC4加密算法、RSA算法、MD5算法

94 篇文章 0 订阅
158 篇文章 2 订阅

使用Java实现RC4算法

      使用RC加密算法,S盒

调用接口:RC4Encrypt.getkeyToPWD(inputStr));
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
*作者:渴望飞的鱼
 * 加密算法:RC4加密
 * 调用: String str = RC4Encrypt.getkeyToPWD(inputStr);  inputStr是密码,即可返回str加密以后的密文
 * 返回的str则是已经加密以后的密码
 *
 */
public class RC4Encrypt {
	public RC4Encrypt(){
		//构造方法,加载密钥		    
	}
	public  String HloveyRC4(String aInput,String aKey){   
		//机密S盒的核心算法
        int[] iS = new int[256];   
        byte[] iK = new byte[256];   
        for (int i=0;i<256;i++)   
            iS[i]=i;           //256个数字   
        int j = 1;             //整数 
        for (short i= 0;i<256;i++){   
        	//
            iK[i]=(byte)aKey.charAt((i % aKey.length()));   
        }   
        j=0;   
        for (int i=0;i<255;i++){   
            j=(j+iS[i]+iK[i]) % 256;   
            int temp = iS[i];   
            iS[i]=iS[j];   
            iS[j]=temp;   
        }   
        int i=0;   
        j=0;   
        char[] iInputChar = aInput.toCharArray();   
        char[] iOutputChar = new char[iInputChar.length];   
        for(short x = 0;x
     
     


使用Java实现RSA算法

使用RSA加密算法,对密文、文件加密

package com.hh.rsa.filter;

import java.io.IOException;
import java.util.Locale;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

/**
 * 
 * @author HH
 *
 */
public class MyFilter extends OncePerRequestFilter {

	/** Default method parameter: {@code _method} */
	public static final String DEFAULT_METHOD_PARAM = "_method";

	private String methodParam = DEFAULT_METHOD_PARAM;


	/**
	 * Set the parameter name to look for HTTP methods.
	 * @see #DEFAULT_METHOD_PARAM
	 */
	public void setMethodParam(String methodParam) {
		Assert.hasText(methodParam, "'methodParam' must not be empty");
		this.methodParam = methodParam;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		HttpServletRequest requestToUse = request;
		requestToUse.setCharacterEncoding("UTF-8");
		if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
			String paramValue = request.getParameter(this.methodParam);
			if (StringUtils.hasLength(paramValue)) {
				requestToUse = new HttpMethodRequestWrapper(request, paramValue);
			}
		}

		filterChain.doFilter(requestToUse, response);
	}


	/**
	 * Simple {@link HttpServletRequest} wrapper that returns the supplied method for
	 * {@link HttpServletRequest#getMethod()}.
	 */
	private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {

		private final String method;

		public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
			super(request);
			this.method = method.toUpperCase(Locale.ENGLISH);
		}

		@Override
		public String getMethod() {
			return this.method;
		}
	}

}
package com.hh.rsa.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Map;

import com.hh.rsa.util.RSAUtil;

/**
 * 
 * @author 黄卉
 *
 */
public class RSATest {
    static String publicKey;    //声明公钥
    static String privateKey;   //声明私钥
    
    
    //通过文件读取路径,对文件文字进行加密
    public static void ReadAndAddRSAToFile(String filePath) throws Exception{
    	//File file=new File("D:\\学习笔记区\\文件测试1.txt");
    	File file=new File(filePath);
    	System.out.println("判断文件是否存在,file.exists:"+file.exists());
    	if(!file.exists()){
    		System.out.println("文件不已经存在!");
    	}
    	else{
    		System.out.println();
    		System.out.println("文件已经存在,开始读取加密,请稍后......");
    		RandomAccessFile raf=new RandomAccessFile(file,"rw");
    		byte[] byt=new byte[(int)raf.length()];
    		raf.read(byt);
    		String ss=new String(byt);  //获取文件内容
    		System.out.println(ss); //打印文件内容
    		
    		
    		//对文件进行加密
    		byte[] toPublicKeyText=testRSAByPublicKeyJiaMi(ss);
    		System.out.println("文件使用公钥加密后的文字: "+new String(toPublicKeyText));
    		
    		
    	
    		//写到新的文档
    		File file2=new File(file.getAbsolutePath()+"加密后版本.txt");
    		RandomAccessFile raf2=new RandomAccessFile(file2,"rw");
    	    raf2.write(new String(toPublicKeyText).getBytes("gbk"));
    	    System.out.println(raf.getFilePointer());
    	    
    	    raf2.close();
    	    raf.close();//关闭 
    	   //(2)通过私钥进行文字解密
    	   String theString=new String(testRSAByPrivateKeyJieMi(toPublicKeyText));
    	   System.out.println("文件使用私钥解密后的文字"+theString);          
    	}  	
    }
    
    //通过文件读取路径,对文件解密
    public static void jieMiFile(String filePath) throws Exception{
    	//File file=new File("D:\\学习笔记区\\文件测试1.txt");
    	File file=new File(filePath);
    	System.out.println("判断文件是否存在,file.exists:"+file.exists());
    	if(!file.exists()){
    		System.out.println("文件不已经存在!");
    	}
    	else{
    		System.out.println();
    		System.out.println("文件已经存在,开始读取,请稍后......");
    		RandomAccessFile raf=new RandomAccessFile(file,"rw");
    		byte[] byt=new byte[(int)raf.length()];
    		raf.read(byt);
    		String ss=new String(byt);  //获取文件内容
    		System.out.println(ss); //打印文件内容
    		
    		
    		//对文件进行解密
    		   String theString=new String(testRSAByPrivateKeyJieMi(byt));
        	   System.out.println("文件使用私钥解密后的文字"+theString);   
    	
    		//写到新的文档
    		File file2=new File(file.getAbsolutePath()+"解密后版本.txt");
    		RandomAccessFile raf2=new RandomAccessFile(file2,"rw");
    	    raf2.write(new String(theString.trim()).getBytes("gbk"));
    	    System.out.println(raf.getFilePointer());
    	    
    	    raf2.close();
    	    raf.close();//关闭 
    	 
    	       
    	}  	
    }
    
    
    
    
    //调用方法
	public static void main(String[] args) throws Exception {
        getKey();    //获得公钥和私钥的密钥
        //   test(source);    //对输入的文字进行使用公钥加密,使用私钥解密
        //(1)通过公钥进行文字加密
        String source = "这是测试一:在这里输入测试文字!输入测试加密文字";  
        byte[] toPublicKeyText=testRSAByPublicKeyJiaMi(source);
        System.out.println("main:加密后的文字: "+new String(toPublicKeyText));
      
        //(2)通过私钥进行文字解密
       String theString=new String(testRSAByPrivateKeyJieMi(toPublicKeyText));
        System.out.println("main:解密后的文字"+theString);
        
        
    
      //(3)进行数字签名 :私钥加密,私钥签名  ——公钥验证签名 ,公钥解密   
       // testSign();    //数字签名功能    
//        //(1)通过私钥加密
        String source3 = "数字签名测试,先对文字进行私钥加密。并在加密后使用数字签名";
        byte[] toPublicKeyText3=testRSAByPrivatyJiaMi(source3);
//        //(2)通过私钥签名
        String sign=testSignPrivateKeyBySign(toPublicKeyText3);//通过私钥签名后
        System.out.println("签名后的sign:"+sign);
//        //(3)通过公钥验证 签名是否正确
        boolean flag= isRightOrFalseSign(toPublicKeyText3,sign);
        if(flag){//验证成功,通过公钥验证签名
               //           (4)通过私钥解密
        	 String source4=	testSignPublicKeyBySignJieMI(toPublicKeyText3);
        	 System.out.println("通过公钥解密后:"+source4);
        }
        
        System.out.println("----文件读取区域------");
     //   ReadAndAddRSAToFile("D:\\学习笔记区\\文件测试3.txt");
        
        
       
	}
	

	
	
	/**
	 * @author 黄卉
	 * @time 2017年6月24日
	 * @param null
	 * @return  null
	 * 获取公钥和私钥
	 */
	 public static void getKey(){  
		 //获得公钥和私钥的密钥的方法
         try {  
        	 
             Map
      
      
       
        keyMap = RSAUtil.genKeyPair();  
             publicKey = RSAUtil.getPublicKey(keyMap);  
             privateKey = RSAUtil.getPrivateKey(keyMap);  
             //输出打印公钥和私钥
             System.out.println("公钥: \n" + publicKey);  
             System.out.println("私钥: \n" + privateKey);  
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
    }  
      
	/**
	 * @author 黄卉
	 * @time 2017年6月25日
	 * @param 需要加密的文字
	 * @return  返回通过公钥加密后的文字
	 * @throws Exception
	 */
	 public static  byte[] testRSAByPublicKeyJiaMi(String source) throws Exception{
		 System.out.println("==============testRSAByPublicKey方法============================");  
	        System.out.println("Test1:公钥加密——>私钥解密");  
	        System.out.println("加密前文字: " + source);    //输入加密文字
	        byte[] data = source.getBytes();  //转换
	        byte[] encodedData = RSAUtil.encryptByPublicKey(data, publicKey);   //调用公钥加密方法加密
	   //     String resultText=new String(encodedData);
	      //  System.out.println("通过公钥加密后文字:\r\n" + resultText);  
	        //把公钥加密后的文字解密
	        return encodedData;
	 }
	 
	 
	 public static  byte[] testRSAByPrivatyJiaMi(String source) throws Exception{
		 System.out.println("==============testRSAByPrivaty私钥加密方法============================");  
	        System.out.println("Test1:私钥加密——>公钥解密");  
	        System.out.println("加密前文字: " + source);    //输入加密文字
	        byte[] data = source.getBytes();  //转换
	        byte[] encodedData = RSAUtil.encryptByPrivateKey(data, privateKey);   //调用私钥机密
	        String resultText=new String(encodedData);
	       System.out.println("通过私钥加密后文字:\r\n" + resultText);  
	        //把公钥加密后的文字解密
	        return encodedData;
	 }
	 
	 /**
		 * @author 黄卉
		 * @time 2017年6月25日
		 * @param 已经用公钥加密后需要使用私钥解密的文字
		 * @return  返回私钥解密的文字
		 * @throws Exception
		 */
	    
	 public static  byte[] testRSAByPrivateKeyJieMi(byte[]  encodedData) throws Exception{
		 System.out.println("==============testRSAByPrivateKey方法============================");  
	     System.out.println("Test1:——>私钥解密"); 
	 
	     byte[] decodedData = RSAUtil.decryptByPrivateKey(encodedData, privateKey);  
	     String target = new String(decodedData);  
	     System.out.println("解密后文字: \r\n" + target); 
         return decodedData;
	 }
	 
	   /**
	     * 验证签名成功后公钥解密
	  	 * @author 黄卉
	  	 * @time 2017年6月25日
	  	 * @param 
	  	 * @return  
	  	 * @throws Exception
	  	 */
	    public static String testSignPublicKeyBySignJieMI(byte[] encodedData) throws Exception {  
	    	//通过公钥解密
	    	   System.out.println("公钥解密");  
	           byte[] decodedData = RSAUtil.decryptByPublicKey(encodedData, publicKey);  
	           String target = new String(decodedData);  
	           System.out.println("解密后: \r\n" + target);  
	           return target;
	   }
    
    /**
	 * @author 黄卉
	 * @time 2017年6月25日
	 * @param 对使用公钥加密后的文字进行签名
	 * @return  返回公钥加密后 并通过  数字签名后的文字
	 * @throws Exception
	 */
    
    public static String testSignPrivateKeyBySign(byte[] encodedData) throws Exception {  
    	//通过私钥进行签名
    	 System.out.println("私钥签名");  
         String sign = RSAUtil.sign(encodedData, privateKey);  
         System.out.println("签名:\r" + sign);  
         System.out.println("====================================================");  
        
		return sign;
    }
    
    /**
     * 验证签名是否正确
  	 * @author 黄卉
  	 * @time 2017年6月25日
  	 * @param 
  	 * @return  
  	 * @throws Exception
  	 */    
    public  static boolean isRightOrFalseSign(byte[] encodedData,String sign) throws Exception { 
    	//判断验证签名是否一致
    	 System.out.println("====================================================");  
         System.out.println("公钥验签");  
         boolean status = RSAUtil.verify(encodedData, publicKey, sign);  
         System.out.println("验证结果:" + status);  
         return status;
    }
    
 
   
    
    //混合测试
    public static void test(String source) throws Exception {  
        System.out.println("====================================================");  
        System.out.println("Test1:公钥加密——>私钥解密");  
        System.out.println("加密前文字:\r\n" + source);    //输入加密文字
        byte[] data = source.getBytes();  //转换
        byte[] encodedData = RSAUtil.encryptByPublicKey(data, publicKey);   //调用公钥加密方法加密
        
        System.out.println("通过公钥加密后文字:\r\n" + new String(encodedData));  
        //把公钥加密后的文字解密
        byte[] decodedData = RSAUtil.decryptByPrivateKey(encodedData, privateKey);  
       String target = new String(decodedData);  
        System.out.println("解密后文字: \r\n" + target);  
        System.out.println("============完成加密解密==================================");  
    }  
  
    
    
    static void testSign() throws Exception {  
        System.out.println("Test2:私钥加密签名——>公钥验签解密");  
        String source = "这是测试二:傻瓜卉在上课的时候居然玩手机!";  
        System.out.println("加密签名前文字:\r\n" + source);  
        System.out.println("私钥加密");  
        byte[] data = source.getBytes();  
        byte[] encodedData = RSAUtil.encryptByPrivateKey(data, privateKey);  
        System.out.println("加密后:\r\n" + new String(encodedData));  
        System.out.println("私钥签名");  
        String sign = RSAUtil.sign(encodedData, privateKey);  
        System.out.println("签名:\r" + sign);  
        System.out.println("====================================================");  
        System.out.println("公钥验签");  
        boolean status = RSAUtil.verify(encodedData, publicKey, sign);  
        System.out.println("验证结果:" + status);  
        System.out.println("公钥解密");  
        byte[] decodedData = RSAUtil.decryptByPublicKey(encodedData, publicKey);  
        String target = new String(decodedData);  
        System.out.println("解密后: \r\n" + target);  
    }  

}
package com.hh.rsa.util;
/**
 * 
 * @author 渴望飞的鱼
 *
 */
public class Base64Coder {
	 private static final String systemLineSeparator = System.getProperty("line.separator");  
	  
	    // Mapping table from 6-bit nibbles to Base64 characters.  
	    private static final char[] map1 = new char[64];  
	    static {  
	        int i = 0;  
	        for (char c = 'A'; c <= 'Z'; c++)  
	            map1[i++] = c;  
	        for (char c = 'a'; c <= 'z'; c++)  
	            map1[i++] = c;  
	        for (char c = '0'; c <= '9'; c++)  
	            map1[i++] = c;  
	        map1[i++] = '+';  
	        map1[i++] = '/';  
	    }  
	  
	    // Mapping table from Base64 characters to 6-bit nibbles.  
	    private static final byte[] map2 = new byte[128];  
	    static {  
	        for (int i = 0; i < map2.length; i++)  
	            map2[i] = -1;  
	        for (int i = 0; i < 64; i++)  
	            map2[map1[i]] = (byte) i;  
	    }  
	  
	    /** 
	     * Encodes a string into Base64 format. No blanks or line breaks are 
	     * inserted. 
	     *  
	     * @param s 
	     *            A String to be encoded. 
	     * @return A String containing the Base64 encoded data. 
	     */  
	    public static String encodeString(String s) {  
	        return new String(encode(s.getBytes()));  
	    }  
	  
	    /** 
	     * Encodes a byte array into Base 64 format and breaks the output into lines 
	     * of 76 characters. This method is compatible with 
	     * 
       
       sun.misc.BASE64Encoder.encodeBuffer(byte[]). 
	     *  
	     * @param in 
	     *            An array containing the data bytes to be encoded. 
	     * @return A String containing the Base64 encoded data, broken into lines. 
	     */  
	    public static String encodeLines(byte[] in) {  
	        return encodeLines(in, 0, in.length, 76, systemLineSeparator);  
	    }  
	  
	    /** 
	     * Encodes a byte array into Base 64 format and breaks the output into 
	     * lines. 
	     *  
	     * @param in 
	     *            An array containing the data bytes to be encoded. 
	     * @param iOff 
	     *            Offset of the first byte in 
       
       in to be processed. 
	     * @param iLen 
	     *            Number of bytes to be processed in 
       
       in, starting 
	     *            at 
       
       iOff. 
	     * @param lineLen 
	     *            Line length for the output data. Should be a multiple of 4. 
	     * @param lineSeparator 
	     *            The line separator to be used to separate the output lines. 
	     * @return A String containing the Base64 encoded data, broken into lines. 
	     */  
	    public static String encodeLines(byte[] in, int iOff, int iLen,  
	            int lineLen, String lineSeparator) {  
	        int blockLen = (lineLen * 3) / 4;  
	        if (blockLen <= 0)  
	            throw new IllegalArgumentException();  
	        int lines = (iLen + blockLen - 1) / blockLen;  
	        int bufLen = ((iLen + 2) / 3) * 4 + lines * lineSeparator.length();  
	        StringBuilder buf = new StringBuilder(bufLen);  
	        int ip = 0;  
	        while (ip < iLen) {  
	            int l = Math.min(iLen - ip, blockLen);  
	            buf.append(encode(in, iOff + ip, l));  
	            buf.append(lineSeparator);  
	            ip += l;  
	        }  
	        return buf.toString();  
	    }  
	  
	    /** 
	     * Encodes a byte array into Base64 format. No blanks or line breaks are 
	     * inserted in the output. 
	     *  
	     * @param in 
	     *            An array containing the data bytes to be encoded. 
	     * @return A character array containing the Base64 encoded data. 
	     */  
	    public static char[] encode(byte[] in) {  
	        return encode(in, 0, in.length);  
	    }  
	  
	    /** 
	     * Encodes a byte array into Base64 format. No blanks or line breaks are 
	     * inserted in the output. 
	     *  
	     * @param in 
	     *            An array containing the data bytes to be encoded. 
	     * @param iLen 
	     *            Number of bytes to process in 
       
       in. 
	     * @return A character array containing the Base64 encoded data. 
	     */  
	    public static char[] encode(byte[] in, int iLen) {  
	        return encode(in, 0, iLen);  
	    }  
	  
	    /** 
	     * Encodes a byte array into Base64 format. No blanks or line breaks are 
	     * inserted in the output. 
	     *  
	     * @param in 
	     *            An array containing the data bytes to be encoded. 
	     * @param iOff 
	     *            Offset of the first byte in 
       
       in to be processed. 
	     * @param iLen 
	     *            Number of bytes to process in 
       
       in, starting at 
	     *            
       
       iOff. 
	     * @return A character array containing the Base64 encoded data. 
	     */  
	    public static char[] encode(byte[] in, int iOff, int iLen) {  
	        int oDataLen = (iLen * 4 + 2) / 3; // output length without padding  
	        int oLen = ((iLen + 2) / 3) * 4; // output length including padding  
	        char[] out = new char[oLen];  
	        int ip = iOff;  
	        int iEnd = iOff + iLen;  
	        int op = 0;  
	        while (ip < iEnd) {  
	            int i0 = in[ip++] & 0xff;  
	            int i1 = ip < iEnd ? in[ip++] & 0xff : 0;  
	            int i2 = ip < iEnd ? in[ip++] & 0xff : 0;  
	            int o0 = i0 >>> 2;  
	            int o1 = ((i0 & 3) << 4) | (i1 >>> 4);  
	            int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);  
	            int o3 = i2 & 0x3F;  
	            out[op++] = map1[o0];  
	            out[op++] = map1[o1];  
	            out[op] = op < oDataLen ? map1[o2] : '=';  
	            op++;  
	            out[op] = op < oDataLen ? map1[o3] : '=';  
	            op++;  
	        }  
	        return out;  
	    }  
	  
	    /** 
	     * Decodes a string from Base64 format. No blanks or line breaks are allowed 
	     * within the Base64 encoded input data. 
	     *  
	     * @param s 
	     *            A Base64 String to be decoded. 
	     * @return A String containing the decoded data. 
	     * @throws IllegalArgumentException 
	     *             If the input is not valid Base64 encoded data. 
	     */  
	    public static String decodeString(String s) {  
	        return new String(decode(s));  
	    }  
	  
	    /** 
	     * Decodes a byte array from Base64 format and ignores line separators, tabs 
	     * and blanks. CR, LF, Tab and Space characters are ignored in the input 
	     * data. This method is compatible with 
	     * 
       
       sun.misc.BASE64Decoder.decodeBuffer(String). 
	     *  
	     * @param s 
	     *            A Base64 String to be decoded. 
	     * @return An array containing the decoded data bytes. 
	     * @throws IllegalArgumentException 
	     *             If the input is not valid Base64 encoded data. 
	     */  
	    public static byte[] decodeLines(String s) {  
	        char[] buf = new char[s.length()];  
	        int p = 0;  
	        for (int ip = 0; ip < s.length(); ip++) {  
	            char c = s.charAt(ip);  
	            if (c != ' ' && c != '\r' && c != '\n' && c != '\t')  
	                buf[p++] = c;  
	        }  
	        return decode(buf, 0, p);  
	    }  
	  
	    /** 
	     * Decodes a byte array from Base64 format. No blanks or line breaks are 
	     * allowed within the Base64 encoded input data. 
	     *  
	     * @param s 
	     *            A Base64 String to be decoded. 
	     * @return An array containing the decoded data bytes. 
	     * @throws IllegalArgumentException 
	     *             If the input is not valid Base64 encoded data. 
	     */  
	    public static byte[] decode(String s) {  
	        return decode(s.toCharArray());  
	    }  
	  
	    /** 
	     * Decodes a byte array from Base64 format. No blanks or line breaks are 
	     * allowed within the Base64 encoded input data. 
	     *  
	     * @param in 
	     *            A character array containing the Base64 encoded data. 
	     * @return An array containing the decoded data bytes. 
	     * @throws IllegalArgumentException 
	     *             If the input is not valid Base64 encoded data. 
	     */  
	    public static byte[] decode(char[] in) {  
	        return decode(in, 0, in.length);  
	    }  
	  
	    /** 
	     * Decodes a byte array from Base64 format. No blanks or line breaks are 
	     * allowed within the Base64 encoded input data. 
	     *  
	     * @param in 
	     *            A character array containing the Base64 encoded data. 
	     * @param iOff 
	     *            Offset of the first character in 
       
       in to be 
	     *            processed. 
	     * @param iLen 
	     *            Number of characters to process in 
       
       in, starting 
	     *            at 
       
       iOff. 
	     * @return An array containing the decoded data bytes. 
	     * @throws IllegalArgumentException 
	     *             If the input is not valid Base64 encoded data. 
	     */  
	    public static byte[] decode(char[] in, int iOff, int iLen) {  
	        if (iLen % 4 != 0)  
	            throw new IllegalArgumentException(  
	                    "Length of Base64 encoded input string is not a multiple of 4.");  
	        while (iLen > 0 && in[iOff + iLen - 1] == '=')  
	            iLen--;  
	        int oLen = (iLen * 3) / 4;  
	        byte[] out = new byte[oLen];  
	        int ip = iOff;  
	        int iEnd = iOff + iLen;  
	        int op = 0;  
	        while (ip < iEnd) {  
	            int i0 = in[ip++];  
	            int i1 = in[ip++];  
	            int i2 = ip < iEnd ? in[ip++] : 'A';  
	            int i3 = ip < iEnd ? in[ip++] : 'A';  
	            if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)  
	                throw new IllegalArgumentException(  
	                        "Illegal character in Base64 encoded data.");  
	            int b0 = map2[i0];  
	            int b1 = map2[i1];  
	            int b2 = map2[i2];  
	            int b3 = map2[i3];  
	            if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)  
	                throw new IllegalArgumentException(  
	                        "Illegal character in Base64 encoded data.");  
	            int o0 = (b0 << 2) | (b1 >>> 4);  
	            int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2);  
	            int o2 = ((b2 & 3) << 6) | b3;  
	            out[op++] = (byte) o0;  
	            if (op < oLen)  
	                out[op++] = (byte) o1;  
	            if (op < oLen)  
	                out[op++] = (byte) o2;  
	        }  
	        return out;  
	    }  
	  
	    // Dummy constructor.  
	    private Base64Coder() {  
	    }  
}
package com.hh.rsa.util;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

public class RSAUtil {
	 /** *//** 
     * 加密算法RSA 
     */  
    public static final String KEY_ALGORITHM = "RSA";  
      
    /** *//** 
     * 签名算法 
     */  
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";  
  
    /** *//** 
     * 获取公钥的key 
     */  
    private static final String PUBLIC_KEY = "RSAPublicKey";  
      
    /** *//** 
     * 获取私钥的key 
     */  
    private static final String PRIVATE_KEY = "RSAPrivateKey";  
      
    /** *//** 
     * RSA最大加密明文大小 
     */  
    private static final int MAX_ENCRYPT_BLOCK = 117;  
      
    /** *//** 
     * RSA最大解密密文大小 
     */  
    private static final int MAX_DECRYPT_BLOCK = 128;  
  
    /** *//** 
     * 
       
       

* 生成密钥对(公钥和私钥) *

* * @return * @throws Exception */ public static Map genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map keyMap = new HashMap (2); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** *//** *

* 用私钥对信息生成数字签名 *

* * @param data 已加密数据 * @param privateKey 私钥(BASE64编码) * * @return * @throws Exception */ //对已经通过公钥加密的数据进行签名 public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64Coder.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //RSA加密算法 PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); //签名 signature.initSign(privateK); signature.update(data); return new String(Base64Coder.encode(signature.sign())); } /** *//** *

* 校验数字签名 *

* * @param data 已加密数据 * @param publicKey 公钥(BASE64编码) * @param sign 数字签名 * * @return * @throws Exception * */ public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { byte[] keyBytes = Base64Coder.decode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicK = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicK); signature.update(data); return signature.verify(Base64Coder.decode(sign)); } /** *//** *

* 私钥解密 *

* * @param encryptedData 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64Coder.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); //获得私钥 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** *//** *

* 公钥解密 *

* * @param encryptedData 已加密数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64Coder.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** *//** *

* 公钥加密 *

* * @param data 源数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64Coder.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; //总长 ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; //0 byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } /** *//** *

* 私钥加密 *

* * @param data 源数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64Coder.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } //返回 byte[] encryptedData = out.toByteArray(); out.close(); //关闭 return encryptedData; } /** *//** *

* 获取私钥 *

* * @param keyMap 密钥对 * @return * @throws Exception */ public static String getPrivateKey(Map keyMap) throws Exception { Key key = (Key) keyMap.get(PRIVATE_KEY); return new String(Base64Coder.encode(key.getEncoded())); } /** *//** *

* 获取公钥 *

* * @param keyMap 密钥对 * @return * @throws Exception */ public static String getPublicKey(Map keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return new String(Base64Coder.encode(key.getEncoded())); } } package com.hh.rsa.handler; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.hh.rsa.test.RSATest; /** * @author 渴望飞的鱼 * @version 创建时间:2017年6月25日 下午8:03:24 * @introduction RSA加密系统 */ @Controller @RequestMapping("/RSAController") public class RSAController { //(一)公钥加密,私钥解密 @RequestMapping(value="/setToPubliKeyToPrivateKey",method=RequestMethod.POST) public String setToPubliKeyToPrivateKey(@RequestParam("usertext") String usertext,Map map) throws Exception{ System.out.println("进入方法"); System.out.println("usertext:"+usertext); RSATest.getKey(); //获得公钥和私钥的密钥 //(1)通过公钥进行文字加 byte[] toPublicKeyText=RSATest.testRSAByPublicKeyJiaMi(usertext.trim()); String publickeyjiamihou=new String(toPublicKeyText); System.out.println("main:加密后的文字: "+new String(toPublicKeyText)); //(2)通过私钥进行文字解密 String privatekeyjiemi=new String(RSATest.testRSAByPrivateKeyJieMi(toPublicKeyText)); System.out.println("main:解密后的文字"+privatekeyjiemi); map.put("usertext", usertext.trim()); map.put("publickeyjiami", publickeyjiamihou.trim()); map.put("privatekeyjiemi", privatekeyjiemi.trim()); return "index"; } //(二)私钥加密,公钥解密 @RequestMapping(value="/setToPrivateKeyToPublicKey",method=RequestMethod.POST) public String setToPrivateKeyToPublicKey(@RequestParam("usertext") String usertext,Map map) throws Exception{ System.out.println("私钥加密公钥解密"); System.out.println("usertext:"+usertext); RSATest.getKey(); //获得公钥和私钥的密钥 //(1)通过私钥进行文字加 byte[] toPublicKeyText3=RSATest.testRSAByPrivatyJiaMi(usertext); String privatekeyjiami=new String(toPublicKeyText3);//加密 //(2)通过公钥进行文字解密 String publickeyjiemi=RSATest.testSignPublicKeyBySignJieMI(toPublicKeyText3); System.out.println("通过公钥解密后:"+publickeyjiemi); map.put("usertext", usertext.trim()); map.put("privatekeyjiami", privatekeyjiami.trim()); map.put("publickeyjiemi", publickeyjiemi.trim()); return "privateToPublic"; } //(三)文件加密 @RequestMapping(value="/setToFile",method=RequestMethod.POST) public String setToFile(@RequestParam("path") String path,Map map) throws Exception{ System.out.println("加密文件"); System.out.println("usertext:"+path); RSATest.getKey(); //获得公钥和私钥的密钥 //(1)通过私钥进行文字加 // RSATest.ReadAndAddRSAToFile("D:\\学习笔记区\\文件测试3.txt"); System.out.println("----文件读取区域------"); RSATest.ReadAndAddRSAToFile(path); map.put("zhuangtai", "成功加密,加密在当前文件的统计目录下"); return "fileSetRSA"; } //(四)文件解密 }


使用Java实现MD5算法

使用MD5算法,对密码进行加密。

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author 渴望飞的鱼 
* @version 创建时间:2017年6月7日 下午5:27:04
* @introduction :密码进行md5加密
* 接口:PwdAddMD5.encodeMD5String("加密密码"),单向验证。
*/
public class PwdAddMD5 {
	  /**  
     * 用MD5算法进行加密  
     * @param str 需要加密的字符串  
     * @return MD5加密后的结果  ,单向加密
     */    
    public static String encodeMD5String(String str) {    
        return encode(str, "MD5");    
    }  
    private static String encode(String str, String method) {    
        MessageDigest md = null;    
        String dstr = null;    
        try {    
        	//通过MD5加密
            md = MessageDigest.getInstance(method);   
            //获得字节
            md.update(str.getBytes());  
            
            dstr = new BigInteger(1, md.digest()).toString(16);    
        } catch (NoSuchAlgorithmException e) {    
            e.printStackTrace();    
        }    
        return dstr;    
    }     
	public static void main(String[] args){
		System.out.println(PwdAddMD5.encodeMD5String("1234567890"));
		System.out.println("2:"+PwdAddMD5.encodeMD5String("1234567890").length());
	System.out.println("3:"+PwdAddMD5.encodeMD5String("admindfdsfsadfdsfdsfad").length());
		System.out.println("4:"+PwdAddMD5.encodeMD5String("123456gfgfg0").length());
	}
}

阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: RC522是一种RFID读写模块,它不具备加密算法,因此没有专门的地方放置加密算法。RC522是通过与外部主控芯片(例如Arduino、树莓派等)进行通信来完成加密算法实现。当使用RC522读取或写入RFID标签时,通常会将RC522与主控芯片连接,并在主控芯片上通过编程实现加密算法的功能。 具体来说,主控芯片负责与RC522进行通信,接收到从RC522读取的RFID标签数据后,可以根据需求对这些数据进行加密操作。加密操作可以使用各种加密算法,例如DES、AES等,具体选择的加密算法取决于应用或系统的安全需求。主控芯片上的程序代码会将RC522读取到的RFID标签数据进行加密并进行相应的验证操作。 总之,RC522本身并不包含加密算法。它只是一种RFID读写模块,用于与外部主控芯片进行通信,并通过主控芯片上的程序代码实现具体的加密算法功能。 ### 回答2: RC522是一种低功耗的射频ID卡读写器芯片。它具有内置的加密算法模块,用于对通信数据进行加密和解密的处理。 RC522的加密算法模块位于其硬件内部。它由一个专用的加密处理器和相关电路组成,用于实现基于ISO14443标准的加密通信。 RC522支持ISO14443A/MIFARE卡的加密通信。根据相关规范,RC522芯片内部集成了MIFARE加密算法,包括AES加密算法、ISO14443A认证算法等。 当RC522与ISO14443A/MIFARE卡进行通信时,它会使用内部的加密算法对通信数据进行加密。同时,RC522还能够对接收到的加密数据进行解密。这样,它可以确保通信数据的安全性,防止数据被非法读取和篡改。 值得注意的是,RC522芯片只提供了一些基本的加密算法功能,如认证和加密。如果需要更高级的加密功能,比如RSA、DES等算法,需要在MCU或其他外部设备上实现。 ### 回答3: RC522是一款RFID芯片,它支持多种加密算法。RC522芯片的加密算法位于其内部的硬件逻辑中。这些加密算法是通过专门的硬件电路实现的,具有高度的安全性和效率。 RC522芯片支持的加密算法包括DES/Triple DES、AES等。这些加密算法常用于RFID通信中的数据加密和身份验证,可以保护数据的安全性和隐私。 在使用RC522芯片进行通信时,需要选择适当的加密算法,并通过配置RC522的相关寄存器来设置和启用加密。具体的加密算法的选择和配置需要根据实际的应用需求和安全要求来确定。 总而言之,RC522芯片的加密算法是通过其内部的硬件逻辑实现的,用户可以通过相应的配置来选择和启用适合的加密算法以保护通信数据的安全。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

渴望飞的鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值