java RSA2 加密、解密 、签名和验证签名

突然发现接收百度资源太多了,我也回馈一下吧。

RSA2 标准算法名称 SHA256WithRSA

1、RSA非对称加密技术

2、SHA256 是SHA-2下细分出的一种算法

SHA-2,名称来自于安全散列算法2(英语:Secure Hash Algorithm 2)的缩写,一种密码散列函数算法标准,由美国国家安全局研发,属于SHA算法之一,是SHA-1的后继者。

详细介绍连接:https://blog.csdn.net/u011583927/article/details/80905740

1、加密和解密
公钥是公开的密钥,有加密方使用。只用于加密无法解密。私钥是不公开的,别人无法获取,用户解密。
注意的是,为什么私钥对同一数据进行签名加密的结果是一样的,使用公钥进行加密就不一样了呢?
详细请参考:https://blog.csdn.net/guyongqiangx/article/details/74930951

2、签名和验证签名
签名是由发送数据的一方发起的,防止传输过程中被篡改数据内容。因此签名使用的是私钥。而验证签名使用的是公钥。

附带:
php RSA2 加密、解密 、签名和验证签名
https://blog.csdn.net/TaLinBoy/article/details/106124132

IOS:RSA2 加密、解密 、签名和验证签名
https://blog.csdn.net/TaLinBoy/article/details/106140526

无法使用 import org.apache.commons.codec.binary.Base64 ?
到下面连接下载:导入jar包
https://commons.apache.org/proper/commons-codec/download_codec.cgi


import android.content.Context;
import android.util.Log;
import org.apache.commons.codec.binary.Base64;

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.KeySpec;
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 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvJWHTWgcfPjzW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xtBn/sMbP9vVnp1Q6KcXCH8pWnHjziS/Wv2cwjYWMVEOj0vICtiwei7G9oulgzBRnO8k8kIeqxrDLwHC9w2/Zh6R39f49xqIo2iHIiVSGObNEqS9NkGbKVPR1WlVzB2VKGc4tsciWYagi98OZwMuvz29Ums0yiG06HlUSAhAWEb+qKeoT4e3/DtXRbu8fXEF4EzjR0X4O6sS3PdwKpKkIlih99IdbnJ0jL8ALqhgV6NXEe/az4+I5WHM7lzviLVWfxIIQIDAQAB";


    /**
     * 生成公、私钥
     * 根据需要返回String或byte[]类型
     * @return
     */
    public static ArrayList createRSAKeys(){
        ArrayList 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.encodeBase64String(publicKey.getEncoded());
            String privateKeyValue = Base64.encodeBase64String(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 getPublicKey() {
        try {
            return  getPublicKey(PUBLIC_KEY_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取本地RSA公钥
    public static String getPublicKeyString() {
        try {
            return  PUBLIC_KEY_NAME;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取服务器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.decodeBase64(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.decodeBase64(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.encodeBase64String(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.decodeBase64(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.encodeBase64String(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.decodeBase64(encryptedBase64);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            decryptedString = new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedString;
    }


}


你可能感兴趣的:(安卓开发)