`

Cryptography

阅读更多

    A signature provides two security services, authentication and integrity. A signature gives you assurance that a message has not been tampered with and that it originated from a certain person. As you'll recall from Chapter 2, a signature is a message digest that is encrypted with the signer's private key. Only the signer's public key can decrypt the signature, which provides authentication. If the message digest of the message matches the decrypted message digest from the signature, then integrity is also assured.

Signatures do not provide confidentiality. A signature accompanies a plaintext message. Anyone can intercept and read the message. Signatures are useful for distributing software and documentation because they foil forgery.

http://oreilly.com/catalog/javacrypt/chapter/ch06.html

 

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

public class Test {

	public static void main(String args[]) {
		try {
			// 1. Get the bytes in the Message.

			String strMessage = " Hello World !";
			byte[] bMessage = strMessage.getBytes();

			// 2. Get the PrivateKey and the PublicKey.

			KeyPair keyPair = KeyPairGenerator.getInstance("DSA")
					.generateKeyPair();

			PrivateKey privateKey = keyPair.getPrivate();
			PublicKey publicKey = keyPair.getPublic();

			// Incorrect Public Key

			KeyPair keyPairIncorrect = KeyPairGenerator.getInstance("DSA")
					.generateKeyPair();
			PublicKey publicKeyIncorrect = keyPairIncorrect.getPublic();

			// 3. Encrypt the Data.

			Signature signature = Signature.getInstance("DSA");

			signature.initSign(privateKey);
			signature.update(bMessage);

			// 4. Get the Signature, by signing the message.

			byte[] bSignature = signature.sign();

			// 5. Decrypt the Signature with the Public Key and get the Message
			// Digest.

			Signature signaturePublic = Signature.getInstance("DSA");

			// 6. Authentication

			signaturePublic.initVerify(publicKey);
			signaturePublic.update(bMessage);

			// 6. Check if the Signatures Match.

			boolean b = signaturePublic.verify(bSignature);

			if (b) {
				System.out.println(" The Signature is Good " + b);
			} else {
				System.out.println(" The Signature is Bad " + b);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (SignatureException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics