Giriş
Şu satırı dahil ederiz.
import java.security.Signature;
Kullanım
İki kullanım amacı var
1. Veriyi imzalamak yani sign
2. İmzayı veriyi doğrulamak yani verify
- Generate a key pair: First, you need to generate a key pair consisting of a public key and a private key. You can use the Java KeyPairGenerator class to do this.
- Sign the payload: Once you have the private key, you can use it to sign the payload. You can use the Java Signature class to do this. The Signature class provides different algorithms to sign data, such as SHA256withRSA, SHA1withDSA, etc. Choose the appropriate algorithm based on your requirements.
Verify için açıklama
şöyle- Send the signed payload and the public key to the client: The client needs to have access to the public key to verify the signature. You can send the signed payload and the public key to the client through a REST endpoint or any other means.
- Verify the signature: Once the client receives the signed payload and the public key, it can use the public key to verify the signature. You can use the Java Signature class to verify the signature.
Sign İşlemi
Signature nesnesi elde edildikten sonra initSign(PrivateKey) metodu çağrılır veri eklenir ve daha sonra update() metodu çağrılır
Örnek
KeyPairGenerator kpg = KeyPairGenerator.getInstance("Ed25519");
KeyPair kp = kpg.generateKeyPair();
Signature sig = Signature.getInstance("Ed25519");
sig.initSign(kp.getPrivate());
sig.update(msg);
Verify İşlemi
Signature nesnesi elde edildikten sonra initVerify(PublicKey) metodu çağrılır imzalı veri eklenir ve daha sonra verify() metodu çağrılır
Örnek - Sign ve Verify
Şöyle yaparız
String payload = "test-payload";
// Generate key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Sign the payload
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(payload.getBytes());
byte[] signedPayload = signature.sign();
// Verify the signature
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(publicKey);
verifier.update(payload.getBytes());
boolean verified = verifier.verify(signedPayload);
if (verified) {
// Signature is valid
System.out.println("valid");
} else {
// Signature is invalid
System.out.println("invalid");
}
getInstance metodu
Şöyle
yaparız.
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
initSign metodu
Şöyle
yaparız.
PrivateKey priv = ...;
sig.initSign (priv);
initVerify metodu
Şöyle
yaparız.
PublicKey pubKey = ...;
sig.initVerify(pubKey);
sign metodu
Şöyle
yaparız.
byte[] signature = sig.sign();
update metodu
Şöyle
yaparız.
byte[] buffer = ...;
sig.update(buffer);
verify metodu
Şöyle
yaparız.
byte[] sigToVerify = ...;
boolean verifies = sig.verify(sigToVerify);