资讯详情

Android Base64&RSA2加解密工具类

import java.io.UnsupportedEncodingException;  public class Base64 { 
             public static final String DEFAULT_ENCODING = "UTF-8";      /* * The methods of this class are static. Do not instantiate this class. Use * its static methods to get the encoded/decoded results */     public static String encode(byte[] byteData) throws UnsupportedEncodingException { 
                return encode(byteData, DEFAULT_ENCODING);     }     public static String encode(byte[] byteData, String encoding) throws UnsupportedEncodingException { 
                if(byteData == null) { 
        throw new IllegalArgumentException("byteData cannot be null"); }         return new String(_encode(byteData),encoding);     }      public static byte[] encode(String string) throws UnsupportedEncodingException { 
                return encode(string, DEFAULT_ENCODING);     }      public static byte[] encode(String string, String encoding) throws UnsupportedEncodingException { 
                if(string == null) { 
        throw new IllegalArgumentException("string cannot be null"); }
        return _encode(string.getBytes(encoding));
    }

    public final static byte[] _encode(byte[] byteData) { 
       
        /* If we received a null argument, exit this method. */
        if (byteData == null) { 
        throw new IllegalArgumentException("byteData cannot be null"); }

        /* * Declare working variables including an array of bytes that will * contain the encoded data to be returned to the caller. Note that the * encoded array is about 1/3 larger than the input. This is because * every group of 3 bytes is being encoded into 4 bytes. */
        int iSrcIdx; // index into source (byteData)
        int iDestIdx; // index into destination (byteDest)
        // byte[] byteData = (byte[])byteData_in.clone();
        // byte[] byteData = byteData_in;
        byte[] byteDest = new byte[((byteData.length + 2) / 3) * 4];

        /* * Walk through the input array, 24 bits at a time, converting them from * 3 groups of 8 to 4 groups of 6 with two unset bits between. as per * Base64 spec see * http://www.javaworld.com/javaworld/javatips/jw-javatip36-p2.html for * example explanation */
        for (iSrcIdx = 0, iDestIdx = 0; iSrcIdx < byteData.length - 2; iSrcIdx += 3) { 
       
            byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx] >>> 2) & 077);
            byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx + 1] >>> 4) & 017 | (byteData[iSrcIdx] << 4) & 077);
            byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx + 2] >>> 6) & 003 | (byteData[iSrcIdx + 1] << 2) & 077);
            byteDest[iDestIdx++] = (byte) (byteData[iSrcIdx + 2] & 077);
        }

        /* * If the number of bytes we received in the input array was not an even * multiple of 3, convert the remaining 1 or 2 bytes. */
        if (iSrcIdx < byteData.length) { 
       
            byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx] >>> 2) & 077);
            if (iSrcIdx < byteData.length - 1) { 
       
                byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx + 1] >>> 4) & 017 | (byteData[iSrcIdx] << 4) & 077);
                byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx + 1] << 2) & 077);
            } else
                byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx] << 4) & 077);
        }

        /* * Use the encoded data as indexes into the Base64 alphabet. (The Base64 * alphabet is completely documented in RFC 1521.) */
        for (iSrcIdx = 0; iSrcIdx < iDestIdx; iSrcIdx++) { 
       
            if (byteDest[iSrcIdx] < 26)
                byteDest[iSrcIdx] = (byte) (byteDest[iSrcIdx] + 'A');
            else if (byteDest[iSrcIdx] < 52)
                byteDest[iSrcIdx] = (byte) (byteDest[iSrcIdx] + 'a' - 26);
            else if (byteDest[iSrcIdx] < 62)
                byteDest[iSrcIdx] = (byte) (byteDest[iSrcIdx] + '0' - 52);
            else if (byteDest[iSrcIdx] < 63)
                byteDest[iSrcIdx] = '+';
            else
                byteDest[iSrcIdx] = '/';
        }

        /* Pad any unused bytes in the destination string with '=' characters. */
        for (; iSrcIdx < byteDest.length; iSrcIdx++)
            byteDest[iSrcIdx] = '=';

        return byteDest;
    }

    public static String decode(byte[] encoded) throws UnsupportedEncodingException { 
       
        return decode(encoded, DEFAULT_ENCODING);
    }

    public static String decode(byte[] encoded, String encoding) throws UnsupportedEncodingException { 
       
        if(encoded == null) { 
        throw new IllegalArgumentException("encoded cannot be null"); }
        return new String(_decode(encoded), encoding);
    }

    public final static byte[] decode(String encoded) throws UnsupportedEncodingException { 
       
        return decode(encoded,DEFAULT_ENCODING);
    }

    public final static byte[] decode(String encoded, String encoding) throws IllegalArgumentException, UnsupportedEncodingException { 
       
        if(null == encoded) { 
        throw new IllegalArgumentException("encoded cannot be null"); }
        return _decode(encoded.getBytes(encoding));
    }

    public final static byte[] _decode(byte[] byteData) throws IllegalArgumentException { 
       
        /* If we received a null argument, exit this method. */
        if (byteData == null) { 
        throw new IllegalArgumentException("byteData cannot be null"); }

        /* * Declare working variables including an array of bytes that will * contain the decoded data to be returned to the caller. Note that the * decoded array is about 3/4 smaller than the input. This is because * every group of 4 bytes is being encoded into 3 bytes. */
        int iSrcIdx; // index into source (byteData)
        int reviSrcIdx; // index from end of the src array (byteData)
        int iDestIdx; // index into destination (byteDest)
        byte[] byteTemp = new byte[byteData.length];

        /* * remove any '=' chars from the end of the byteData they would have * been padding to make it up to groups of 4 bytes note that I don't * need to remove it just make sure that when progressing throug array * we don't go past reviSrcIdx ;-) */
        for (reviSrcIdx = byteData.length; reviSrcIdx -1 > 0 && byteData[reviSrcIdx -1] == '='; reviSrcIdx--) { 
       
            ; // do nothing. I'm just interested in value of reviSrcIdx
        }

        /* sanity check */
        if (reviSrcIdx -1 == 0) { 
        return null; /* ie all padding */ }

        /* * Set byteDest, this is smaller than byteData due to 4 -> 3 byte munge. * Note that this is an integer division! This fact is used in the logic * l8r. to make sure we don't fall out of the array and create an * OutOfBoundsException and also in handling the remainder */
        byte byteDest[] = new byte[((reviSrcIdx * 3) / 4)];

        /* * Convert from Base64 alphabet to encoded data (The Base64 alphabet is * completely documented in RFC 1521.) The order of the testing is * important as I use the '<' operator which looks at the hex value of * these ASCII chars. So convert from the smallest up * * do all of this in a new array so as not to edit the original input */
        for (iSrcIdx = 0; iSrcIdx < reviSrcIdx; iSrcIdx++) { 
       
            if (byteData[iSrcIdx] == '+')
                byteTemp[iSrcIdx] = 62;
            else if (byteData[iSrcIdx] == '/')
                byteTemp[iSrcIdx] = 63;
            else if (byteData[iSrcIdx] < '0' + 10)
                byteTemp[iSrcIdx] = (byte) (byteData[iSrcIdx] + 52 - '0');
            else if (byteData[iSrcIdx] < ('A' + 26))
                byteTemp[iSrcIdx] = (byte) (byteData[iSrcIdx] - 'A');
            else if (byteData[iSrcIdx] < 'a' + 26)
                byteTemp[iSrcIdx] = (byte) (byteData[iSrcIdx] + 26 - 'a');
        }

        /* * 4bytes -> 3bytes munge Walk through the input array, 32 bits at a * time, converting them from 4 groups of 6 to 3 groups of 8 removing * the two unset most significant bits of each sorce byte as this was * filler, as per Base64 spec. stop before potential buffer overun on * byteDest, remember that byteDest is 3/4 (integer division) the size * of input and won't necessary divide exactly (ie iDestIdx must be < * (integer div byteDest.length / 3)*3 see * http://www.javaworld.com/javaworld/javatips/jw-javatip36-p2.html for * example */
        for (iSrcIdx = 0, iDestIdx = 0; iSrcIdx < reviSrcIdx
                 && iDestIdx < ((byteDest.length / 3) * 3); iSrcIdx += 4) { 
       
            byteDest[iDestIdx++] = (byte) ((byteTemp[iSrcIdx] << 2) & 0xFC | (byteTemp[iSrcIdx + 1] >>> 4) & 0x03);
            byteDest[iDestIdx++] = (byte) ((byteTemp[iSrcIdx + 1] << 4) & 0xF0 | (byteTemp[iSrcIdx + 2] >>> 2) & 0x0F);
            byteDest[iDestIdx++] = (byte) ((byteTemp[iSrcIdx + 2] << 6) & 0xC0 | byteTemp[iSrcIdx + 3] & 0x3F);
        }

        /* * tidy up any remainders if iDestIdx >= ((byteDest.length / 3)*3) but * iSrcIdx < reviSrcIdx then we have at most 2 extra destination bytes * to fill and posiblr 3 input bytes yet to process */
        if (iSrcIdx < reviSrcIdx) { 
       
            if (iSrcIdx < reviSrcIdx - 2) { 
       
                // "3 input bytes left"
                byteDest[iDestIdx++] = (byte) ((byteTemp[iSrcIdx] << 2) & 0xFC | (byteTemp[iSrcIdx + 1] >>> 4) & 0x03);
                byteDest[iDestIdx++] = (byte) ((byteTemp[iSrcIdx + 1] << 4) & 0xF0 | (byteTemp[iSrcIdx + 2] >>> 2) & 0x0F);
            } else if (iSrcIdx < reviSrcIdx - 1) { 
       
                // "2 input bytes left"
                byteDest[iDestIdx++] = (byte) ((byteTemp[iSrcIdx] << 2) & 0xFC | (byteTemp[iSrcIdx + 1] >>> 4) & 0x03);
            }
            /* * wont have just one input byte left (unless input wasn't base64 * encoded ) due to the for loop steps and array sizes, after "=" * pad removed, but for compleatness */
            else { 
       
                throw new IllegalArgumentException("Warning: 1 input bytes left to process. This was not Base64 input");
            }
        }
        return byteDest;
    }

} 

import android.util.Log;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;

import javax.crypto.Cipher;

public final class RSAUtils { 
       
    private static final String KEY_ALGORITHM = "RSA";
    private static final int KEY_SIZE = 2048;//设置长度
    public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
    public static final String RSA_TYPE = "RSA/ECB/PKCS1Padding";


    private final static String PUBLIC_KEY_NAME = "";
    private final static String PRIVATE_KEY_NAME = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDA+JBLaviBNeXEihGBz9FmZXyF86REYDHa9dttSGOWMVg3zINAVPk2R/Fr5ecobeGyRzb6NiK32UDIq2qtu+8NooNURLZ/GlHTcM0NWeO6hLPTfSAwBviMXvzx8W5ps73g/mKs/tQLyEbYTFwMT0buBNr+zl4XSyqXOv4kT1ZiWf+rAjJdqUbW5LPh+syiQ7vGcn0miw8dJL/MwfOC28HToknyvTf598CNf2Z3wO9cpGiEbslGVDNTBCz9TI85+y+68i8D+l1DS7GeBa9wL3pcb7GsYtht87lOD2soWrHogWwH4uIlDFuwvIL48A3co/mQ/K7/Zksg0KQmk2Q6+8x/AgMBAAECggEASNfLiFyZ8BSLZnSEBU+QiSm4JsyA7rqtNy1lpkwUI6b+2RlfVlJ9PItNy+AeMTnBX83YJ/11f5cICHgErg5qP+hf0NibV0F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yw4d5DgabsOZEP5IIaxrK/O7GV1mBWgKKb37ColCbXusJ3uJ7OVnO";
    private final static String SERVICE_PUBLIC_KEY_NAME = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwPiQS2r4gTXlxIoRgc/RZmV8hfOkRGAx2vXbbUhjljFYN8yDQFT5Nkfxa+XnKG3hskc2+jYit9lAyKtqrbvvDaKDVES2fxpR03DNDVnjuoSz030gMAb4jF788fFuabO94P5irP7UC8hG2ExcDE9G7gTa/s5eF0sqlzr+JE9WYln/qwIyXalG1uSz4frMokO7xnJ9JosPHSS/zMHzgtvB06JJ8r03+ffAjX9md8DvXKRohG7JRlQzUwQs/UyPOfsvuvIvA/pdQ0uxngWvcC96XG+xrGLYbfO5Tg9rKFqx6IFsB+LiJQxbsLyC+PAN3KP5kPyu/2ZLINCkJpNkOvvMfwIDAQAB";


    /** * 生成公、私钥 * 根据需要返回String或byte[]类型 * @return */
    public static ArrayList<String> createRSAKeys(){ 
       
        ArrayList<String> array = new ArrayList<>();
        try { 
       
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            //获取公、私钥值
            String publicKeyValue = Base64.encode(publicKey.getEncoded());
            String privateKeyValue = Base64.encode(privateKey.getEncoded());

            //存入
            array.add(publicKeyValue);
            array.add(privateKeyValue);

            Log.e(" >>> ",publicKeyValue);
            Log.e(" >>> ",privateKeyValue);

        } catch (Exception e) { 
       
            e.printStackTrace();
        }
        return array;
    }

    //获取服务器RSA公钥
    public static PublicKey getServicePublicKey() { 
       
        try { 
       
            return  getPublicKey(SERVICE_PUBLIC_KEY_NAME);
        } catch (Exception e) { 
       
            e.printStackTrace();
        }
        return null;
    }


    //获取RSA公钥 根据钥匙字段
    public static PublicKey getPublicKey(String key) { 
       
        try { 
       
            byte[] byteKey = Base64.decode(key);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(byteKey);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePublic(x509EncodedKeySpec);

        } catch (Exception e) { 
       
            e.printStackTrace();
        }
        return null;
    }

    //获取RSA私钥 根据钥匙字段
    private static PrivateKey getPrivateKey(String key) { 
       
        try { 
       
            byte[] byteKey = Base64.decode(key);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(byteKey);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

            return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        } catch (Exception e) { 
       
            e.printStackTrace();
        }

        return null;
    }




    //本地RSA私钥 签名
    public static String sign(String requestData){ 
       
        String signature = null;
        byte[] signed = null;
        try { 
       
// Log.e("=0== 签名前 >>>",requestData);
            PrivateKey privateKey = getPrivateKey(PRIVATE_KEY_NAME);
            Signature Sign = Signature.getInstance(SIGNATURE_ALGORITHM);
            Sign.initSign(privateKey);
            Sign.update(requestData.getBytes());
            signed = Sign.sign();
            signature = Base64.encode(signed);

        } catch (Exception e) { 
       
            e.printStackTrace();
        }
        return signature;
    }


    //公钥验证签名 base64签名 signature 签名内容requestData
    public static boolean verifySign(String requestData, String signature){ 
       
        boolean verifySignSuccess = false;
        try { 
       
            PublicKey publicKey = getServicePublicKey();
            Signature verifySign = Signature.getInstance(SIGNATURE_ALGORITHM);
            verifySign.initVerify(publicKey);
            verifySign.update(requestData.getBytes());

            verifySignSuccess = verifySign.verify(Base64.decode(signature));
            System.out.println(" >>> "+verifySignSuccess);
        } catch (Exception e) { 
       
            e.printStackTrace();
        }

        return verifySignSuccess;
    }


    public static String encrypt(String clearText) { 
       
        String encryptedBase64 = "";
        try { 
       
            Key key = getServicePublicKey();
            final Cipher cipher = Cipher.getInstance(RSA_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //
            byte[] encryptedBytes = cipher.doFinal(clearText.getBytes("UTF-8"));
            encryptedBase64 = Base64.encode(encryptedBytes);

        } catch (Exception e) { 
       
            e.printStackTrace();
        }
        return encryptedBase64;
    }

    public static String encryptSafe(String clearText,String servicePublicKey) { 
       
        String encryptedBase64 = "";
        try { 
       
            Key key = getPublicKey(servicePublicKey);
            final Cipher cipher = Cipher.getInstance(RSA_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //
            byte[] encryptedBytes = cipher.doFinal(clearText.getBytes("UTF-8"));
            encryptedBase64 = Base64.encode(encryptedBytes);

        } catch (Exception e) { 
       
            e.printStackTrace();
        }
        return encryptedBase64;
    }

    public static String decrypt(String encryptedBase64) { 
       
        String decryptedString = "";
        try { 
       
            Key key =  getPrivateKey(PRIVATE_KEY_NAME);
            final Cipher cipher = Cipher.getInstance(RSA_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedBytes = Base64.decode(encryptedBase64);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            decryptedString = new String(decryptedBytes);
        } catch (Exception e) { 
       
            e.printStackTrace();
        }
        return decryptedString;
    }


}

标签: 油位传感器xgyw310

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台