1. 程式人生 > >nodejs和java加解密

nodejs和java加解密

一、首先安裝node.js

  1. mac 安裝完

     mode -v 檢視安裝是否成功
     touch hello-word.js 找個目錄建立js
     vi hello-word.js 開啟js 按i編輯js
    

    1.hello-word.js內容

    	const http = require('http');
    
    	const hostname = '127.0.0.1';
    	const port = 3000;
    
    	const server = http.createServer((req, res) => {
    
    	cipher.write('some clear text data');
    	cipher.end();
    	  res.statusCode = 200;
    	  res.setHeader('Content-Type', 'text/plain');
    	  res.end('Hello, World!\n');
    	});
    
    	server.listen(port, hostname, () => {
    	  console.log(`伺服器執行在 http://${hostname}:${port}/`);
    	});
    
    	  //1.----------------sha256----------------
    
    	  // const crypto = require('crypto');
    
    	  // const secret = 'ndE2jdZNFixH9G6Aidsfyf7lYT3PxW';
    	  // const hash = crypto.createHmac('sha256', secret)
    	  //                    .update('I love 額外若翁')
    	  //                    .digest('hex');
    	  // console.log(hash);
    
    	//2.----------------aes192----------------
    
    
    	const crypto = require('crypto');
    	/**
    	 * aes加密
    	 * @param data
    	 * @param secretKey
    	 */
    	function aesEncrypt(data, key) {
    		const cipher = crypto.createCipher('aes-128-ecb', key);
    		var crypted = cipher.update(data, 'utf8', 'hex');
    		crypted += cipher.final('hex');
    		return crypted;
    	}
    	/**
    	 * aes解密
    	 * @param data
    	 * @param secretKey
    	 * @returns {*}
    	 */
    	function aesDecrypt(encrypted, key) {
    		const decipher = crypto.createDecipher('aes-128-ecb', key);
    		var decrypted = decipher.update(encrypted, 'hex', 'utf8');
    		decrypted += decipher.final('utf8');
    		return decrypted;
    	}
    
    	var data = 'Hello, this is a secret message!';
    	var key = 'Password!';
    	var encrypted = aesEncrypt(data, key);
    	var decrypted = aesDecrypt(encrypted, key);
    
    	console.log('Plain text: ' + data);
    	console.log('Encrypted text: ' + encrypted);
    	console.log('Decrypted text: ' + decrypted);
    
    
    	//--------------------------------
    
     	按esc 按:
     	wq; 儲存退出
     	node hello-word.js 執行js檔案列印ip埠可加解密資料成功
    
  2. java

    	package com.util;
    	/**
    	 * description: sha256_HMAC
    	 * QQ:       905845006
    	 */
    
    	import javax.crypto.Mac;
    	import javax.crypto.spec.SecretKeySpec;
    	public class HMACSHA256 {
    
    		//   SECRET KEY
    		private final static String secret_key = "ndE2jdZNFixH9G6Aidsfyf7lYT3PxW";
    		/**
    		 * 將加密後的位元組陣列轉換成字串
    		 *
    		 * @param b 位元組陣列
    		 * @return 字串
    		 */
    		private static String byteArrayToHexString(byte[] b) {
    			StringBuilder hs = new StringBuilder();
    			String stmp;
    			for (int n = 0; b!=null && n < b.length; n++) {
    				stmp = Integer.toHexString(b[n] & 0XFF);
    				if (stmp.length() == 1)
    					hs.append('0');
    				hs.append(stmp);
    			}
    			return hs.toString().toLowerCase();
    		}
    		/**
    		 * sha256_HMAC加密
    		 * @param message 訊息
    		 * @param secret  祕鑰
    		 * @return 加密後字串
    		 */
    		private static String sha256_HMAC(String message, String secret) {
    			String hash = "";
    			try {
    				Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    				SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    				sha256_HMAC.init(secret_key);
    				byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
    				hash = byteArrayToHexString(bytes);
    				System.out.println(hash);
    			} catch (Exception e) {
    				System.out.println("Error HmacSHA256 ===========" + e.getMessage());
    			}
    			return hash;
    		}
    
    		public static void main(String[] args) {
    			String message ="I love 額外若翁";
    			sha256_HMAC(message, secret_key);
    		}
    	}
    
    	package com.springboot.util;
    
    	/**
    	 * description: AES
    	 *
    	 * QQ:       905845006
    	 */
    
    	import java.security.MessageDigest;
    
    	import javax.crypto.Cipher;
    	import javax.crypto.spec.SecretKeySpec;
    
    	/**
    	 * AES加密,與Nodejs 保持一致
    	 * @author lmiky
    	 * @date 2014-2-25
    	 */
    	public class AESForNodejs {
    		public static final String DEFAULT_CODING = "utf-8";
    
    		/**
    		 * 解密
    		 * @author lmiky
    		 * @date 2014-2-25
    		 * @param encrypted
    		 * @param seed
    		 * @return
    		 * @throws Exception
    		 */
    		private static String decrypt(String encrypted, String seed) throws Exception {
    			byte[] keyb = seed.getBytes(DEFAULT_CODING);
    			MessageDigest md = MessageDigest.getInstance("MD5");
    			byte[] thedigest = md.digest(keyb);
    			SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
    			Cipher dcipher = Cipher.getInstance("AES");
    			dcipher.init(Cipher.DECRYPT_MODE, skey);
    
    			byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
    			return new String(clearbyte);
    		}
    
    		/**
    		 * 加密
    		 * @author lmiky
    		 * @date 2014-2-25
    		 * @param content
    		 * @param key
    		 * @return
    		 * @throws Exception
    		 */
    		public static String encrypt(String content, String key) throws Exception {
    			byte[] input = content.getBytes(DEFAULT_CODING);
    
    			MessageDigest md = MessageDigest.getInstance("MD5");
    			byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING));
    			SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
    			 // 演算法/模式/補碼方式
    			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    			cipher.init(Cipher.ENCRYPT_MODE, skc);
    
    			byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    			int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    			ctLength += cipher.doFinal(cipherText, ctLength);
    
    			return parseByte2HexStr(cipherText);
    		}
    
    		/**
    		 * 字串轉位元組陣列
    		 * @author lmiky
    		 * @date 2014-2-25
    		 * @param hexString
    		 * @return
    		 */
    		private static byte[] toByte(String hexString) {
    			int len = hexString.length() / 2;
    			byte[] result = new byte[len];
    			for (int i = 0; i < len; i++) {
    				result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
    			}
    			return result;
    		}
    
    		/**
    		 * 位元組轉16進位制陣列
    		 * @author lmiky
    		 * @date 2014-2-25
    		 * @param buf
    		 * @return
    		 */
    		private static String parseByte2HexStr(byte buf[]) {
    			StringBuffer sb = new StringBuffer();
    			for (int i = 0; i < buf.length; i++) {
    				String hex = Integer.toHexString(buf[i] & 0xFF);
    				if (hex.length() == 1) {
    					hex = '0' + hex;
    				}
    				sb.append(hex);
    			}
    			return sb.toString();
    		}
    
    		public static void main(String[] args) throws Exception {
    			System.out.println(AESForNodejs.encrypt("Hello, this is a secret message!", "Password!"));
    			System.out.println(AESForNodejs.decrypt("f4a829a62a6e9e22a195bd3daeef2e00a87a6051dd32315b1bf912c58ca5fbbb9c2b4aa4d3fd2d319ea0f032a3b478b5", "Password!"));
    		}
    	}