⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sharesec.java

📁 Shamir秘密分享算法的java实现
💻 JAVA
字号:
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ShareSec {

	public static  int primeLength = 200;

	public static  int KLength = 40;

	public static  int coefLength = 10;

	public static  int maxXLength = 10;

	static int DIVIDESCALE = 100;

	Polynomial poly;

	BigInteger p;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
	}


	/**
	 * Generate a Polynomial
	 * 
	 * @param int
	 *            sharenum pieces to share
	 */
	public Polynomial initPoly(int sharenum,BigInteger secValue) {
		p = BigInteger.probablePrime(primeLength, new Random(1));

		BigInteger K = secValue.mod(p);//BigInteger.probablePrime(KLength, new Random(1));
		
		Map<Integer, BigDecimal> polyMap = new HashMap<Integer, BigDecimal>();
		polyMap.put(new Integer(0), new BigDecimal(K));

		int maxpow = sharenum;
		Random rand = new Random(maxpow);
		
		for (int iloop = 1; iloop <= maxpow - 1; iloop++) { // 多项式数次数比门限少1
			BigInteger bitmp = new BigInteger(coefLength, rand);

			polyMap.put(new Integer(iloop), new BigDecimal(bitmp.mod(p))); // 
																			
		}
		
		poly = new Polynomial(polyMap);
		return poly;
	}

	public BigInteger getP() {
		return p;
	}

	/**
	 * 由x求出多项式的值Y
	 */
	public BigInteger getPoly_Y(BigInteger x) {
		return poly.getCalValue(x).toBigInteger();
	}

	
	/**
	 * 由数值对求出多项式-用多项式插值法
	 * 
	 * @Map map <BigInteger,BigDecimal>
	 */
	public BigInteger getPolynomialValue(Map map) {
		Object[] xArray = map.keySet().toArray();
		BigDecimal result = new BigDecimal(0);
		BigDecimal decZero = new BigDecimal(0);

		for (int iloop = 0; iloop < xArray.length; iloop++) {
			BigDecimal result1 = new BigDecimal(1);
			for (int jloop = 0; jloop < xArray.length; jloop++) {
				if (jloop == iloop)
					continue;

				result1 = result1.multiply(
						decZero.subtract(new BigDecimal(
								(BigInteger) xArray[jloop])));
				result1=result1.divide(
						new BigDecimal(((BigInteger) xArray[iloop])
								.subtract((BigInteger) xArray[jloop])),
						DIVIDESCALE, BigDecimal.ROUND_HALF_EVEN);

			}
			result=result.add(result1.multiply((BigDecimal) (map.get(xArray[iloop]))));
		}

		result =result.add(new BigDecimal(0.5)); 
		return result.toBigInteger();
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -