IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> android非对称加密算法DSA -> 正文阅读

[移动开发]android非对称加密算法DSA

step1: D:\workspace\DsaDemo\app\src\main\java\com\mondor\dsademo\MainActivity.java

package com.mondor.dsademo;

import androidx.appcompat.app.AppCompatActivity;


import java.math.BigInteger;

import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String message = "Hi I think I have an A";
        String message2 = "Hi I think I have an A";
        Session session = Session.getInstance(true);
        Pair<BigInteger, BigInteger> privateKeys = session.getPrivateKey();
        Pair<BigInteger, BigInteger> sign = DSA.sign(true, message,
                session.getGlobalKeyG(), session.getGlobalKeyP(),
                session.getGlobalKeyQ(), privateKeys.getFirst());
        boolean isPass = DSA.verify(true, message2, sign.getFirst(),
                sign.getSecond(), session.getGlobalKeyG(),
                session.getGlobalKeyP(), session.getGlobalKeyQ(),
                privateKeys.getSecond());
        session.destroy();
    }
}

step2: D:\workspace\DsaDemo\app\src\main\java\com\mondor\dsademo\DSA.java

package com.mondor.dsademo;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;


/**
 * @author robertomm
 *
 */
public class DSA {

    /*
     * Static methods -> (M,r,s) sign(M, claves) Boolean verify(M, r, s)
     */
    private static boolean debug;

    /**
     * Method to create the signature
     *
     * @param deb
     *            , boolean for activate the debug mode
     * @param message
     *            , string to make the signature
     * @param publcG
     *            , the global public g key
     * @param publicP
     *            , the global public p key
     * @param publicQ
     *            , the global public q key
     * @param privateX
     *            , the personal private x key
     * @return Pair<String, Pair<BigInteger, BigInteger>>, Pair of the message
     *         and another Pair with (r,s)
     */
    public static Pair<BigInteger, BigInteger> sign(boolean deb,
                                                    String message, BigInteger publcG, BigInteger publicP,
                                                    BigInteger publicQ, BigInteger privateX) {
        debug = deb;
        debugMode("=== CREATING SIGNATURE ===", true);

        // K
        debugMode("Creating auxiliar variable K .......... ", false);
        BigInteger k = new BigInteger(publicQ.bitLength(), new SecureRandom());
        while (k.compareTo(publicQ) != -1 && k.compareTo(BigInteger.ZERO) != 1) {
            k = new BigInteger(publicQ.bitLength(), new SecureRandom());
        }
        debugMode("[OK]", true);

        // R
        debugMode("Creating R .......... ", false);
        BigInteger r = publcG.modPow(k, publicP).mod(publicQ);
        debugMode("[OK]", true);

        // S
        debugMode("Creating S .......... ", false);
        MessageDigest md = null;
        BigInteger s = BigInteger.ONE;
        try {
            md = MessageDigest.getInstance("SHA-1");
            md.update(message.getBytes());
            BigInteger hash = new BigInteger(md.digest());
            s = (k.modInverse(publicQ).multiply(hash.add(privateX.multiply(r))))
                    .mod(publicQ);
        } catch (Exception e) {
            e.printStackTrace();
        }
        debugMode("[OK]", true);
        Pair<BigInteger, BigInteger> result = new Pair<BigInteger, BigInteger>(
                r, s);
        return result;
    }

    /**
     * Method to verify the integrity of a message
     *
     * @param deb , boolean for activate the debug mode   激活调试模式
     * @param message , string to make the signature        制作签名的字符串
     * @param r  , signature value          签名值
     * @param s , signature value           签名值
     * @param publcG   , the global public g key        全局公钥 g 密钥
     * @param publicP , the global public p key          全局公钥 p 密钥
     * @param publicQ  , the global public q key             全局公钥
     * @param privateX  , the personal private x key  个人私钥 x 密钥
     * @return if the message is verified with (r,s)  如果消息通过 (r,s) 验证
     */
    public static Boolean verify(boolean deb, String message, BigInteger r,
                                 BigInteger s, BigInteger publcG, BigInteger publicP,
                                 BigInteger publicQ, BigInteger privateY) {
        debugMode("=== VERIFYING SIGNATURE ===", true);
        debug = deb;
        MessageDigest md;
        BigInteger v = BigInteger.ZERO;
        try {
            md = MessageDigest.getInstance("SHA-1");
            md.update(message.getBytes());
            BigInteger messagehash = new BigInteger(md.digest());
            debugMode("Creating W .......... ", false);
            BigInteger w = s.modInverse(publicQ);
            debugMode("[OK]", true);
            debugMode("Creating U1 .......... ", false);
            BigInteger u1 = messagehash.multiply(w).mod(publicQ);
            debugMode("[OK]", true);
            debugMode("Creating U2 .......... ", false);
            BigInteger u2 = r.multiply(w).mod(publicQ);
            debugMode("[OK]", true);
            debugMode("Creating V .......... ", false);
            v = ((publcG.modPow(u1, publicP).multiply(privateY.modPow(u2,
                    publicP))).mod(publicP)).mod(publicQ);
            debugMode("[OK]", true);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        return v.compareTo(r) == 0;
    }

    /**
     *  s, the string to write.
     */
    private static void debugMode(String s, boolean ln) {
        if (debug) {
            if (ln) {
                System.out.println(s);
            } else {
                System.out.print(s);
            }
        }
    }

}

step3: D:\workspace\DsaDemo\app\src\main\java\com\mondor\dsademo\Pair.java

package com.mondor.dsademo;


public class Pair<F, S> {
    private F first; // first member of pair
    private S second; // second member of pair

    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    public void setFirst(F first) {
        this.first = first;
    }

    public void setSecond(S second) {
        this.second = second;
    }

    public F getFirst() {
        return first;
    }

    public S getSecond() {
        return second;
    }
}

step4: D:\workspace\DsaDemo\app\src\main\java\com\mondor\dsademo\Session.java

package com.mondor.dsademo;


        import java.math.BigInteger;
        import java.security.SecureRandom;
        import java.util.Random;

/**
 * @author robertomm
 */
public class Session {

    private static Session session;
    private static boolean debug;
    private BigInteger globalKeyP;
    private BigInteger globalKeyQ;
    private BigInteger globalKeyG;
    private static int L = 512;

    /**
     * This method is the one that gives you the instance of Session or create a
     * new one if it isn't created.
     *
     * @return Object Session
     */
    public static Session getInstance(boolean debugMode) {
        if (session == null)
            session = new Session(debugMode);

        return session;

    }

    /**
     */
    private Session(boolean b) {
        if (b) {
            debug = true;
        } else {
            debug = false;
        }
        debugMode("=== CREATION OF GLOBAL KEYS ===", true);

        // ==Q==
        debugMode("Creating global key Q .......... ", false);

        globalKeyQ = new BigInteger(160, 20, new SecureRandom());
        debugMode("[OK]", true);

        // ==P==
        debugMode("Creating global key P (be patient).......... ", false);

        BigInteger tempP;
        BigInteger tempP2;
        SecureRandom rand = new SecureRandom();
        do {
            tempP = new BigInteger(L, 20, rand);
            tempP2 = tempP.subtract(BigInteger.ONE);
            tempP = tempP.subtract(tempP2.remainder(globalKeyQ));
        } while (!tempP.isProbablePrime(20) || tempP.bitLength() != L);

        BigInteger p = tempP;

        globalKeyP = p;
        debugMode("[OK]", true);

        // ==G==
        debugMode("Creating global key G .......... ", false);
        BigInteger p1 = globalKeyP.subtract(BigInteger.ONE);
        BigInteger exp = p1.divide(globalKeyQ);

        BigInteger tempg;
        Random random = new Random();
        do {
            tempg = new BigInteger(p1.bitLength(), random);
        } while (tempg.compareTo(p1) != -1
                && tempg.compareTo(BigInteger.ONE) != 1);
        globalKeyG = tempg.modPow(exp, p);
        debugMode("[OK]", true);
        System.out.println("");
        System.out.println("Q: " + globalKeyQ);
        System.out.println("P: " + globalKeyP);
        System.out.println("G: " + globalKeyG);
    }

    /**
     * @return the globalKeyP
     */
    public BigInteger getGlobalKeyP() {
        return globalKeyP;
    }

    /**
     * @return the globalKeyQ
     */
    public BigInteger getGlobalKeyQ() {
        return globalKeyQ;
    }

    /**
     * @return the globalKeyG
     */
    public BigInteger getGlobalKeyG() {
        return globalKeyG;
    }

    /**
     *            s, the string to write.
     */
    private void debugMode(String s, boolean ln) {
        if (debug) {
            if (ln) {
                System.out.println(s);
            } else {
                System.out.print(s);
            }
        }
    }

    /**
     * @return Pair<BigInteger, BigInteger> the pair of (x,y) the private and
     *         the public personal key
     */
    public Pair<BigInteger, BigInteger> getPrivateKey() {

        debugMode("=== CREATION OF PRIVATE KEY ===", true);
        // Private key
        debugMode("Creating private key X .......... ", false);
        BigInteger privK = new BigInteger(getGlobalKeyQ().bitLength(),
                new SecureRandom());
        while (privK.compareTo(globalKeyQ) != -1) {
            privK = new BigInteger(getGlobalKeyQ().bitLength(),
                    new SecureRandom());
        }
        debugMode("[OK]", true);
        debugMode("Creating private key Y .......... ", false);
        // Public key:
        BigInteger pubK = getGlobalKeyG().modPow(privK, getGlobalKeyP());

        Pair<BigInteger, BigInteger> result = new Pair<BigInteger, BigInteger>(
                privK, pubK);
        debugMode("[OK]", true);

        return result;
    }

    /**
     * Method to destroy the Session
     */
    public void destroy() {
        debugMode("=== DESTROYING SESSION ===", true);
        globalKeyP = null;
        globalKeyQ = null;
        globalKeyG = null;
        session = null;
        debugMode("Session destroyed", true);
    }

}

end

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-05-13 11:51:34  更:2022-05-13 11:51:57 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 1:27:26-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码