Example usage for java.security.spec MGF1ParameterSpec MGF1ParameterSpec

List of usage examples for java.security.spec MGF1ParameterSpec MGF1ParameterSpec

Introduction

In this page you can find the example usage for java.security.spec MGF1ParameterSpec MGF1ParameterSpec.

Prototype

public MGF1ParameterSpec(String mdName) 

Source Link

Document

Constructs a parameter set for mask generation function MGF1 as defined in the PKCS #1 standard.

Usage

From source file:be.e_contract.eid.applet.service.impl.handler.SignatureDataMessageHandler.java

@Override
public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    byte[] signatureValue = message.signatureValue;
    List<X509Certificate> certificateChain = message.certificateChain;
    if (certificateChain.isEmpty()) {
        throw new ServletException("certificate chain is empty");
    }/*from  ww w.j a  v  a 2  s. c o  m*/
    X509Certificate signingCertificate = certificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("non-repudiation certificate missing");
    }
    LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal());
    PublicKey signingPublicKey = signingCertificate.getPublicKey();

    BeIDContextQualifier contextQualifier = new BeIDContextQualifier(request);

    /*
     * Verify the signature.
     */
    String digestAlgo = this.signatureState.getDigestAlgo();
    byte[] expectedDigestValue = this.signatureState.getDigestValue();
    if (digestAlgo.endsWith("-PSS")) {
        LOG.debug("verifying RSA/PSS signature");
        try {
            Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME);
            if ("SHA-256-PSS".equals(digestAlgo)) {
                LOG.debug("RSA/PSS SHA256");
                signature.setParameter(
                        new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
            }
            signature.initVerify(signingPublicKey);
            signature.update(expectedDigestValue);
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                        signingCertificate, signatureValue);
                this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage(), e);
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                    signingCertificate, signatureValue);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    } else {
        try {
            Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME);
            signature.initVerify(signingPublicKey);
            ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
            if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) {
                digestInfo.write(SHA1_DIGEST_INFO_PREFIX);
            } else if ("SHA-224".equals(digestAlgo)) {
                digestInfo.write(SHA224_DIGEST_INFO_PREFIX);
            } else if ("SHA-256".equals(digestAlgo)) {
                digestInfo.write(SHA256_DIGEST_INFO_PREFIX);
            } else if ("SHA-384".equals(digestAlgo)) {
                digestInfo.write(SHA384_DIGEST_INFO_PREFIX);
            } else if ("SHA-512".equals(digestAlgo)) {
                digestInfo.write(SHA512_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD160".equals(digestAlgo)) {
                digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD128".equals(digestAlgo)) {
                digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD256".equals(digestAlgo)) {
                digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX);
            }
            digestInfo.write(expectedDigestValue);
            signature.update(digestInfo.toByteArray());
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                        signingCertificate, signatureValue);
                this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage());
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                    signingCertificate, signatureValue);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    }

    SignatureEvent signatureEvent = new SignatureEvent(signatureValue, certificateChain);
    try {
        this.signatureEvent.select(contextQualifier).fire(signatureEvent);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    }

    if (null != signatureEvent.getError()) {
        SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.TRUST, signingCertificate);
        this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
        return new FinishedMessage(signatureEvent.getError());
    }
    return new FinishedMessage();
}

From source file:be.fedict.eid.applet.service.impl.handler.SignatureDataMessageHandler.java

public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    LOG.debug("signature data message received");

    byte[] signatureValue = message.signatureValue;
    List<X509Certificate> certificateChain = message.certificateChain;
    if (certificateChain.isEmpty()) {
        throw new ServletException("certificate chain is empty");
    }/*from   w w w.j  av  a  2s. c o m*/
    X509Certificate signingCertificate = certificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("non-repudiation certificate missing");
    }
    LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal());

    for (X509Certificate certificate : certificateChain) {
        LOG.debug("signing x509 cert: " + certificate.getSubjectX500Principal());

    }
    PublicKey signingPublicKey = signingCertificate.getPublicKey();

    /*
     * Verify the signature.
     */
    String digestAlgo = SignatureDataMessageHandler.getDigestAlgo(session);
    byte[] expectedDigestValue = SignatureDataMessageHandler.getDigestValue(session);
    if (digestAlgo.endsWith("-PSS")) {
        LOG.debug("verifying RSA/PSS signature");
        try {
            Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME);
            if ("SHA-256-PSS".equals(digestAlgo)) {
                LOG.debug("RSA/PSS SHA256");
                signature.setParameter(
                        new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
            }
            signature.initVerify(signingPublicKey);
            signature.update(expectedDigestValue);
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage(), e);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    } else {
        try {
            Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME);
            signature.initVerify(signingPublicKey);
            ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
            if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) {
                digestInfo.write(SHA1_DIGEST_INFO_PREFIX);
            } else if ("SHA-224".equals(digestAlgo)) {
                digestInfo.write(SHA224_DIGEST_INFO_PREFIX);
            } else if ("SHA-256".equals(digestAlgo)) {
                digestInfo.write(SHA256_DIGEST_INFO_PREFIX);
            } else if ("SHA-384".equals(digestAlgo)) {
                digestInfo.write(SHA384_DIGEST_INFO_PREFIX);
            } else if ("SHA-512".equals(digestAlgo)) {
                digestInfo.write(SHA512_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD160".equals(digestAlgo)) {
                digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD128".equals(digestAlgo)) {
                digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD256".equals(digestAlgo)) {
                digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX);
            }
            digestInfo.write(expectedDigestValue);
            signature.update(digestInfo.toByteArray());
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.signatureError(remoteAddress, signingCertificate);
                }
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage());
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    }

    AuditService auditService = this.auditServiceLocator.locateService();
    if (null != auditService) {
        String userId = UserIdentifierUtil.getUserId(signingCertificate);
        auditService.signed(userId);
    }

    SignatureService signatureService = this.signatureServiceLocator.locateService();
    try {
        signatureService.setHttpSessionObject(request.getSession());
        signatureService.postSign(signatureValue, certificateChain);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    } catch (Exception e) {
        /*
         * We don't want to depend on the full JavaEE profile in this
         * artifact.
         */
        if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
            Exception exception;
            try {
                Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                        new Class[] {});
                exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
            } catch (Exception e2) {
                LOG.debug("error: " + e.getMessage(), e);
                throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
            }
            if (exception instanceof ExpiredCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
            }
            if (exception instanceof RevokedCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
            }
            if (exception instanceof TrustCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
            }
            if (exception instanceof CertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE);
            }
        }
        throw new SecurityException("signature service error: " + e.getMessage(), e);
    }

    return new FinishedMessage();
}

From source file:org.apache.xml.security.stax.impl.processor.output.XMLEncryptOutputProcessor.java

/**
 * Override this method to return a different AbstractInternalEncryptionOutputProcessor instance
 * which will write out the KeyInfo contents in the EncryptedData.
 *//*ww  w  .j  a va 2  s  .c o m*/
protected AbstractInternalEncryptionOutputProcessor createInternalEncryptionOutputProcessor(
        EncryptionPartDef encryptionPartDef, XMLSecStartElement startElement, String encoding,
        final OutboundSecurityToken keyWrappingToken) throws XMLStreamException, XMLSecurityException {

    final AbstractInternalEncryptionOutputProcessor processor = new AbstractInternalEncryptionOutputProcessor(
            encryptionPartDef, startElement, encoding) {

        @Override
        protected void createKeyInfoStructure(OutputProcessorChain outputProcessorChain)
                throws XMLStreamException, XMLSecurityException {
            if (keyWrappingToken == null) {
                // Do not write out a KeyInfo element
                return;
            }

            final String encryptionKeyTransportAlgorithm = getSecurityProperties()
                    .getEncryptionKeyTransportAlgorithm();

            PublicKey pubKey = keyWrappingToken.getPublicKey();
            Key secretKey = keyWrappingToken.getSecretKey(encryptionKeyTransportAlgorithm);
            if (pubKey == null && secretKey == null) {
                // Do not write out a KeyInfo element
                return;
            }

            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo,
                    true, null);

            List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1);
            String keyId = IDGenerator.generateID("EK");
            attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, keyId));
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey,
                    true, attributes);

            attributes = new ArrayList<XMLSecAttribute>(1);
            attributes.add(
                    createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportAlgorithm));
            createStartElementAndOutputAsEvent(outputProcessorChain,
                    XMLSecurityConstants.TAG_xenc_EncryptionMethod, false, attributes);

            final String encryptionKeyTransportDigestAlgorithm = getSecurityProperties()
                    .getEncryptionKeyTransportDigestAlgorithm();
            final String encryptionKeyTransportMGFAlgorithm = getSecurityProperties()
                    .getEncryptionKeyTransportMGFAlgorithm();

            if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm)
                    || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) {

                byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams();
                if (oaepParams != null) {
                    createStartElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_xenc_OAEPparams, false, null);
                    createCharactersAndOutputAsEvent(outputProcessorChain,
                            Base64.encodeBase64String(oaepParams));
                    createEndElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_xenc_OAEPparams);
                }

                if (encryptionKeyTransportDigestAlgorithm != null) {
                    attributes = new ArrayList<XMLSecAttribute>(1);
                    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm,
                            encryptionKeyTransportDigestAlgorithm));
                    createStartElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_dsig_DigestMethod, true, attributes);
                    createEndElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_dsig_DigestMethod);
                }

                if (encryptionKeyTransportMGFAlgorithm != null) {
                    attributes = new ArrayList<XMLSecAttribute>(1);
                    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm,
                            encryptionKeyTransportMGFAlgorithm));
                    createStartElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_xenc11_MGF, true, attributes);
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc11_MGF);
                }
            }

            createEndElementAndOutputAsEvent(outputProcessorChain,
                    XMLSecurityConstants.TAG_xenc_EncryptionMethod);

            createKeyInfoStructureForEncryptedKey(outputProcessorChain, keyWrappingToken);

            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData,
                    false, null);
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue,
                    false, null);

            //encrypt the symmetric session key with the public key from the receiver:
            String jceid = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportAlgorithm);
            if (jceid == null) {
                throw new XMLSecurityException("algorithms.NoSuchMap",
                        new Object[] { encryptionKeyTransportAlgorithm });
            }

            try {
                Cipher cipher = Cipher.getInstance(jceid);

                AlgorithmParameterSpec algorithmParameterSpec = null;
                if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm)
                        || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) {

                    String jceDigestAlgorithm = "SHA-1";
                    if (encryptionKeyTransportDigestAlgorithm != null) {
                        jceDigestAlgorithm = JCEAlgorithmMapper
                                .translateURItoJCEID(encryptionKeyTransportDigestAlgorithm);
                    }

                    PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
                    byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams();
                    if (oaepParams != null) {
                        pSource = new PSource.PSpecified(oaepParams);
                    }

                    MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
                    if (encryptionKeyTransportMGFAlgorithm != null) {
                        String jceMGFAlgorithm = JCEAlgorithmMapper
                                .translateURItoJCEID(encryptionKeyTransportMGFAlgorithm);
                        mgfParameterSpec = new MGF1ParameterSpec(jceMGFAlgorithm);
                    }
                    algorithmParameterSpec = new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec,
                            pSource);
                }

                if (pubKey != null) {
                    cipher.init(Cipher.WRAP_MODE, pubKey, algorithmParameterSpec);
                } else {
                    cipher.init(Cipher.WRAP_MODE, secretKey, algorithmParameterSpec);
                }

                String tokenId = outputProcessorChain.getSecurityContext()
                        .get(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION);
                SecurityTokenProvider<OutboundSecurityToken> securityTokenProvider = outputProcessorChain
                        .getSecurityContext().getSecurityTokenProvider(tokenId);

                final OutboundSecurityToken securityToken = securityTokenProvider.getSecurityToken();
                Key sessionKey = securityToken
                        .getSecretKey(getSecurityProperties().getEncryptionSymAlgorithm());
                if (pubKey != null) {
                    int blockSize = cipher.getBlockSize();
                    if (blockSize > 0 && blockSize < sessionKey.getEncoded().length) {
                        throw new XMLSecurityException("stax.unsupportedKeyTransp");
                    }
                }
                byte[] encryptedEphemeralKey = cipher.wrap(sessionKey);

                createCharactersAndOutputAsEvent(outputProcessorChain,
                        new Base64(76, new byte[] { '\n' }).encodeToString(encryptedEphemeralKey));

            } catch (NoSuchPaddingException e) {
                throw new XMLSecurityException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new XMLSecurityException(e);
            } catch (InvalidKeyException e) {
                throw new XMLSecurityException(e);
            } catch (IllegalBlockSizeException e) {
                throw new XMLSecurityException(e);
            } catch (InvalidAlgorithmParameterException e) {
                throw new XMLSecurityException(e);
            }

            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue);
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData);

            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey);

            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
        }

        protected void createKeyInfoStructureForEncryptedKey(OutputProcessorChain outputProcessorChain,
                OutboundSecurityToken securityToken) throws XMLStreamException, XMLSecurityException {
            SecurityTokenConstants.KeyIdentifier keyIdentifier = getSecurityProperties()
                    .getEncryptionKeyIdentifier();

            X509Certificate[] x509Certificates = securityToken.getX509Certificates();
            if (x509Certificates == null) {
                if (securityToken.getPublicKey() != null
                        && SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) {
                    createStartElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_dsig_KeyInfo, true, null);

                    XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain,
                            securityToken.getPublicKey());
                    createEndElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_dsig_KeyInfo);
                }
                return;
            }

            if (!SecurityTokenConstants.KeyIdentifier_NoKeyInfo.equals(keyIdentifier)) {
                createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo,
                        true, null);

                if (keyIdentifier == null
                        || SecurityTokenConstants.KeyIdentifier_IssuerSerial.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509IssuerSerialStructure(this, outputProcessorChain,
                            x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) {
                    XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_SkiKeyIdentifier.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509SubjectKeyIdentifierStructure(this, outputProcessorChain,
                            x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509CertificateStructure(this, outputProcessorChain,
                            x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_X509SubjectName.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509SubjectNameStructure(this, outputProcessorChain,
                            x509Certificates);
                } else {
                    throw new XMLSecurityException("stax.unsupportedToken", new Object[] { keyIdentifier });
                }

                createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
            }
        }
    };
    processor.getAfterProcessors().add(XMLEncryptOutputProcessor.class.getName());
    return processor;
}

From source file:test.be.fedict.eid.applet.RSATest.java

@Test
public void testPSS() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC");

    byte[] data = "hello world".getBytes();

    signature.initSign(privateKey);/*from  www .j  a v  a  2 s .  co  m*/
    signature.update(data);
    byte[] signatureValue = signature.sign();

    LOG.debug("signature size: " + signatureValue.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue)));

    signature.initVerify(publicKey);
    signature.update(data);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    signature.initSign(privateKey);
    signature.update(data);
    byte[] signatureValue2 = signature.sign();

    LOG.debug("signature size: " + signatureValue2.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2)));

    assertFalse(Arrays.equals(signatureValue, signatureValue2));

    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC");
    byte[] digest = messageDigest.digest(data);

    signature = Signature.getInstance("RAWRSASSA-PSS", "BC");
    signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
    signature.initVerify(publicKey);
    signature.update(digest);
    result = signature.verify(signatureValue);
    assertTrue(result);
}