Android-ios-php Rsa加密解密

====
公钥加密
私钥解密
====
私钥加密
公钥解密
====一般只需要公钥即可,服务器保留私钥验证====
调用方式:

Logger.e("sub", "加密:" + Rsa.encryptByPublic("123456")
                + "解密:" + Rsa.decryptByPublic(Rsa.encryptByPublic("123456")));//是私钥解密,方法名字没改
11-16 19:23:41.056  5954  5954 E sub     : ╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════
11-16 19:23:41.058  5954  5954 E sub     : ║ 19:23:41:058 main MainActivity.initData(MainActivity.java:181)
11-16 19:23:41.058  5954  5954 E sub     : ╟───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
11-16 19:23:41.058  5954  5954 E sub     : ║ 加密:fDpfo0MtIJm/VDpM3zYbb5WwxVso/+z+GBQkhl65tQRnnf94xrpXm1B61fkcN0a5Fuooj96KZEBT
11-16 19:23:41.058  5954  5954 E sub     : ║ WDGTFS6Qw6oSYMYuR59Qi+IqGnvVMO1sVRIEbHWXG1T1RUdDo4TmgjsgU2FZzMwOf7l3I0uCPcTs
11-16 19:23:41.058  5954  5954 E sub     : ║ toZOPafadnkIi1fDPmo=
11-16 19:23:41.058  5954  5954 E sub     : ║ 解密:????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????123456


========调试成功后如下==========


11-16 20:02:30.649 16952 16952 E sub     : #解密后#123456
11-16 20:02:30.650 16952 16952 E sub     : ╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════
11-16 20:02:30.652 16952 16952 E sub     : ║ 20:02:30:651 main MainActivity.initData(MainActivity.java:181)
11-16 20:02:30.652 16952 16952 E sub     : ╟───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
11-16 20:02:30.652 16952 16952 E sub     : ║ 加密:jX6s2YPJzDbL28RPm4Y0o51T+H7QR5aHMm9VJLIbC73OsulKyOi8cQXqtagrgcaUT9IC8K0s+WTW
11-16 20:02:30.652 16952 16952 E sub     : ║ 4AErVqfh67lmo1GEFuFg9wxxrLEhjW9boILaKy2632mbbeZ7e9olDUpfu7eYpRU1VE2WXKiTupYo
11-16 20:02:30.652 16952 16952 E sub     : ║ qsbZsD9S4Eox5/4XBZQ=
11-16 20:02:30.652 16952 16952 E sub     : ║ 解密:123456
11-16 20:02:30.652 16952 16952 E sub     : ╚═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════
11-16 20:02:47.743 17420 17420 E sub     : #解密后#123456
11-16 20:02:47.743 17420 17420 E sub     : ╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════
11-16 20:02:47.746 17420 17420 E sub     : ║ 20:02:47:745 main MainActivity.initData(MainActivity.java:181)
11-16 20:02:47.746 17420 17420 E sub     : ╟───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
11-16 20:02:47.746 17420 17420 E sub     : ║ 加密:E/+0+jW9qqRlbOr3aqihaTIyxcOTGU5VWJIfJR40BKIkfOllKMGKcChXP/L56NQ1eP8HG0ROAzRu
11-16 20:02:47.746 17420 17420 E sub     : ║ I8bjFCL/1oIavqv8OFOvU63m7QElLrmo8BnDK3C02TT6OwwF/xaxRJKsOKYKJj3sL+dj5UvoYzYg
11-16 20:02:47.746 17420 17420 E sub     : ║ 8ETXeAGSkwaFTJd00AY=
11-16 20:02:47.746 17420 17420 E sub     : ║ 解密:123456
11-16 20:02:47.746 17420 17420 E sub     : ╚═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════

代码如下

package com.wyhd.encry.decry.security.config;

import android.util.Base64;
import android.util.Log;

import com.wyhd.encry.decry.security.security.RSACipherStrategy;
import com.wyhd.encry.decry.security.security.util.RSAUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * 公钥加密
 * 私钥加密
 * 公钥解密
 * 私钥解密
 * ----->>>> 公钥加密,服务器私钥解密
 * 公钥用来公开并加密,私钥用来保留解密,且不可互换。
 */
public class Rsa {
    public final static String KEY_PAIR = "RSA";
   // public final static String CIPHER = "RSA/ECB/PKCS1Padding";
      public final static String CIPHER = "RSA/ECB/PKCS1Padding";
    // public final static String CIPHER = "RSA/None/PKCS1Padding";//error
    //public final static String CIPHER = "RSA/ECB/NoPadding";//error
    // public static final String RSA_PUBLICE = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJ4/3VqHevhEUwMvmkY/DizPUF/s2lhyXHp1AhZhpzMjFUMGFIppJyHhcg3/r1jTHo+RJOjiT4D0g4yameVcp3ELmhyQArde4+gAG9762Zk4eDU+MM4AtOG7jSQk23BFWtYYEtwjXhGCX+L37sMqDdDJd6dLnKD+ghzswVEwAlgwIDAQAB";
    public static final String RSA_PUBLICE =
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNQDs3peFeKvvl/lcOzatuEYiC\n" +
                    "V5bUF/xD/ldrBFswOQaDszxY5Up/sl4HGNRqMAomgAlOoNM1cXulmdFX7M6mzv2S\n" +
                    "48hT8GNJwPsG/dvaourQ6//EL/AC/Ue/t8nWCHToKct2ejbDShXKHLsqtsoh5Gb+\n" +
                    "PWjwdh1a1od+h3ZlZwIDAQAB\n";
    public static final String RSA_PRIVATE =
            "MIICXQIBAAKBgQDNQDs3peFeKvvl/lcOzatuEYiCV5bUF/xD/ldrBFswOQaDszxY\n" +
                    "5Up/sl4HGNRqMAomgAlOoNM1cXulmdFX7M6mzv2S48hT8GNJwPsG/dvaourQ6//E\n" +
                    "L/AC/Ue/t8nWCHToKct2ejbDShXKHLsqtsoh5Gb+PWjwdh1a1od+h3ZlZwIDAQAB\n" +
                    "AoGADZRiVpwy/Pf7EoxxVhllbjLaxUTmRcIQfq8lOX9gSSB8vdnt9DO3ahty/SU3\n" +
                    "aI8lHMb71qftUWvgsmQq5ZZVVbWlpT7eAFT1cauizPfMZeIrhwqLIPIvixR3w0+o\n" +
                    "hBRE+MLfHnEFtrpJXVYTU5qZ/Ca3DQU8h2JiYWvOhGOrqIECQQDp1juG1CPCBilx\n" +
                    "cRh2CzwsYKspCTtuNrOUdocW0dZzug3yWBC3yCbBWMpAWcBY+2h+8+PMB6aPM1/e\n" +
                    "s7KodH4dAkEA4LRlRDOG6gIMaMfFSOpC6qXxcooqc0oAxEfJqqlfLixiukqzNmDt\n" +
                    "xiKSUIiE8F7bXMI7uY3i/9fOrTQjmCfqUwJBAL6+DTKPS1fSlO2/dlecFIqSlCvW\n" +
                    "Jw9hOZ1qDgnUQ12FMCk2IvT3JH3lAp35WEh9U6DzKydcOkZnftV3uc1lsRUCQEWe\n" +
                    "frWXxVghVFjudCh4NE1hJqKXPjnEFuK5XzkaCtxScjBHzqitdV3q/iwncBDNQufF\n" +
                    "Yh3GYStlYKp3OgP9cfMCQQCAG9IXppb2aFPQQQiOWf8BSimzaVTORphQL83VBsKp\n" +
                    "B74ZVjhs0cXBS1DBPZ7LTO8goFzF1R4Nz+d6Q18f3vCQ\n";
    private static final String ALGORITHM = "RSA";

    /**
     * 得到公钥
     *
     * @param algorithm
     * @param bysKey
     * @return
     */
    private static PublicKey getPublicKeyFromX509(String algorithm,
                                                  String bysKey) throws NoSuchAlgorithmException, Exception {
        byte[] decodedKey = Base64.decode(bysKey, Base64.DEFAULT);
        X509EncodedKeySpec x509 = new X509EncodedKeySpec(decodedKey);

        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory.generatePublic(x509);
    }

    /**
     * 使用公钥加密
     *
     * @param content
     * @param key
     * @return
     */
    public static String encryptByPublic(String content) {
        try {
           // PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);
            PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);
            // Log.e("sub", "公钥:" + RSA_PUBLICE);
            // RSACipherStrategy.printPublicKeyInfo(pubkey);
            // Cipher cipher = Cipher.getInstance(RSAUtils.CIPHER);
            Cipher cipher = Cipher.getInstance(RSAUtils.CIPHER);
            //Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, pubkey);

            byte plaintext[] = content.getBytes("UTF-8");
            byte[] output = cipher.doFinal(plaintext);

            String s = new String(Base64.encode(output, Base64.DEFAULT));

            return s;
            // 必须先encode成 byte[],再转成encodeToString,否则服务器解密会失败
//            byte[] encode = Base64.encode(output, Base64.DEFAULT);
//            return Base64.encodeToString(encode, Base64.DEFAULT);
        } catch (Exception e) {
            Log.e("sub", e + "|加密");
            return null;
        }
    }

    /**
     * 使用公钥解密
     * 使用私钥解密<br/>
     *
     * @param content 密文
     * @param key     商户私钥
     * @return 解密后的字符串
     */
    public static String decryptByPublic(String content) {
        try {
            PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);
            // Log.e("sub", "私钥:" + RSA_PRIVATE);
            // 解密
            PrivateKey privateKey = loadPrivateKey(RSA_PRIVATE);
            //RSACipherStrategy.printPrivateKeyInfo(privateKey);
            Cipher cipher = Cipher.getInstance(RSAUtils.CIPHER);
            //Cipher cipher = Cipher.getInstance(ALGORITHM);
           cipher.init(Cipher.DECRYPT_MODE, privateKey);
            //cipher.init(Cipher.DECRYPT_MODE, pubkey);
            //byte[] output = cipher.doFinal(Base64.decode(content, Base64.DEFAULT));
            boolean tst = true;
            if (tst) {
               // return new String(output);
            }
            InputStream ins = new ByteArrayInputStream(Base64.decode(content,
                    Base64.DEFAULT));
            ByteArrayOutputStream writer = new ByteArrayOutputStream();
            //byte[] buf = new byte[128];
            byte[] buf = new byte[128];
            int bufl;
            while ((bufl = ins.read(buf)) != -1) {
                byte[] block = null;
                if (buf.length == bufl) {
                    block = buf;
                } else {
                    block = new byte[bufl];
                    for (int i = 0; i < bufl; i++) {
                        block[i] = buf[i];
                    }
                }
                writer.write(cipher.doFinal(block));
            }
            // byte[] bytes = Base64.decode(writer.toByteArray(),Base64.DEFAULT);
            Log.e("sub", "#解密后#"+new String(writer.toByteArray()));
            return new String(writer.toByteArray(), "utf-8");
            //return new String(bytes, "utf-8");
        } catch (Exception e) {
            Log.e("sub", e + "|解密异常||||||");
            return null;
        }
    }

    public static String getMD5(String content) {
        String s = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(content.getBytes());
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
     /**
     * 从字符串中加载私钥<br>
     * 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
     *
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static PrivateKey loadPrivateKey(String privateKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64Utils.decode(privateKeyStr);
            //byte[] buffer = Base64.decode(privateKeyStr,Base64.DEFAULT);
            // PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(s_privateKeyIn1t);
            //X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            //KeyFactory keyFactory = KeyFactory.getInstance(KEY_PAIR,"BC"); //神秘符号
            // KeyFactory keyFactory = KeyFactory.getInstance(KEY_PAIR,"BC");
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_PAIR,"BC");
            //KeyFactory keyFactory = KeyFactory.getInstance(KEY_PAIR);
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法" + e);
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }
}

base64utils

package com.wyhd.encry.decry.security.util;

import java.io.UnsupportedEncodingException;

/**
 * @author Rocko
 */
public class Base64Utils {
    private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/' };
    private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
            60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
            10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
            -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
            38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
            -1, -1 };

    public static String encode(byte[] data) {
        StringBuffer sb = new StringBuffer();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;
        while (i < len) {
            b1 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4)
                        | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[((b1 & 0x03) << 4)
                    | ((b2 & 0xf0) >>> 4)]);
            sb.append(base64EncodeChars[((b2 & 0x0f) << 2)
                    | ((b3 & 0xc0) >>> 6)]);
            sb.append(base64EncodeChars[b3 & 0x3f]);
        }
        return sb.toString();
    }

    public static byte[] decode(String str) {
        try {
            return decodePrivate(str);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new byte[] {};
    }

    private static byte[] decodePrivate(String str)
            throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        byte[] data = null;
        data = str.getBytes("US-ASCII");
        int len = data.length;
        int i = 0;
        int b1, b2, b3, b4;
        while (i < len) {

            do {
                b1 = base64DecodeChars[data[i++]];
            } while (i < len && b1 == -1);
            if (b1 == -1)
                break;

            do {
                b2 = base64DecodeChars[data[i++]];
            } while (i < len && b2 == -1);
            if (b2 == -1)
                break;
            sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

            do {
                b3 = data[i++];
                if (b3 == 61)
                    return sb.toString().getBytes("iso8859-1");
                b3 = base64DecodeChars[b3];
            } while (i < len && b3 == -1);
            if (b3 == -1)
                break;
            sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

            do {
                b4 = data[i++];
                if (b4 == 61)
                    return sb.toString().getBytes("iso8859-1");
                    //return sb.toString().getBytes("utf-8");
                b4 = base64DecodeChars[b4];
            } while (i < len && b4 == -1);
            if (b4 == -1)
                break;
            sb.append((char) (((b3 & 0x03) << 6) | b4));
        }
        return sb.toString().getBytes("iso8859-1");
        //return sb.toString().getBytes("utf-8");
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容