美文网首页
2020-09-16 rsa加密(利用模数和公钥指数)

2020-09-16 rsa加密(利用模数和公钥指数)

作者: lodtap | 来源:发表于2020-09-16 10:57 被阅读0次

    用到的包

    import java.math.BigInteger;

    import java.security.interfaces.RSAPublicKey;

    import java.security.KeyFactory;

    import java.security.spec.RSAPublicKeySpec;

    import java.security.PublicKey;

    import javax.crypto.Cipher;

    import java.io.ByteArrayOutputStream;

    import java.util.Base64;

    public static final String muduls = "138128429165014960214288316246915564109957848967973935739058724552651480736930647934382755460619033465620384391387196627089864034424350665139841418169631846827850418205510584071030219835341930960684577738773846628024223162766742868530563861053134130417499539521288428945157726371402147367583657263208271059771";//模

    public static final String exp = "65537";//指数

    public static void main(String[] args) throws Exception{

    RSAPublicKey res = rsaGY(muduls , exp );

    //待加密内容

    String text = "我是一个小test";

    //加密后内容

    String en_text = a(res, text);

    public static RSAPublicKey rsaGY(String str, String str2) {

        try {

            return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(new BigInteger(str), new BigInteger(str2)));

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

    public static String a(PublicKey publicKey, String str) throws Exception {

        Cipher instance = Cipher.getInstance("RSA");

        instance.init(1, publicKey);

        byte[] bytes = str.getBytes("UTF-8");

        int length = bytes.length;

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int i = 0;

        int i2 = 0;

        while (true) {

            int i3 = length - i;

            if (i3 > 0) {

                byte[] doFinal = i3 > 117 ? instance.doFinal(bytes, i, 117) : instance.doFinal(bytes, i, i3);

                byteArrayOutputStream.write(doFinal, 0, doFinal.length);

                i2++;

                i = i2 * 117;

            } else {

                byte[] byteArray = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();

                return Base64.getEncoder().encodeToString(byteArray);

            }

        }

    }

    相关文章

      网友评论

          本文标题:2020-09-16 rsa加密(利用模数和公钥指数)

          本文链接:https://www.haomeiwen.com/subject/pzscyktx.html