熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

談談Java加密技術(六)

2022-06-13   來源: Java高級技術 

  接下來我們介紹DSA數字簽名非對稱加密的另一種實現

  DSA

  DSADigital Signature Algorithm 是Schnorr和ElGamal簽名算法的變種被美國NIST作為DSS(DigitalSignature Standard)簡單的說這是一種更高級的驗證方式用作數字簽名不單單只有公鑰私鑰還有數字簽名私鑰加密生成數字簽名公鑰驗證數據及簽名如果數據和簽名不匹配則認為驗證失敗!數字簽名的作用就是校驗數據在傳輸過程中不被修改數字簽名是單向加密的升級!

  

  

  

  

  通過java代碼實現如下

  import javasecurityKey;
import javasecurityKeyFactory;
import javasecurityKeyPair;
import javasecurityKeyPairGenerator;
import javasecurityPrivateKey;
import javasecurityPublicKey;
import javasecuritySecureRandom;
import javasecuritySignature;
import javasecurityinterfacesDSAPrivateKey;
import javasecurityinterfacesDSAPublicKey;
import javasecurityspecPKCSEncodedKeySpec;
import javasecurityspecXEncodedKeySpec;
import javautilHashMap;
import javautilMap;

  /**
 * DSA安全編碼組件
 *
 * @author 梁棟
 * @version
 * @since
 */
public abstract class DSACoder extends Coder {

  public static final String ALGORITHM = DSA;

  /**
     * 默認密鑰字節數
     *
     * <pre>
     * DSA
     * Default Keysize
     * Keysize must be a multiple of ranging from to (inclusive)
     * </pre>
     */
    private static final int KEY_SIZE = ;

  /**
     * 默認種子
     */
    private static final String DEFAULT_SEED = fabbddddae;

  private static final String PUBLIC_KEY = DSAPublicKey;
    private static final String PRIVATE_KEY = DSAPrivateKey;

  /**
     * 用私鑰對信息生成數字簽名
     *
     * @param data
     *            加密數據
     * @param privateKey
     *            私鑰
     *
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data String privateKey) throws Exception {
        // 解密由base編碼的私鑰
        byte[] keyBytes = decryptBASE(privateKey);

  // 構造PKCSEncodedKeySpec對象
        PKCSEncodedKeySpec pkcsKeySpec = new PKCSEncodedKeySpec(keyBytes);

  // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactorygetInstance(ALGORITHM);

  // 取私鑰匙對象
        PrivateKey priKey = keyFactorygeneratePrivate(pkcsKeySpec);

  // 用私鑰對信息生成數字簽名
        Signature signature = SignaturegetInstance(keyFactorygetAlgorithm());
        signatureinitSign(priKey);
        signatureupdate(data);

  return encryptBASE(signaturesign());
    }

  /**
     * 校驗數字簽名
     *
     * @param data
     *            加密數據
     * @param publicKey
     *            公鑰
     * @param sign
     *            數字簽名
     *
     * @return 校驗成功返回true 失敗返回false
     * @throws Exception
     *
     */
    public static boolean verify(byte[] data String publicKey String sign)
            throws Exception {

  // 解密由base編碼的公鑰
        byte[] keyBytes = decryptBASE(publicKey);

  // 構造XEncodedKeySpec對象
        XEncodedKeySpec keySpec = new XEncodedKeySpec(keyBytes);

  // ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactorygetInstance(ALGORITHM);

  // 取公鑰匙對象
        PublicKey pubKey = keyFactorygeneratePublic(keySpec);

  Signature signature = SignaturegetInstance(keyFactorygetAlgorithm());
        signatureinitVerify(pubKey);
        signatureupdate(data);

  // 驗證簽名是否正常
        return signatureverify(decryptBASE(sign));
    }

  /**
     * 生成密鑰
     *
     * @param seed
     *            種子
     * @return 密鑰對象
     * @throws Exception
     */
    public static Map<String Object> initKey(String seed) throws Exception {
        KeyPairGenerator keygen = KeyPairGeneratorgetInstance(ALGORITHM);
        // 初始化隨機產生器
        SecureRandom secureRandom = new SecureRandom();
        secureRandomsetSeed(seedgetBytes());
        keygeninitialize(KEY_SIZE secureRandom);

  KeyPair keys = keygengenKeyPair();

  DSAPublicKey publicKey = (DSAPublicKey) keysgetPublic();
        DSAPrivateKey privateKey = (DSAPrivateKey) keysgetPrivate();

  Map<String Object> map = new HashMap<String Object>();
        mapput(PUBLIC_KEY publicKey);
        mapput(PRIVATE_KEY privateKey);

  return map;
    }

  /**
     * 默認生成密鑰
     *
     * @return 密鑰對象
     * @throws Exception
     */
    public static Map<String Object> initKey() throws Exception {
        return initKey(DEFAULT_SEED);
    }

  /**
     * 取得私鑰
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String Object> keyMap)
            throws Exception {
        Key key = (Key) keyMapget(PRIVATE_KEY);

  return encryptBASE(keygetEncoded());
    }

  /**
     * 取得公鑰
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String Object> keyMap)
            throws Exception {
        Key key = (Key) keyMapget(PUBLIC_KEY);

  return encryptBASE(keygetEncoded());
    }
}

    再給出一個測試類

  import static orgjunitAssert*;

  import javautilMap;

  import orgjunitTest;

  /**
 *
 * @author 梁棟
 * @version
 * @since
 */
public class DSACoderTest {

  @Test
    public void test() throws Exception {
        String inputStr = abc;
        byte[] data = inputStrgetBytes();

  // 構建密鑰
        Map<String Object> keyMap = DSACoderinitKey();

  // 獲得密鑰
        String publicKey = DSACodergetPublicKey(keyMap);
        String privateKey = DSACodergetPrivateKey(keyMap);

  Systemerrprintln(公鑰:\r + publicKey);
        Systemerrprintln(私鑰:\r + privateKey);

  // 產生簽名
        String sign = DSACodersign(data privateKey);
        Systemerrprintln(簽名:\r + sign);

  // 驗證簽名
        boolean status = DSACoderverify(data publicKey sign);
        Systemerrprintln(狀態:\r + status);
        assertTrue(status);

  }

    控制台輸出

  公鑰:
MIIBtzCCASwGByqGSMBAEwggEfAoGBAP/UEddRIpUtKnCsOfEbdSPOEAMMePCUSZp
RVAIlHWTNWPq/xfWMPbLmVsEgBb/JmYLdrmVClpJ+fARECLCTup/xhvOfn
xqimFQE+PUewwIVBNaFpEynXzrithyrviIDGZRSAHHAhUAlBQjxUjCyykrmCouuE
C/BYHPUCgYEA+GghdabPdLvKtcNrhXuXmUrvOuqC+VdMCzHgmdRWVeOutRZT+ZxBxCBgLRJ
FnEjEwoFhOzwkyjMimTwWeotUfIoKOuHiuzpnWRbqN/C/ohNWLx+JASQzKTxvqhRkImo
g/hWuWfBpKLZlAeUlZAFMO/PSSoDgYQAAoGAIuRUlcQLpPIMrbssOY+uySVnpTULSv
TVaHoKzsLHgGTrwOvsGA+VyCNlWDuDbSLFliTWgOj+SMOEaPkVyRTlLXZWGPsfMfd
XAbMeVyKDSHHVGbMjBScajfbXooYQMlyoHiOt/WrCo+mvefstMMPGo=

  私鑰:
MIIBTAIBADCCASwGByqGSMBAEwggEfAoGBAP/UEddRIpUtKnCsOfEbdSPOEAMMePC
USZpRVAIlHWTNWPq/xfWMPbLmVsEgBb/JmYLdrmVClpJ+fARECLCTup/xhv
OfnxqimFQE+PUewwIVBNaFpEynXzrithyrviIDGZRSAHHAhUAlBQjxUjCyykrmC
ouuEC/BYHPUCgYEA+GghdabPdLvKtcNrhXuXmUrvOuqC+VdMCzHgmdRWVeOutRZT+ZxBxCB
gLRJFnEjEwoFhOzwkyjMimTwWeotUfIoKOuHiuzpnWRbqN/C/ohNWLx+JASQzKTxvqhR
kImog/hWuWfBpKLZlAeUlZAFMO/PSSoEFwIVAIegLUtmmoQKQJTOiLugHTSjl/q

  簽名:
MCCFQCMgJ/uZmFGuRprTNqwnDwIUJCyYNah+HtbUNcQfyAcLeLQs=

  狀態:
true


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27470.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.