当前位置: 代码迷 >> 综合 >> android 和 Koa2 服务器 在 RSA加密上的 通用算法
  详细解决方案

android 和 Koa2 服务器 在 RSA加密上的 通用算法

热度:41   发布时间:2024-01-30 07:25:18.0

首先在koa2上

var RSAJS = null
var RSAPKEY = null//需传递给客户端使用的公钥,在android端调用 getPKey()方法 生成 android使用的publickey
var RSASKEY = null 
function RSAInit() {var NodeRSA = require("node-rsa");RSAJS = new NodeRSA({b:1024})RSAJS.setOptions({encryptionScheme: 'pkcs1'});RSAPKEY = RSAJS.exportKey('public');RSASKEY = RSAJS.exportKey('private');
}
function RSAEncrypt(value) {return RSAJS.encryptPrivate(value, 'base64')
}function RSADecrypt(value) {return RSAJS.decryptPublic(value, 'utf8')
}
RSAInit()

在android上使用的

 

//注意在android上使用koa2的pkey的时候需要吧 -----BEGIN PUBLIC KEY----- 和 -----END PUBLIC KEY----- 去掉 //类似此种//PublicKey pk = //RSAUtil.getPKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHZ3cCV863r2aDaAg5wUS39vrF\n" +
//              "1yoCbQQhuUMbtDc3VJImLpZk54aVN8jR1cG7JdyozboZbBeDNhlEhNBfjH8wwiED\n" +
//              "LOmNfLZCDGbFfiVyfNdwnUa+uAbuMsy6p0vNeizPxt7XhDG4AJK2Mvfea1d2oKhR\n" +
//              "oTvgHQIqQcPdATRZ0QIDAQAB");public static PublicKey getPKey(String pkey) throws Exception {byte[] keyBytes = Base64.decode(pkey,Base64.DEFAULT);X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);PublicKey publicKey = null;try {KeyFactory kf = KeyFactory.getInstance("RSA");publicKey = kf.generatePublic(spec);} catch (Exception e) {e.printStackTrace();}return publicKey;}    public static byte[] encryptByPublicKey(PublicKey pubKey, byte[] data) throws Exception {return doFinal(pubKey, Mode.ENCRYPT, data);}public static byte[] decryptByPrivateKey(PrivateKey priKey, byte[] data) throws Exception {return doFinal(priKey, Mode.DECRYPT, Base64.decode(data,Base64.DEFAULT));}public static byte[] encryptByPrivateKey(PrivateKey priKey, byte[] data) throws Exception {return doFinal(priKey, Mode.ENCRYPT, data);}public static byte[] decryptByPublicKey(PublicKey pubKey, byte[] data) throws Exception {return doFinal(pubKey, Mode.DECRYPT, Base64.decode(data,Base64.DEFAULT));}private static byte[] doFinal(Key key, Mode mode, byte[] data) throws Exception {final int MAX = (mode == Mode.ENCRYPT) ? MAX_ENCRYPT_BLOCK : MAX_DECRYPT_BLOCK;final int LEN = data.length;byte[] cache;int i = 0, off = 0;ByteArrayOutputStream out = new ByteArrayOutputStream();Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");cipher.init(mode.value, key);while (off < LEN) {cache = cipher.doFinal(data, off, Math.min(LEN - off, MAX));out.write(cache, 0, cache.length);i++;off = i * MAX;}byte[] result = out.toByteArray();out.close();return result;}

以上方法均已验证请放心使用

  相关解决方案