Condensed-RSA

2017-10-26  本文已影响0人  SeanC52111

Condensed-RSA Definition:

image.png
package sig;
import java.security.*;
import java.security.interfaces.RSAPublicKey;
import java.security.interfaces.RSAPrivateKey;
import javax.crypto.Cipher;

import Tool.Hasher;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.*;


public class signature {
    public static int byteArrayToInt(byte[] b) {  
        return   b[3] & 0xFF |  
                (b[2] & 0xFF) << 8 |  
                (b[1] & 0xFF) << 16 |  
                (b[0] & 0xFF) << 24;  
    }
        //change a string to integer using sha1 algorithm
    public static int digest(String s) {
        int result = 0;
        try {
            MessageDigest messageDigest =MessageDigest.getInstance("SHA-1");
            byte[] inputByteArray = s.getBytes("utf-8");
            messageDigest.update(inputByteArray);
            byte[] resultbyte = messageDigest.digest();
            result = byteArrayToInt(resultbyte);
        }catch(Exception e) {}
        return result;
    }
    public static void main(String[] args)throws Exception{
        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        gen.initialize(512);
        KeyPair keyPair = gen.generateKeyPair();
        PublicKey publickey = keyPair.getPublic();
        PrivateKey privatekey = keyPair.getPrivate();
        
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publickey;
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privatekey;
        BigInteger n = rsaPublicKey.getModulus();
        BigInteger e = rsaPublicKey.getPublicExponent();
        BigInteger d = rsaPrivateKey.getPrivateExponent();
        BigInteger num1 = new BigInteger("3");
        BigInteger mul = num1.modPow(e, n).modPow(d, n);
        System.out.println(mul);
        
        
        String str1 = new String("2ef7bde608ce5404e97d5f042f95f89f1c232871");
        int hashnum1 = digest(str1);
        String str2 = new String("361772a491529e2ddc1740c7a8187bf466faeb41");
        int hashnum2 = digest(str1);
        BigInteger bighashnum1 = new BigInteger(""+hashnum1);
        BigInteger bighashnum2 = new BigInteger(""+hashnum2);
        long start = System.nanoTime();
        BigInteger mulmod = bighashnum1.multiply(bighashnum2).mod(n);
        
        BigInteger sig1 = bighashnum1.modPow(e,n);
        BigInteger sig2 = bighashnum2.modPow(e, n);
        
        
        BigInteger sigmul = sig1.multiply(sig2).mod(n);
        
        BigInteger decryptedsigmul = sigmul.modPow(d, n);
        long end = System.nanoTime();
        System.out.println(decryptedsigmul.equals(mulmod));
        System.out.println((end-start));
        
    }
}
上一篇下一篇

猜你喜欢

热点阅读