Cordova插件之MD5加密

PART_A 插件目录结构

照官方插件做参考即可
这里写图片描述


PART_B 具体代码

  1. plugin.xml配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
        id="deppon.md5"
        version="0.0.5">
        <name>Deppon MD5</name>
        <description>this is based on JavaAPI</description>
    
        <!-- js中间件的目录指定 -->
        <js-module src="www/md5.js" name="md5">
            <!-- target值为js调用的对象符号 -->
            <clobbers target="deppon"/>
        </js-module>
    
        <platform name="android">
    
            <!-- 原生代码 -->
            <source-file src="src/android/MD5Tool.java" target-dir="src/catface/plugin"/>
            <source-file src="src/android/BASE64Encoder.java" target-dir="src/catface/plugin"/>
            <source-file src="src/android/CharacterEncoder.java" target-dir="src/catface/plugin"/>
    
            <!-- 配置中间件及插件类 -->
            <config-file target="res/xml/config.xml" parent="/*">
                <!-- name值为中间件调用原生代码的对象符号 -->
                <feature name="MD5Tool">
                    <!-- value值为插件类的包类路径 -->
                    <param name="android-package" value="catface.plugin.MD5Tool"/>
                </feature>
            </config-file>
    
        </platform>
    
    </plugin>
    
  2. js中间件

    var exec = require('cordova/exec');
    var catfaceFunc = function(){};
    
    // arg1:成功回调
    // arg2:失败回调
    // arg3:将要调用类配置的标识
    // arg4:调用的原生代码中的方法名
    // arg5:参数,json格式
    catfaceFunc.prototype.str2MD5=function(str, success, error) {
        exec(success, error, "MD5Tool", "str2MD5", [str]);
    };
    
    var catfaceFunc = new catfaceFunc();
    module.exports = catfaceFunc;
    
  3. Java代码

    public class MD5Tool extends CordovaPlugin {
    	
    	@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    		
    		if (action.equals("str2MD5")) {
    			
    			// 获取js传入的参数
    			String str = args.getString(0);
    			// 加密
    			String result = str2MD5(str);
    			if (!"".equals(result)) {
    				callbackContext.success(result);
    			} else {
    				// 失败回调,结果传空字符串
    				callbackContext.error("error");
    			}
    		}
    		return true;
    	}
    	
    	// MD5 + BASE64加密
    	private static String str2MD5(String origin) {
    		String resultString = new String(origin);
    		MessageDigest md = null;
    		try {
    			md = MessageDigest.getInstance("MD5");
    			byte[] buf = md.digest(resultString.getBytes());
    			// BASE64Encoder + CharacterEncoder作为辅助类
    			BASE64Encoder encoder = new BASE64Encoder();
    			return encoder.encode(buf);
    		} catch (NoSuchAlgorithmException e) {
    			e.printStackTrace();
    		}
    		return "";
    	}
    }
    
  4. 加密中需要的两个类,不需手动修改,直接CV即可

    • BASE64Encoder

      public class BASE64Encoder extends CharacterEncoder {
      
          private final static int NUMBER_ZERO = 0;
          private final static int NUMBER_ONE = 1;
          private final static int NUMBER_TWO = 2;
          private final static int NUMBER_THREE = 3;
          private final static int NUMBER_FOUR= 4;
          private final static int NUMBER_FIVE = 5;
          private final static int NUMBER_SIX= 6;
          private final static int NUMBER_SEVEN = 7;
      
          protected int bytesPerAtom() {
              return (NUMBER_THREE);
          }
      
          protected int bytesPerLine() {
          	return 200;
          }
      
          private final static char pem_array[] = {
              //       0   1   2   3   4   5   6   7
                      'A','B','C','D','E','F','G','H', // 0
                      'I','J','K','L','M','N','O','P', // 1
                      'Q','R','S','T','U','V','W','X', // 2
                      'Y','Z','a','b','c','d','e','f', // 3
                      'g','h','i','j','k','l','m','n', // 4
                      'o','p','q','r','s','t','u','v', // 5
                      'w','x','y','z','0','1','2','3', // 6
                      '4','5','6','7','8','9','+','/'  // 7
              };
      
          protected void encodeAtom(OutputStream outStream, byte data[], int offset, int len)
              throws IOException {
              byte a, b, c;
      
              if (len == NUMBER_ONE) {
                  a = data[offset];
                  b = NUMBER_ZERO;
                  c = NUMBER_ZERO;
                  outStream.write(pem_array[(a >>> NUMBER_TWO) & 0x3F]);
                  outStream.write(pem_array[((a << NUMBER_FOUR) & 0x30) + ((b >>> NUMBER_FOUR) & 0xf)]);
                  outStream.write('=');
                  outStream.write('=');
              } else if (len == NUMBER_TWO) {
                  a = data[offset];
                  b = data[offset+1];
                  c = NUMBER_ZERO;
                  outStream.write(pem_array[(a >>> NUMBER_TWO) & 0x3F]);
                  outStream.write(pem_array[((a << NUMBER_FOUR) & 0x30) + ((b >>> NUMBER_FOUR) & 0xf)]);
                  outStream.write(pem_array[((b << NUMBER_TWO) & 0x3c) + ((c >>> NUMBER_SIX) & 0x3)]);
                  outStream.write('=');
              } else {
                  a = data[offset];
                  b = data[offset+1];
                  c = data[offset+2];
                  outStream.write(pem_array[(a >>> NUMBER_TWO) & 0x3F]);
                  outStream.write(pem_array[((a << NUMBER_FOUR) & 0x30) + ((b >>> NUMBER_FOUR) & 0xf)]);
                  outStream.write(pem_array[((b << NUMBER_TWO) & 0x3c) + ((c >>> NUMBER_SIX) & 0x3)]);
                  outStream.write(pem_array[c & 0x3F]);
              }
          }
      }
      
    • CharacterEncoder

      import java.io.ByteArrayInputStream;
      import java.io.ByteArrayOutputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.OutputStream;
      import java.io.PrintStream;
      import java.nio.ByteBuffer;
      
      public abstract class CharacterEncoder {
      	protected PrintStream pStream;
      	abstract protected int bytesPerAtom();
      	abstract protected int bytesPerLine();
      	protected void encodeBufferPrefix(OutputStream aStream) throws IOException {
      		pStream = new PrintStream(aStream);
      	}
      
      	protected void encodeBufferSuffix(OutputStream aStream) throws IOException {
      	}
      
      	protected void encodeLinePrefix(OutputStream aStream, int aLength) throws IOException {
      	}
      
      	protected void encodeLineSuffix(OutputStream aStream) throws IOException {
      		pStream.println();
      	}
      
      	abstract protected void encodeAtom(OutputStream aStream, byte someBytes[], int anOffset, int aLength)
      			throws IOException;
      
      	protected int readFully(InputStream in, byte buffer[]) throws IOException {
      		for (int i = 0; i < buffer.length; i++) {
      			int q = in.read();
      			if (q == -1) {
      				return i;
      			}
      			buffer[i] = (byte) q;
      		}
      		return buffer.length;
      	}
      
      	public void encode(InputStream inStream, OutputStream outStream) throws IOException {
      		int j;
      		int numBytes;
      		byte tmpbuffer[] = new byte[bytesPerLine()];
      
      		encodeBufferPrefix(outStream);
      
      		while (true) {
      			numBytes = readFully(inStream, tmpbuffer);
      			if (numBytes == 0) {
      				break;
      			}
      			encodeLinePrefix(outStream, numBytes);
      			for (j = 0; j < numBytes; j += bytesPerAtom()) {
      
      				if ((j + bytesPerAtom()) <= numBytes) {
      					encodeAtom(outStream, tmpbuffer, j, bytesPerAtom());
      				} else {
      					encodeAtom(outStream, tmpbuffer, j, (numBytes) - j);
      				}
      			}
      			if (numBytes < bytesPerLine()) {
      				break;
      			} else {
      				encodeLineSuffix(outStream);
      			}
      		}
      		encodeBufferSuffix(outStream);
      	}
      
      	public void encode(byte aBuffer[], OutputStream aStream) throws IOException {
      		ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer);
      		encode(inStream, aStream);
      	}
      
      	public String encode(byte aBuffer[]) {
      		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      		ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer);
      		String retVal = null;
      		try {
      			encode(inStream, outStream);
      			retVal = outStream.toString("8859_1");
      		} catch (Exception e) {
      			throw new Error("CharacterEncoder.encode internal error",e);
      		}
      		return (retVal);
      	}
      
      	private byte[] getBytes(ByteBuffer bb) {
      	
      		byte[] buf = null;
      
      		if (bb.hasArray()) {
      			byte[] tmp = bb.array();
      			if ((tmp.length == bb.capacity()) && (tmp.length == bb.remaining())) {
      				buf = tmp;
      				bb.position(bb.limit());
      			}
      		}
      
      		if (buf == null) {
      			
      			buf = new byte[bb.remaining()];
      
      			bb.get(buf);
      		}
      
      		return buf;
      	}
      
      	public void encode(ByteBuffer aBuffer, OutputStream aStream) throws IOException {
      		byte[] buf = getBytes(aBuffer);
      		encode(buf, aStream);
      	}
      
      	public String encode(ByteBuffer aBuffer) {
      		byte[] buf = getBytes(aBuffer);
      		return encode(buf);
      	}
      
      	public void encodeBuffer(InputStream inStream, OutputStream outStream) throws IOException {
      		int j;
      		int numBytes;
      		byte tmpbuffer[] = new byte[bytesPerLine()];
      
      		encodeBufferPrefix(outStream);
      
      		while (true) {
      			numBytes = readFully(inStream, tmpbuffer);
      			if (numBytes == 0) {
      				break;
      			}
      			encodeLinePrefix(outStream, numBytes);
      			for (j = 0; j < numBytes; j += bytesPerAtom()) {
      				if ((j + bytesPerAtom()) <= numBytes) {
      					encodeAtom(outStream, tmpbuffer, j, bytesPerAtom());
      				} else {
      					encodeAtom(outStream, tmpbuffer, j, (numBytes) - j);
      				}
      			}
      			encodeLineSuffix(outStream);
      			if (numBytes < bytesPerLine()) {
      				break;
      			}
      		}
      		encodeBufferSuffix(outStream);
      	}
      
      	public void encodeBuffer(byte aBuffer[], OutputStream aStream) throws IOException {
      		ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer);
      		encodeBuffer(inStream, aStream);
      	}
      
      	public String encodeBuffer(byte aBuffer[]) {
      		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      		ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer);
      		try {
      			encodeBuffer(inStream, outStream);
      		} catch (Exception e) {
      			throw new Error("CharacterEncoder.encodeBuffer internal error",e);
      		}
      		return (outStream.toString());
      	}
      
      	public void encodeBuffer(ByteBuffer aBuffer, OutputStream aStream) throws IOException {
      		byte[] buf = getBytes(aBuffer);
      		encodeBuffer(buf, aStream);
      	}
      
      	public String encodeBuffer(ByteBuffer aBuffer) {
      		byte[] buf = getBytes(aBuffer);
      		return encodeBuffer(buf);
      	}
      
      }
      
  5. 使用方式

    deppon.str2MD5(str, function(msg) {
        alert(msg); // 加密后结果
    }, function(err) {
        alert(err); // 失败返回空字符串""
    })
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
开发 Cordova 插件的基本步骤如下: 1. 创建插件项目 使用 Cordova 命令行工具创建一个新的插件项目,例如: ``` cordova create my-plugin com.example.myplugin MyPlugin ``` 这将创建一个名为 `my-plugin` 的 Cordova 项目,并在 `my-plugin/plugins` 目录下创建一个名为 `com.example.myplugin` 的插件。 2. 添加插件代码 在 `my-plugin/plugins/com.example.myplugin` 目录下创建一个子目录,例如 `src/ios`,在其中添加插件的原生代码。对于 iOS 平台,这通常是一个 `.m` 文件和一个 `.h` 文件。对于 Android 平台,这通常是一个 `.java` 文件。 3. 添加插件描述文件 在 `my-plugin/plugins/com.example.myplugin` 目录下创建一个名为 `plugin.xml` 的文件,该文件描述了插件的信息和功能。插件描述文件示例: ```xml <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" id="com.example.myplugin" version="1.0.0"> <name>MyPlugin</name> <description>This is my plugin</description> <license>Apache 2.0</license> <keywords>cordova, plugin, myplugin</keywords> <author email="[email protected]" href="http://example.com"> My Name </author> <engines> <engine name="cordova" version=">=3.0.0" /> </engines> <platform name="ios"> <source-file src="src/ios/MyPlugin.m" /> <header-file src="src/ios/MyPlugin.h" /> </platform> <platform name="android"> <source-file src="src/android/MyPlugin.java" /> </platform> </plugin> ``` 4. 安装插件插件添加到 Cordova 项目中: ``` cordova plugin add /path/to/my-plugin ``` 5. 使用插件Cordova 应用程序中使用插件,例如: ```js var myPlugin = cordova.plugins.myPlugin; myPlugin.doSomething(); ``` 以上是 Cordova 插件开发的基本步骤,具体实现需要根据插件的功能和要求进行调整和修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值