import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.io.*;
import java.math.BigInteger;
/**
* RSA 工具類。提供加密,解密,生成密鑰對等方法。
* 需要到http://www.bouncycastle.org下載bcprov-jdk14-123.jar。
* @author xiaoyusong
* mail: [email protected]
* msn:[email protected]
* @since 2004-5-20
*
*/
public class RSAUtil {
/**
* 生成密鑰對
* @return KeyPair
* @throws EncryptException
*/
public static KeyPair generateKeyPair() throws EncryptException {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
final int KEY_SIZE = 1024;//沒什麼好說的了,這個值關繫到塊加密的大小,可以更改,但是不要太大,否則效率會低
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.genKeyPair();
return keyPair;
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
* 生成公鑰
* @param molus
* @param publicExponent
* @return RSAPublicKey
* @throws EncryptException
*/
public static RSAPublicKey generateRSAPublicKey(byte[] molus, byte[] publicExponent) throws EncryptException {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new EncryptException(ex.getMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new EncryptException(ex.getMessage());
}
}
/**
* 生成私鑰
* @param molus
* @param privateExponent
* @return RSAPrivateKey
* @throws EncryptException
*/
public static RSAPrivateKey generateRSAPrivateKey(byte[] molus, byte[] privateExponent) throws EncryptException {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new EncryptException(ex.getMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new EncryptException(ex.getMessage());
}
}
/**
* 加密
* @param key 加密的密鑰
* @param data 待加密的明文數據
* @return 加密後的數據
* @throws EncryptException
*/
public static byte[] encrypt(Key key, byte[] data) throws EncryptException {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, key);
int blockSize = cipher.getBlockSize();//獲得加密塊大小,如:加密前數據為128個byte,而key_size=1024 加密塊大小為127 byte,加密後為128個byte;因此共有2個加密塊,第一個127 byte第二個為1個byte
int outputSize = cipher.getOutputSize(data.length);//獲得加密塊加密後塊大小
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
//這裡面doUpdate方法不可用,查看源代碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到ByteArrayOutputStream中,而最後doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
* 解密
* @param key 解密的密鑰
* @param raw 已經加密的數據
* @return 解密後的明文
* @throws EncryptException
*/
public static byte[] decrypt(Key key, byte[] raw) throws EncryptException {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
File file = new File("test.html");
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] tmpbuf = new byte[1024];
int count = 0;
while ((count = in.read(tmpbuf)) != -1) {
bout.write(tmpbuf, 0, count);
tmpbuf = new byte[1024];
}
in.close();
byte[] orgData = bout.toByteArray();
KeyPair keyPair = RSAUtil.generateKeyPair();
RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
byte[] pubModBytes = pubKey.getMolus().toByteArray();
byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
byte[] priModBytes = priKey.getMolus().toByteArray();
byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
RSAPublicKey recoveryPubKey = RSAUtil.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
RSAPrivateKey recoveryPriKey = RSAUtil.generateRSAPrivateKey(priModBytes,priPriExpBytes);
byte[] raw = RSAUtil.encrypt(priKey, orgData);
file = new File("encrypt_result.dat");
OutputStream out = new FileOutputStream(file);
out.write(raw);
out.close();
byte[] data = RSAUtil.decrypt(recoveryPubKey, raw);
file = new File("decrypt_result.html");
out = new FileOutputStream(file);
out.write(data);
out.flush();
out.close();
}
}
http://book.77169.org/data/web5409/20050328/20050328__3830259.html
這個行吧
http://soft.zdnet.com.cn/software_zone/2007/0925/523319.shtml
再參考這個吧
http://topic.csdn.net/t/20040427/20/3014655.html
② java十大演算法
演算法一:快速排序演算法
快速排序是由東尼·霍爾所發展的一種排序演算法。在平均狀況下,排序 n 個項目要Ο(n log n)次比較。在最壞狀況下則需要Ο(n2)次比較,但這種狀況並不常見。事實上,快速排序通常明顯比其他Ο(n log n) 演算法更快,因為它的內部循環(inner loop)可以在大部分的架構上很有效率地被實現出來。
快速排序使用分治法(Divide and conquer)策略來把一個串列(list)分為兩個子串列(sub-lists)。
演算法步驟:
1 從數列中挑出一個元素,稱為 "基準"(pivot),
2 重新排序數列,所有元素比基準值小的擺放在基準前面,所有元素比基準值大的擺在基準的後面(相同的數可以到任一邊)。在這個分區退出之後,該基準就處於數列的中間位置。這個稱為分區(partition)操作。
3 遞歸地(recursive)把小於基準值元素的子數列和大於基準值元素的子數列排序。
遞歸的最底部情形,是數列的大小是零或一,也就是永遠都已經被排序好了。雖然一直遞歸下去,但是這個演算法總會退出,因為在每次的迭代(iteration)中,它至少會把一個元素擺到它最後的位置去。
演算法二:堆排序演算法
堆排序(Heapsort)是指利用堆這種數據結構所設計的一種排序演算法。堆積是一個近似完全二叉樹的結構,並同時滿足堆積的性質:即子結點的鍵值或索引總是小於(或者大於)它的父節點。
堆排序的平均時間復雜度為Ο(nlogn) 。
演算法步驟:
創建一個堆H[0..n-1]
把堆首(最大值)和堆尾互換
3. 把堆的尺寸縮小1,並調用shift_down(0),目的是把新的數組頂端數據調整到相應位置
4. 重復步驟2,直到堆的尺寸為1
演算法三:歸並排序
歸並排序(Merge sort,台灣譯作:合並排序)是建立在歸並操作上的一種有效的排序演算法。該演算法是採用分治法(Divide and Conquer)的一個非常典型的應用。
演算法步驟:
1. 申請空間,使其大小為兩個已經排序序列之和,該空間用來存放合並後的序列
2. 設定兩個指針,最初位置分別為兩個已經排序序列的起始位置
3. 比較兩個指針所指向的元素,選擇相對小的元素放入到合並空間,並移動指針到下一位置
4. 重復步驟3直到某一指針達到序列尾
5. 將另一序列剩下的所有元素
③ 關於java新聞網站的演算法
問:新聞網站,如新浪網站,比如說國際足球頻道,每天會有跟新。請問這塊在代碼設計的地方,是從資料庫中讀取5條最新的(按照日期)還是說做一個程序由編輯強制置頂?
答:是從資料庫中讀取5條最新的(按照日期)
問:如果是論壇,需要把點擊最高的新聞自動排到前面,這個怎麼處理,需要用到servletcontext嗎 ?
答:讀取點擊最高的新聞記錄(你想讀取幾條就幾條),然後放到網頁上去,就怎麼回事.......跟你平時放其他數據沒什麼區別,都是根據條件取數據而已.
④ 標簽傳播演算法 可以用於計算信息傳播的覆蓋率嗎
首先我們從氫氧化鈉溶液增重2.2g入手,可以知道生成的二氧化碳的質量為2.2g。再根據CaCO3+2HCl==CaCl2+CO2↑+H2O,我們可以算出碳酸鈣的質量為5g,也就是說碳酸鈣的純度是100%。那麼碳酸鈣的質量分數就是100%。2NaOH+CO2=Na2CO3+H2O,根據這條方程式可以算出氫氧化鈉的質量為4g,那麼質量分數就是4/100=4%希望能夠幫到你!
⑤ 標簽傳播演算法是一種分類演算法,還是聚類演算法
在聚類分析中,K-均值聚類演算法(k-meansalgorithm)是無監督分類中的一種基本方法,其也稱為C-均值演算法,其基本思想是:通過迭代的方法,逐次更新各聚類中心的值,直至得到最好的聚類結果.\x0d假設要把樣本集分為c個類別,演算法如下:\x0d(1)適當選擇c個類的初始中心;\x0d(2)在第k次迭代中,對任意一個樣本,求其到c個中心的距離,將該樣本歸到距離最短的中心所在的類,\x0d(3)利用均值等方法更新該類的中心值;\x0d(4)對於所有的c個聚類中心,如果利用(2)(3)的迭代法更新後,值保持不變,則迭代結束,否則繼續迭代.\x0d下面介紹作者編寫的一個分兩類的程序,可以把其作為函數調用.\x0d%%function[samp1,samp2]=kmeans(samp);作為調用函數時去掉注釋符\x0dsamp=[11.15066.72222.31395.901811.08275.745913.217413.82434.80050.937012.3576];%樣本集\x0d[l0l]=size(samp);\x0d%%利用均值把樣本分為兩類,再將每類的均值作為聚類中心\x0dth0=mean(samp);n1=0;n2=0;c1=0.0;c1=double(c1);c2=c1;fori=1:lifsamp(i)<th0\x0dc1=c1+samp(i);n1=n1+1;elsec2=c2+samp(i);n2=n2+1;endendc1=c1/n1;c2=c2/n2;%初始聚類中心t=0;cl1=c1;cl2=c2;\x0dc11=c1;c22=c2;%聚類中心whilet==0samp1=zeros(1,l);\x0dsamp2=samp1;n1=1;n2=1;fori=1:lifabs(samp(i)-c11)<abs(samp(i)-c22)\x0dsamp1(n1)=samp(i);\x0dcl1=cl1+samp(i);n1=n1+1;\x0dc11=cl1/n1;elsesamp2(n2)=samp(i);\x0dcl2=cl2+samp(i);n2=n2+1;\x0dc22=cl2/n2;endendifc11==c1&&c22==c2t=1;endcl1=c11;cl2=c22;\x0dc1=c11;c2=c22;\x0dend%samp1,samp2為聚類的結果.\x0d初始中心值這里採用均值的法,也可以根據問題的性質,用經驗的方法來確定,或者將樣本集隨機分成c類,計算每類的均值.\x0dk-均值演算法需要事先知道分類的數量,這是其不足之處.
⑥ 如何用Java實現遺傳演算法
通過遺傳演算法走迷宮。雖然圖1和圖2均成功走出迷宮,但是圖1比圖2的路徑長的多,且復雜,遺傳演算法可以計算出有多少種可能性,並選擇其中最簡潔的作為運算結果。
示例圖1:
實現代碼:
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Iterator;
importjava.util.LinkedList;
importjava.util.List;
importjava.util.Random;
/**
* 用遺傳演算法走迷宮
*
* @author Orisun
*
*/
publicclassGA {
intgene_len;// 基因長度
intchrom_len;// 染色體長度
intpopulation;// 種群大小
doublecross_ratio;// 交叉率
doublemuta_ratio;// 變異率
intiter_limit;// 最多進化的代數
List<boolean[]> indivials;// 存儲當代種群的染色體
Labyrinth labyrinth;
intwidth;//迷宮一行有多少個格子
intheight;//迷宮有多少行
publicclassBI {
doublefitness;
boolean[] indv;
publicBI(doublef,boolean[] ind) {
fitness = f;
indv = ind;
}
publicdoublegetFitness() {
returnfitness;
}
publicboolean[] getIndv() {
returnindv;
}
}
List<BI> best_indivial;// 存儲每一代中最優秀的個體
publicGA(Labyrinth labyrinth) {
this.labyrinth=labyrinth;
this.width = labyrinth.map[0].length;
this.height = labyrinth.map.length;
chrom_len =4* (width+height);
gene_len =2;
population =20;
cross_ratio =0.83;
muta_ratio =0.002;
iter_limit =300;
indivials =newArrayList<boolean[]>(population);
best_indivial =newArrayList<BI>(iter_limit);
}
publicintgetWidth() {
returnwidth;
}
publicvoidsetWidth(intwidth) {
this.width = width;
}
publicdoublegetCross_ratio() {
returncross_ratio;
}
publicList<BI> getBest_indivial() {
returnbest_indivial;
}
publicLabyrinth getLabyrinth() {
returnlabyrinth;
}
publicvoidsetLabyrinth(Labyrinth labyrinth) {
this.labyrinth = labyrinth;
}
publicvoidsetChrom_len(intchrom_len) {
this.chrom_len = chrom_len;
}
publicvoidsetPopulation(intpopulation) {
this.population = population;
}
publicvoidsetCross_ratio(doublecross_ratio) {
this.cross_ratio = cross_ratio;
}
publicvoidsetMuta_ratio(doublemuta_ratio) {
this.muta_ratio = muta_ratio;
}
publicvoidsetIter_limit(intiter_limit) {
this.iter_limit = iter_limit;
}
// 初始化種群
publicvoidinitPopulation() {
Random r =newRandom(System.currentTimeMillis());
for(inti =0; i < population; i++) {
intlen = gene_len * chrom_len;
boolean[] ind =newboolean[len];
for(intj =0; j < len; j++)
ind[j] = r.nextBoolean();
indivials.add(ind);
}
}
// 交叉
publicvoidcross(boolean[] arr1,boolean[] arr2) {
Random r =newRandom(System.currentTimeMillis());
intlength = arr1.length;
intslice =0;
do{
slice = r.nextInt(length);
}while(slice ==0);
if(slice < length /2) {
for(inti =0; i < slice; i++) {
booleantmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
}else{
for(inti = slice; i < length; i++) {
booleantmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
}
}
// 變異
publicvoidmutation(boolean[] indivial) {
intlength = indivial.length;
Random r =newRandom(System.currentTimeMillis());
indivial[r.nextInt(length)] ^=false;
}
// 輪盤法選擇下一代,並返回當代最高的適應度值
publicdoubleselection() {
boolean[][] next_generation =newboolean[population][];// 下一代
intlength = gene_len * chrom_len;
for(inti =0; i < population; i++)
next_generation[i] =newboolean[length];
double[] cumulation =newdouble[population];
intbest_index =0;
doublemax_fitness = getFitness(indivials.get(best_index));
cumulation[0] = max_fitness;
for(inti =1; i < population; i++) {
doublefit = getFitness(indivials.get(i));
cumulation[i] = cumulation[i -1] + fit;
// 尋找當代的最優個體
if(fit > max_fitness) {
best_index = i;
max_fitness = fit;
}
}
Random rand =newRandom(System.currentTimeMillis());
for(inti =0; i < population; i++)
next_generation[i] = indivials.get(findByHalf(cumulation,
rand.nextDouble() * cumulation[population -1]));
// 把當代的最優個體及其適應度放到best_indivial中
BI bi =newBI(max_fitness, indivials.get(best_index));
// printPath(indivials.get(best_index));
//System.out.println(max_fitness);
best_indivial.add(bi);
// 新一代作為當前代
for(inti =0; i < population; i++)
indivials.set(i, next_generation[i]);
returnmax_fitness;
}
// 折半查找
publicintfindByHalf(double[] arr,doublefind) {
if(find <0|| find ==0|| find > arr[arr.length -1])
return-1;
intmin =0;
intmax = arr.length -1;
intmedium = min;
do{
if(medium == (min + max) /2)
break;
medium = (min + max) /2;
if(arr[medium] < find)
min = medium;
elseif(arr[medium] > find)
max = medium;
else
returnmedium;
}while(min < max);
returnmax;
}
// 計算適應度
publicdoublegetFitness(boolean[] indivial) {
intlength = indivial.length;
// 記錄當前的位置,入口點是(1,0)
intx =1;
inty =0;
// 根據染色體中基因的指導向前走
for(inti =0; i < length; i++) {
booleanb1 = indivial[i];
booleanb2 = indivial[++i];
// 00向左走
if(b1 ==false&& b2 ==false) {
if(x >0&& labyrinth.map[y][x -1] ==true) {
x--;
}
}
// 01向右走
elseif(b1 ==false&& b2 ==true) {
if(x +1< width && labyrinth.map[y][x +1] ==true) {
x++;
}
}
// 10向上走
elseif(b1 ==true&& b2 ==false) {
if(y >0&& labyrinth.map[y -1][x] ==true) {
y--;
}
}
// 11向下走
elseif(b1 ==true&& b2 ==true) {
if(y +1< height && labyrinth.map[y +1][x] ==true) {
y++;
}
}
}
intn = Math.abs(x - labyrinth.x_end) + Math.abs(y -labyrinth.y_end) +1;
// if(n==1)
// printPath(indivial);
return1.0/ n;
}
// 運行遺傳演算法
publicbooleanrun() {
// 初始化種群
initPopulation();
Random rand =newRandom(System.currentTimeMillis());
booleansuccess =false;
while(iter_limit-- >0) {
// 打亂種群的順序
Collections.shuffle(indivials);
for(inti =0; i < population -1; i +=2) {
// 交叉
if(rand.nextDouble() < cross_ratio) {
cross(indivials.get(i), indivials.get(i +1));
}
// 變異
if(rand.nextDouble() < muta_ratio) {
mutation(indivials.get(i));
}
}
// 種群更替
if(selection() ==1) {
success =true;
break;
}
}
returnsuccess;
}
// public static void main(String[] args) {
// GA ga = new GA(8, 8);
// if (!ga.run()) {
// System.out.println("沒有找到走出迷宮的路徑.");
// } else {
// int gen = ga.best_indivial.size();
// boolean[] indivial = ga.best_indivial.get(gen - 1).indv;
// System.out.println(ga.getPath(indivial));
// }
// }
// 根據染色體列印走法
publicString getPath(boolean[] indivial) {
intlength = indivial.length;
intx =1;
inty =0;
LinkedList<String> stack=newLinkedList<String>();
for(inti =0; i < length; i++) {
booleanb1 = indivial[i];
booleanb2 = indivial[++i];
if(b1 ==false&& b2 ==false) {
if(x >0&& labyrinth.map[y][x -1] ==true) {
x--;
if(!stack.isEmpty() && stack.peek()=="右")
stack.poll();
else
stack.push("左");
}
}elseif(b1 ==false&& b2 ==true) {
if(x +1< width && labyrinth.map[y][x +1] ==true) {
x++;
if(!stack.isEmpty() && stack.peek()=="左")
stack.poll();
else
stack.push("右");
}
}elseif(b1 ==true&& b2 ==false) {
if(y >0&& labyrinth.map[y -1][x] ==true) {
y--;
if(!stack.isEmpty() && stack.peek()=="下")
stack.poll();
else
stack.push("上");
}
}elseif(b1 ==true&& b2 ==true) {
if(y +1< height && labyrinth.map[y +1][x] ==true) {
y++;
if(!stack.isEmpty() && stack.peek()=="上")
stack.poll();
else
stack.push("下");
}
}
}
StringBuilder sb=newStringBuilder(length/4);
Iterator<String> iter=stack.descendingIterator();
while(iter.hasNext())
sb.append(iter.next());
returnsb.toString();
}
}
⑦ 標簽傳播演算法為什麼具有線性時間復雜度
計算公式:K(N)=AO(N)+B線性時間在計算復雜性理論,一個被稱為線性時間或Ο(n)時間的演算法,表示此演算法解題所需時間正比於輸入資料的大小,通常以n表示。換句話說,執行時間與輸入資料大小為線性比例。例如將一列數字加總的所需時間,正比於串列的長度。