接下來我們介紹DSA數字簽名
DSA
DSA
通過java代碼實現如下
import java
import java
import java
import java
import java
import java
import java
import java
import java
import java
import java
import java
import java
import java
/**
* DSA安全編碼組件
*
* @author 梁棟
* @version
* @since
*/
public abstract class DSACoder extends Coder {
public static final String ALGORITHM =
/**
* 默認密鑰字節數
*
* <pre>
* DSA
* Default Keysize
* Keysize must be a multiple of
* </pre>
*/
private static final int KEY_SIZE =
/**
* 默認種子
*/
private static final String DEFAULT_SEED =
private static final String PUBLIC_KEY =
private static final String PRIVATE_KEY =
/**
* 用私鑰對信息生成數字簽名
*
* @param data
* 加密數據
* @param privateKey
* 私鑰
*
* @return
* @throws Exception
*/
public static String sign(byte[] data
// 解密由base
byte[] keyBytes = decryptBASE
// 構造PKCS
PKCS
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory
// 取私鑰匙對象
PrivateKey priKey = keyFactory
// 用私鑰對信息生成數字簽名
Signature signature = Signature
signature
signature
return encryptBASE
}
/**
* 校驗數字簽名
*
* @param data
* 加密數據
* @param publicKey
* 公鑰
* @param sign
* 數字簽名
*
* @return 校驗成功返回true 失敗返回false
* @throws Exception
*
*/
public static boolean verify(byte[] data
throws Exception {
// 解密由base
byte[] keyBytes = decryptBASE
// 構造X
X
// ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory
// 取公鑰匙對象
PublicKey pubKey = keyFactory
Signature signature = Signature
signature
signature
// 驗證簽名是否正常
return signature
}
/**
* 生成密鑰
*
* @param seed
* 種子
* @return 密鑰對象
* @throws Exception
*/
public static Map<String
KeyPairGenerator keygen = KeyPairGenerator
// 初始化隨機產生器
SecureRandom secureRandom = new SecureRandom();
secureRandom
keygen
KeyPair keys = keygen
DSAPublicKey publicKey = (DSAPublicKey) keys
DSAPrivateKey privateKey = (DSAPrivateKey) keys
Map<String
map
map
return map;
}
/**
* 默認生成密鑰
*
* @return 密鑰對象
* @throws Exception
*/
public static Map<String
return initKey(DEFAULT_SEED);
}
/**
* 取得私鑰
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPrivateKey(Map<String
throws Exception {
Key key = (Key) keyMap
return encryptBASE
}
/**
* 取得公鑰
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPublicKey(Map<String
throws Exception {
Key key = (Key) keyMap
return encryptBASE
}
}
import static org
import java
import org
/**
*
* @author 梁棟
* @version
* @since
*/
public class DSACoderTest {
@Test
public void test() throws Exception {
String inputStr =
byte[] data = inputStr
// 構建密鑰
Map<String
// 獲得密鑰
String publicKey = DSACoder
String privateKey = DSACoder
System
System
// 產生簽名
String sign = DSACoder
System
// 驗證簽名
boolean status = DSACoder
System
assertTrue(status);
}
控制台輸出 公鑰:
MIIBtzCCASwGByqGSM
RV
xqimFQ
C/BYHPUCgYEA
FnEj
g
私鑰:
MIIBTAIBADCCASwGByqGSM
USZpRV
O
ouuEC/BYHPUCgYEA
gLRJFnEj
kImog
簽名:
MC
狀態:
true
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27470.html