android非对称加密算法DSA

android非对称加密算法DSA,第1张

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>, 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 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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/920604.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存