欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android-ios-php Rsa加密解密

程序员文章站 2024-03-14 13:16:16
...

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

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 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");
    }

}

上一篇: [NCTF2019]SQLi

下一篇: [NCTF2019]Sore