Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

In this page you can find the example usage for java.security Signature getInstance.

Prototype

public static Signature getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1", "BC");
    signature.setParameter(PSSParameterSpec.DEFAULT);

    AlgorithmParameters params = signature.getParameters();

    ASN1InputStream aIn = new ASN1InputStream(params.getEncoded("ASN.1"));

    System.out.println(ASN1Dump.dumpAsString(aIn.readObject()));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "BC");

    keyGen.initialize(512, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();
    Signature signature = Signature.getInstance("DSA", "BC");

    signature.initSign(keyPair.getPrivate(), new SecureRandom());
    byte[] message = "abc".getBytes();
    signature.update(message);//from www  .  j a v  a  2 s.c  om

    byte[] sigBytes = signature.sign();
    signature.initVerify(keyPair.getPublic());
    signature.update(message);
    System.out.println(signature.verify(sigBytes));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");

    keyGen.initialize(512, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();
    Signature signature = Signature.getInstance("SHA1withRSA", "BC");

    signature.initSign(keyPair.getPrivate(), new SecureRandom());

    byte[] message = "abc".getBytes();
    signature.update(message);/*  w ww. ja  va 2 s  .c  om*/

    byte[] sigBytes = signature.sign();
    signature.initVerify(keyPair.getPublic());
    signature.update(message);
    System.out.println(signature.verify(sigBytes));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(512, new SecureRandom());
    KeyPair keyPair = keyGen.generateKeyPair();

    Signature signature = Signature.getInstance("SHA256withRSA", "BC");
    signature.initSign(keyPair.getPrivate());

    byte[] message = "abc".getBytes();
    signature.update(message);/*from   w  w  w . j a va2 s  . c om*/

    byte[] sigBytes = signature.sign();
    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());

    byte[] decSig = cipher.doFinal(sigBytes);
    ASN1InputStream aIn = new ASN1InputStream(decSig);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

    System.out.println(ASN1Dump.dumpAsString(seq));

    MessageDigest hash = MessageDigest.getInstance("SHA-256", "BC");
    hash.update(message);

    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    System.out.println(MessageDigest.isEqual(hash.digest(), sigHash.getOctets()));
}

From source file:signature.SignLicense.java

public static void main(String[] args) throws Exception {

    if (args.length != 2) {
        System.out.println("Usage: SignLicense licenseFile privateKey");
        System.exit(1);/*from  ww  w. ja  va2  s . co m*/
    }

    Properties license = new Properties();
    license.load(new FileInputStream(args[0]));

    PrivateKey privateKey = Utils.readPrivateKeyFromFile(args[1]);
    Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
    signature.initSign(privateKey);

    String[] propKeys = license.keySet().toArray(new String[0]);
    Arrays.sort(propKeys);
    for (String propKey : propKeys) {
        if (!"Signature".equals(propKey)) {
            String propValue = license.getProperty(propKey);
            signature.update(propValue.getBytes("UTF-8"));
        }
    }

    byte[] sig = signature.sign();
    license.setProperty("Signature", new String(Base64.encodeBase64(sig)));
    license.store(new FileOutputStream(args[0]), null);
}

From source file:GenSig.java

public static void main(String[] args) {

    /* Generate a DSA signature */

    if (args.length != 1) {
        System.out.println("Usage: GenSig nameOfFileToSign");
    } else/*from w  w  w.j a va  2  s. c om*/
        try {

            /* Generate a key pair */

            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

            keyGen.initialize(1024, random);

            KeyPair pair = keyGen.generateKeyPair();
            PrivateKey priv = pair.getPrivate();
            PublicKey pub = pair.getPublic();

            /*
             * Create a Signature object and initialize it with the private
             * key
             */

            Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");

            dsa.initSign(priv);

            /* Update and sign the data */

            FileInputStream fis = new FileInputStream(args[0]);
            BufferedInputStream bufin = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024];
            int len;
            while (bufin.available() != 0) {
                len = bufin.read(buffer);
                dsa.update(buffer, 0, len);
            }
            ;

            bufin.close();

            /*
             * Now that all the data to be signed has been read in, generate
             * a signature for it
             */

            byte[] realSig = dsa.sign();

            /* Save the signature in a file */
            FileOutputStream sigfos = new FileOutputStream("sig");
            sigfos.write(realSig);

            sigfos.close();

            /* Save the public key in a file */
            byte[] key = pub.getEncoded();
            FileOutputStream keyfos = new FileOutputStream("suepk");
            keyfos.write(key);

            keyfos.close();

        } catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
        }

}

From source file:Main.java

static Signature getSignatureInstance(String algorithm, String provider)
        throws NoSuchProviderException, NoSuchAlgorithmException {
    if (provider != null) {
        return Signature.getInstance(algorithm, provider);
    } else {/*w ww .j a v a2  s  .com*/
        return Signature.getInstance(algorithm);
    }
}

From source file:Main.java

static public String getSignature(String s, RSAPrivateKey privKey, String algorithm) {
    try {//from  w w  w . ja v  a2  s. c o  m
        if ("RS256".compareTo(algorithm) == 0)
            algorithm = "SHA256withRSA";
        Signature signature = Signature.getInstance(algorithm, "SC");
        signature.initSign(privKey);
        signature.update(s.getBytes(Charset.forName("UTF-8")));
        byte[] signed = signature.sign();
        return encodeB64(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

static public boolean verifyJWS(String s, String algorithm, PublicKey pubKey, PrivateKey privKey) {
    boolean bverify = false;

    String parts[] = s.split("\\.");
    if (parts == null || parts.length != 3)
        return bverify;

    try {/*from w ww .j a v  a  2  s  . c  o m*/
        if ("RS256".compareTo(algorithm) == 0)
            algorithm = "SHA256withRSA";
        Signature signature = Signature.getInstance(algorithm, "SC");
        signature.initVerify(pubKey);
        signature.update((parts[0] + "." + parts[1]).getBytes());
        bverify = signature.verify(decodeB64(parts[2]));

        Log.d("verifyJWS", "payload: " + new String(decodeB64(parts[1])));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return bverify;
}

From source file:nl.arietimmerman.u2f.server.CryptoHelper.java

/**
 * Verifies the signature, as set on the registration response and authentication response messages
 * @param publicKey The public key/*from   w  ww  .j a  v  a2  s.c o m*/
 * @param bytesSigned The bytes to be signed
 * @param signature See "FIDO U2F Raw Message Formats" for requirements regarding signatures
 * @return
 */
public static boolean verifySignature(PublicKey publicKey, byte[] bytesSigned, byte[] signature) {
    Log.info("start verifySignature");
    try {
        Signature signatureObject = Signature.getInstance("SHA256withECDSA", new BouncyCastleProvider());
        Log.info("Initialized SHA256withECDSA");
        signatureObject.initVerify(publicKey);
        Log.info("executed initVerify");
        signatureObject.update(bytesSigned);
        Log.info("start verifying");
        return signatureObject.verify(signature);
    } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) {
        e.printStackTrace();
        return false;
    }
}