下面列出了javax.annotation.security.DenyAll#org.bouncycastle.util.encoders.Base64 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Element createSignatureHashReference(Document doc, byte[] signedTagData) {
HashMap<String, String> param = new HashMap<String, String>();
param.put("type", "http://uri.etsi.org/01903#SignedProperties");
param.put("uri", "#xades-"+id);
param.put("alg", "http://www.w3.org/2001/10/xml-exc-c14n#");
param.put("digAlg", "http://www.w3.org/2001/04/xmlenc#sha256");
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] digestValue = md.digest(signedTagData);
param.put("digVal", Base64.toBase64String(digestValue));
return createReferenceTag(doc, param);
}
/**
* Reads a p7m file from a stream. Sets the signed data with the stream as
* content.
*
* @param is The inputStream
*/
public void read(InputStream is) {
byte[] buffer = new byte[4096];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while (is.read(buffer) > 0) {
baos.write(buffer);
}
} catch (Exception ex) {
log.error("Error reading file");
}
byte[] tmp = baos.toByteArray();
try {
// if the content is on Base64, we must decode it into DER format
content = Base64.decode(tmp);
log.debug("Decoding on Base64 completed");
log.debug("The signed file is in DER format");
} catch (Exception e) {
// the content has the DER format
content = tmp;
log.debug("The signed file is probably in DER format");
}
read(content);
}
@Test
public void certTest() throws IOException {
String privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" +
"8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" +
"8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" +
"C8r6EmyE";
byte[] sk = org.bouncycastle.util.encoders.Base64.decode(privateKey);
System.out.println("私钥长度" + sk.length);
System.out.println(Hex.toHexString(sk));
String cert_path = MspValidateTest.class.getResource("/szca/testsm2.pem").getPath();
byte[] idBytes = FileUtils.readFileBytes(cert_path);
Certificate certificate = Certificate.getInstance(new PemReader(new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent());
byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
System.out.println(certificate.getSubject());
System.out.println("公钥:" + Hex.toHexString(publickey));
System.out.println("公钥长度:" + publickey.length);
}
protected byte[] perform(byte[] input) throws Exception {
if( ! this.keyAvailable.isSelected() )
throw new IllegalArgumentException("No private key available.");
String padding = (String)paddings.getSelectedItem();
Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s", algorithm, cipherMode, padding));
cipher.init(Cipher.DECRYPT_MODE, this.selectedEntry.getPrivateKey());
String selectedInputMode = (String)inputMode.getSelectedItem();
String selectedOutputMode = (String)outputMode.getSelectedItem();
if( selectedInputMode.equals("Hex") )
input = Hex.decode(input);
if( selectedInputMode.equals("Base64") )
input = Base64.decode(input);
byte[] encrypted = cipher.doFinal(input);
if( selectedOutputMode.equals("Hex") )
encrypted = Hex.encode(encrypted);
if( selectedOutputMode.equals("Base64") )
encrypted = Base64.encode(encrypted);
return encrypted;
}
private void verifyTimestampList(SignatureVerificationResult result, Element baseElement, NodeList timestampList, String c14nMethodValue) throws TechnicalConnectorException {
if (timestampList != null && timestampList.getLength() > 0) {
for(int j = 0; j < timestampList.getLength(); ++j) {
try {
Node timestampNode = timestampList.item(j);
byte[] digestValue = this.generateTimestampDigest(baseElement, c14nMethodValue);
TimeStampToken tsToken = TimestampUtil.getTimeStampToken(Base64.decode(timestampNode.getTextContent().getBytes()));
TimeStampValidatorFactory.Companion.getInstance().validateTimeStampToken(digestValue, tsToken);
result.getTimestampGenTimes().add(new DateTime(tsToken.getTimeStampInfo().getGenTime()));
result.getTsTokens().add(tsToken);
} catch (InvalidTimeStampException var9) {
LOG.error(var9.getMessage(), var9);
result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_VALID);
}
}
} else {
result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_FOUND);
}
}
/**
* Given a piece of text and a message signature encoded in base64, returns an ECKey
* containing the public key that was used to sign it. This can then be compared to the expected public key to
* determine if the signature was correct.
*
* @param messageHash a piece of human readable text that was signed
* @param signatureBase64 The Ethereum-format message signature in base64
* @return -
* @throws SignatureException If the public key could not be recovered or if there was a signature format error.
*/
public static byte[] signatureToKeyBytes(byte[] messageHash, String signatureBase64) throws SignatureException {
byte[] signatureEncoded;
try {
signatureEncoded = Base64.decode(signatureBase64);
} catch (RuntimeException e) {
// This is what you get back from Bouncy Castle if base64 doesn't decode :(
throw new SignatureException("Could not decode base64", e);
}
// Parse the signature bytes into r/s and the selector value.
if (signatureEncoded.length < 65)
throw new SignatureException("Signature truncated, expected 65 bytes and got " + signatureEncoded.length);
return signatureToKeyBytes(
messageHash,
ECDSASignature.fromComponents(
Arrays.copyOfRange(signatureEncoded, 1, 33),
Arrays.copyOfRange(signatureEncoded, 33, 65),
(byte) (signatureEncoded[0] & 0xFF)));
}
@Test
void gen() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
// 获取SM2椭圆曲线的参数
final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
// 获取一个椭圆曲线类型的密钥对生成器
final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
// 使用SM2参数初始化生成器
kpg.initialize(sm2Spec);
// 使用SM2的算法区域初始化密钥生成器
kpg.initialize(sm2Spec, new SecureRandom());
// 获取密钥对
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pubKey = keyPair.getPublic();
String pubKEnc = Base64.toBase64String(pubKey.getEncoded());
System.out.println(">> Pub Key: " + pubKEnc);
PrivateKey priKey = keyPair.getPrivate();
String priKEnc = Base64.toBase64String(priKey.getEncoded());
System.out.println(">> Pri Key: " + priKEnc);
}
public static boolean checkPassword(String password,String hashStr) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
String salt64 = hashStr.substring(hashStr.indexOf('}') + 1,hashStr.indexOf(':'));
byte[] salt = Base64.decode(salt64.getBytes("UTF-8"));
String hash64 = hashStr.substring(hashStr.indexOf(':') + 1);
byte[] hash = Base64.decode(hash64.getBytes("UTF-8"));
byte[] check = deriveKey(password.getBytes("UTF-8"),salt,10000,32);
if (hash.length != check.length) {
return false;
}
for (int i=0;i<hash.length;i++) {
if (hash[i] != check[i]) {
return false;
}
}
return true;
}
private void verifyTimestampList(SignatureVerificationResult result, Element baseElement, NodeList timestampList, String c14nMethodValue) throws TechnicalConnectorException {
if (timestampList != null && timestampList.getLength() > 0) {
for(int j = 0; j < timestampList.getLength(); ++j) {
try {
Node timestampNode = timestampList.item(j);
byte[] digestValue = this.generateTimestampDigest(baseElement, c14nMethodValue);
TimeStampToken tsToken = TimestampUtil.getTimeStampToken(Base64.decode(timestampNode.getTextContent().getBytes()));
TimeStampValidatorFactory.getInstance().validateTimeStampToken(digestValue, tsToken);
result.getTimestampGenTimes().add(new DateTime(tsToken.getTimeStampInfo().getGenTime()));
result.getTsTokens().add(tsToken);
} catch (InvalidTimeStampException var9) {
LOG.error(var9.getMessage(), var9);
result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_VALID);
}
}
} else {
result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_FOUND);
}
}
private String processHolderOfKeyCredentials(Credential hokCred, String request) throws TechnicalConnectorException, CertificateEncodingException {
if (hokCred != null && hokCred.getCertificate() != null) {
request = StringUtils.replace(request, "${holder.of.key}", new String(Base64.encode(hokCred.getCertificate().getEncoded())));
PublicKey publicKey = hokCred.getCertificate().getPublicKey();
if (publicKey instanceof RSAPublicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
request = StringUtils.replace(request, "${publickey.rsa.modulus}", new String(Base64.encode(convertTo(rsaPublicKey.getModulus()))));
request = StringUtils.replace(request, "${publickey.rsa.exponent}", new String(Base64.encode(convertTo(rsaPublicKey.getPublicExponent()))));
request = StringUtils.replace(request, "<ds:DSAKeyValue><ds:G>${publickey.dsa.g}<ds:G><ds:P>${publickey.dsa.p}</ds:P><ds:Q>${publickey.dsa.q}</ds:Q></ds:DSAKeyValue>", "");
} else if (publicKey instanceof DSAPublicKey) {
DSAPublicKey dsaPublicKey = (DSAPublicKey)publicKey;
request = StringUtils.replace(request, "${publickey.dsa.g}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getG()))));
request = StringUtils.replace(request, "${publickey.dsa.p}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getP()))));
request = StringUtils.replace(request, "${publickey.dsa.q}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getQ()))));
request = StringUtils.replace(request, "<ds:RSAKeyValue><ds:Modulus>${publickey.rsa.modulus}</ds:Modulus><ds:Exponent>${publickey.rsa.exponent}</ds:Exponent></ds:RSAKeyValue>", "");
} else {
LOG.info("Unsupported public key: [" + publicKey.getClass().getName() + "+]");
}
}
return request;
}
String convertHexToBase64String(String input) throws IOException {
byte barr[] = new byte[16];
int bcnt = 0;
for (int i = 0; i < 32; i += 2) {
char c1 = input.charAt(i);
char c2 = input.charAt(i + 1);
int i1 = convertCharToInt(c1);
int i2 = convertCharToInt(c2);
barr[bcnt] = 0;
barr[bcnt] |= (byte) ((i1 & 0x0F) << 4);
barr[bcnt] |= (byte) (i2 & 0x0F);
bcnt++;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Base64.encode(barr, outputStream);
return outputStream.toString();
}
public Key generateSecretKey() throws TechnicalConnectorException {
TechnicalConnectorExceptionValues errorValue = TechnicalConnectorExceptionValues.ERROR_CRYPTO;
String param = "Could not generate secret key (SymmKey)";
try {
if (config.hasProperty("SYMM_KEY_PROPERTY")) {
String base64key = config.getProperty("SYMM_KEY_PROPERTY");
DESedeKeySpec keyspec = new DESedeKeySpec(Base64.decode(base64key));
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
return keyfactory.generateSecret(keyspec);
} else {
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
return keyGen.generateKey();
}
} catch (Exception var6) {
LOG.debug(MessageFormat.format(errorValue.getMessage(), param));
throw new TechnicalConnectorException(errorValue, var6, new Object[]{param});
}
}
public static Mapper getMapper(String... mappingFiles) {
Set<String> mappingSet = new TreeSet();
mappingSet.addAll(Arrays.asList(mappingFiles));
MessageDigest complete = DigestUtils.getMd5Digest();
Iterator i$ = mappingSet.iterator();
while(i$.hasNext()) {
String mapping = (String)i$.next();
complete.update(mapping.getBytes());
}
String key = new String(Base64.encode(complete.digest()));
if (!cache.containsKey(key)) {
Map<String, Object> options = new HashMap();
options.put("be.ehealth.technicalconnector.mapper.configfiles", mappingFiles);
try {
cache.put(key, helper.getImplementation(options));
} catch (TechnicalConnectorException var6) {
throw new IllegalArgumentException(var6);
}
}
return (Mapper)cache.get(key);
}
private void verifyTimestampList(SignatureVerificationResult result, Element baseElement, NodeList timestampList, String c14nMethodValue) throws TechnicalConnectorException {
if (timestampList != null && timestampList.getLength() > 0) {
for(int j = 0; j < timestampList.getLength(); ++j) {
try {
Node timestampNode = timestampList.item(j);
byte[] digestValue = this.generateTimestampDigest(baseElement, c14nMethodValue);
TimeStampToken tsToken = TimestampUtil.getTimeStampToken(Base64.decode(timestampNode.getTextContent().getBytes()));
TimeStampValidatorFactory.getInstance().validateTimeStampToken(digestValue, tsToken);
result.getTimestampGenTimes().add(new DateTime(tsToken.getTimeStampInfo().getGenTime()));
result.getTsTokens().add(tsToken);
} catch (InvalidTimeStampException var9) {
LOG.error(var9.getMessage(), var9);
result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_VALID);
}
}
} else {
result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_FOUND);
}
}
private String processHolderOfKeyCredentials(Credential hokCred, String request) throws TechnicalConnectorException, CertificateEncodingException {
if (hokCred != null && hokCred.getCertificate() != null) {
request = StringUtils.replace(request, "${holder.of.key}", new String(Base64.encode(hokCred.getCertificate().getEncoded())));
PublicKey publicKey = hokCred.getCertificate().getPublicKey();
if (publicKey instanceof RSAPublicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
request = StringUtils.replace(request, "${publickey.rsa.modulus}", new String(Base64.encode(convertTo(rsaPublicKey.getModulus()))));
request = StringUtils.replace(request, "${publickey.rsa.exponent}", new String(Base64.encode(convertTo(rsaPublicKey.getPublicExponent()))));
request = StringUtils.replace(request, "<ds:DSAKeyValue><ds:G>${publickey.dsa.g}<ds:G><ds:P>${publickey.dsa.p}</ds:P><ds:Q>${publickey.dsa.q}</ds:Q></ds:DSAKeyValue>", "");
} else if (publicKey instanceof DSAPublicKey) {
DSAPublicKey dsaPublicKey = (DSAPublicKey)publicKey;
request = StringUtils.replace(request, "${publickey.dsa.g}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getG()))));
request = StringUtils.replace(request, "${publickey.dsa.p}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getP()))));
request = StringUtils.replace(request, "${publickey.dsa.q}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getQ()))));
request = StringUtils.replace(request, "<ds:RSAKeyValue><ds:Modulus>${publickey.rsa.modulus}</ds:Modulus><ds:Exponent>${publickey.rsa.exponent}</ds:Exponent></ds:RSAKeyValue>", "");
} else {
LOG.info("Unsupported public key: [" + publicKey.getClass().getName() + "+]");
}
}
return request;
}
public Key generateSecretKey() throws TechnicalConnectorException {
TechnicalConnectorExceptionValues errorValue = TechnicalConnectorExceptionValues.ERROR_CRYPTO;
String param = "Could not generate secret key (SymmKey)";
try {
if (config.hasProperty("SYMM_KEY_PROPERTY")) {
String base64key = config.getProperty("SYMM_KEY_PROPERTY");
DESedeKeySpec keyspec = new DESedeKeySpec(Base64.decode(base64key));
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
return keyfactory.generateSecret(keyspec);
} else {
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
return keyGen.generateKey();
}
} catch (Exception var6) {
LOG.debug(MessageFormat.format(errorValue.getMessage(), param));
throw new TechnicalConnectorException(errorValue, var6, new Object[]{param});
}
}
private void verifyDigest(SignatureVerificationResult result, Element certEl) {
X509Certificate signingCert = result.getSigningCert();
String digestMethod = ((Element)certEl.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "DigestMethod").item(0)).getAttribute("Algorithm");
String digestValue = certEl.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "DigestValue").item(0).getTextContent();
try {
MessageDigest messageDigest = SignatureUtils.getDigestInstance(digestMethod);
messageDigest.reset();
byte[] calculatedDigest = messageDigest.digest(signingCert.getEncoded());
if (!MessageDigest.isEqual(calculatedDigest, Base64.decode(digestValue))) {
result.getErrors().add(SignatureVerificationError.XADES_SIGNEDPROPS_NOT_VALID);
}
} catch (CertificateEncodingException var8) {
LOG.warn("Unable to encode certificate with CN [{}] Reason: {}", new Object[]{signingCert.getSubjectX500Principal().getName("RFC1779"), var8.getMessage(), var8});
result.getErrors().add(SignatureVerificationError.XADES_SIGNEDPROPS_COULD_NOT_BE_VERIFIED);
} catch (NoSuchAlgorithmException var9) {
LOG.error("Invalid digest method [{}]", digestMethod, var9);
result.getErrors().add(SignatureVerificationError.XADES_SIGNEDPROPS_NOT_VALID);
}
}
private String signinWithSAML2POST(SAMLToken samlToken) throws TechnicalConnectorException {
FileWriter fw = null;
try {
String template = ConnectorIOUtils.getResourceAsString("/sso/SSORequestSTSSAML2POST.xml");
template = StringUtils.replaceEach(template, new String[]{"${reqId}", "${endpoint.idp.saml2.post}"}, new String[]{this.idGenerator.generateId(), this.getSAML2Post()});
NodeList assertions = this.invokeSecureTokenService(ConnectorXmlUtils.flatten(template), samlToken).getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion");
Validate.notNull(assertions);
Validate.isTrue(assertions.getLength() == 1);
Element assertion = (Element)assertions.item(0);
String samlResponse = ConnectorIOUtils.getResourceAsString("/sso/bindingTemplate-SAMLResponse.xml");
samlResponse = StringUtils.replaceEachRepeatedly(samlResponse, new String[]{"${SAMLResponseID}", "${SAMLResponseIssueInstant}", "${SAMLAssertion}"}, new String[]{IdGeneratorFactory.getIdGenerator("xsid").generateId(), (new DateTime()).toString(), this.toXMLString(assertion)});
return new String(Base64.encode(ConnectorIOUtils.toBytes(ConnectorXmlUtils.flatten(samlResponse), Charset.UTF_8)));
} finally {
ConnectorIOUtils.closeQuietly(fw);
}
}
private void verifyDigest(SignatureVerificationResult result, Element certEl) {
X509Certificate signingCert = result.getSigningCert();
String digestMethod = ((Element)certEl.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "DigestMethod").item(0)).getAttribute("Algorithm");
String digestValue = certEl.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "DigestValue").item(0).getTextContent();
try {
MessageDigest messageDigest = SignatureUtils.getDigestInstance(digestMethod);
messageDigest.reset();
byte[] calculatedDigest = messageDigest.digest(signingCert.getEncoded());
if (!MessageDigest.isEqual(calculatedDigest, Base64.decode(digestValue))) {
result.getErrors().add(SignatureVerificationError.XADES_SIGNEDPROPS_NOT_VALID);
}
} catch (CertificateEncodingException var8) {
LOG.warn("Unable to encode certificate with CN [{}] Reason: {}", new Object[]{signingCert.getSubjectX500Principal().getName("RFC1779"), var8.getMessage(), var8});
result.getErrors().add(SignatureVerificationError.XADES_SIGNEDPROPS_COULD_NOT_BE_VERIFIED);
} catch (NoSuchAlgorithmException var9) {
LOG.error("Invalid digest method [{}]", digestMethod, var9);
result.getErrors().add(SignatureVerificationError.XADES_SIGNEDPROPS_NOT_VALID);
}
}
@Profiled(logFailuresSeparately = true, tag = "0.AbstractIntegrationModule#getKeyFromKgss", logger = "org.perf4j.TimingLogger_Common")
public KeyResult getKeyFromKgss(String keyId, byte[] myEtk) throws IntegrationModuleException {
KeyResult keyResult = null;
try {
// For test, when a sim key is specified in the config
if (getPropertyHandler().hasProperty("test_kgss_key")) {
String part1 = getPropertyHandler().getProperty("test_kgss_key").split(";")[0];
String part2 = getPropertyHandler().getProperty("test_kgss_key").split(";")[1];
// LOG.info("KGSS key retrieved from configuration. Key Id = part1);
byte[] keyResponse = Base64.decode(part2);
return new KeyResult(new SecretKeySpec(keyResponse, "AES"), part1);
}
keyResult = kgssService.retrieveKeyFromKgss(keyId.getBytes(), myEtk, etkHelper.getKGSS_ETK().get(0).getEncoded());
} catch (Throwable t) {
LOG.error("Exception in getKeyFromKgss abstractIntegrationModule: ", t);
Exceptionutils.errorHandler(t);
}
return keyResult;
}
@Deprecated
public Key generateSecretKey() throws TechnicalConnectorException {
TechnicalConnectorExceptionValues errorValue = TechnicalConnectorExceptionValues.ERROR_CRYPTO;
String param = "Could not generate secret key (SymmKey)";
try {
if (config.hasProperty("SYMM_KEY_PROPERTY")) {
String base64key = config.getProperty("SYMM_KEY_PROPERTY");
DESedeKeySpec keyspec = new DESedeKeySpec(Base64.decode(base64key));
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
return keyfactory.generateSecret(keyspec);
} else {
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
return keyGen.generateKey();
}
} catch (Exception var6) {
LOG.debug(MessageFormat.format(errorValue.getMessage(), param));
throw new TechnicalConnectorException(errorValue, var6, new Object[]{param});
}
}
private String processHolderOfKeyCredentials(Credential hokCred, String request) throws TechnicalConnectorException, CertificateEncodingException {
if (hokCred != null && hokCred.getCertificate() != null) {
request = StringUtils.replace(request, "${holder.of.key}", new String(Base64.encode(hokCred.getCertificate().getEncoded())));
PublicKey publicKey = hokCred.getCertificate().getPublicKey();
if (publicKey instanceof RSAPublicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
request = StringUtils.replace(request, "${publickey.rsa.modulus}", new String(Base64.encode(convertTo(rsaPublicKey.getModulus()))));
request = StringUtils.replace(request, "${publickey.rsa.exponent}", new String(Base64.encode(convertTo(rsaPublicKey.getPublicExponent()))));
request = StringUtils.replace(request, "<ds:DSAKeyValue><ds:G>${publickey.dsa.g}<ds:G><ds:P>${publickey.dsa.p}</ds:P><ds:Q>${publickey.dsa.q}</ds:Q></ds:DSAKeyValue>", "");
} else if (publicKey instanceof DSAPublicKey) {
DSAPublicKey dsaPublicKey = (DSAPublicKey)publicKey;
request = StringUtils.replace(request, "${publickey.dsa.g}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getG()))));
request = StringUtils.replace(request, "${publickey.dsa.p}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getP()))));
request = StringUtils.replace(request, "${publickey.dsa.q}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getQ()))));
request = StringUtils.replace(request, "<ds:RSAKeyValue><ds:Modulus>${publickey.rsa.modulus}</ds:Modulus><ds:Exponent>${publickey.rsa.exponent}</ds:Exponent></ds:RSAKeyValue>", "");
} else {
LOG.info("Unsupported public key: [" + publicKey.getClass().getName() + "+]");
}
}
return request;
}
public static String calculateHMAC(String secret, String data) {
try {
SecretKeySpec signingKey = new SecretKeySpec(Hex.decode(secret), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleFipsProvider());
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
return Base64.toBase64String(rawHmac);
} catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException ex) {
System.out.println("Unexpected error while creating hash: " + ex.getMessage());
throw new IllegalArgumentException();
}
}
public static String calculateHash(String contentToEncode, String hash) {
try {
MessageDigest digest = MessageDigest.getInstance(hash);
digest.update(contentToEncode.getBytes());
return Base64.toBase64String(digest.digest());
} catch (NoSuchAlgorithmException ex) {
logp(Level.SEVERE, classname, "generateX509FromBytes", "CRYPTO-MSG-1000", printStackTrace(ex));
}
return null;
}
public String signDBRow(String did,
String signingdn,
String input,
Boolean standalone,
String password)
throws CryptoException {
String signedData = null;
String sigalg;
try {
PrivateKey pvkey;
if (standalone) {
pvkey = getXMLSignatureSigningKeyLocal(password, signingdn);
sigalg = cryptoCommon.getConfigurationProperty("crypto.cfg.property.signing.rsa.signaturealgorithm");
} else {
pvkey = getXMLSignatureSigningKey(signingdn);
sigalg = cryptoCommon.getConfigurationProperty("crypto.cfg.property.signing.ec.signaturealgorithm");
}
// Get signature object
Signature signature = Signature.getInstance(sigalg, BC_FIPS_PROVIDER);
signature.initSign(pvkey, FIPS_DRBG);
signature.update(input.getBytes("UTF-8"));
byte[] signbytes = signature.sign();
signedData = new String(Base64.encode(signbytes), "UTF-8");
cryptoCommon.logp(Level.FINE, classname, "signDBRow", "CRYPTO-MSG-1000", signedData + " [Length: " + signbytes.length + "]");
} catch (NoSuchAlgorithmException | IOException
| IllegalArgumentException | InvalidKeyException
| SignatureException ex) {
ex.printStackTrace();
cryptoCommon.logp(Level.SEVERE, classname, "signDBRow", "CRYPTO-ERR-1000", ex.toString());
throw new CryptoException(cryptoCommon.getMessageWithParam("CRYPTO-ERR-1000", ex.getLocalizedMessage()));
}
return signedData;
}
private static PrivateKey generatePrivateKeyFromString(String key, String algorithm) {
PrivateKey privateKey = null;
if(key.length()>1){
key = cleanKey(key);
try {
byte[] keyByteArray = Base64.decode(key);
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyByteArray);
privateKey = kf.generatePrivate(keySpec);
} catch (Exception e) {
Output.outputError("Error generating private key with input string '"+key+"' and algorithm '"+algorithm+"' - "+e.getMessage()+" - ");
}
}
return privateKey;
}
protected byte[] perform(byte[] input) throws Exception {
if( !this.keyAvailable.isSelected() )
throw new IllegalArgumentException("No private key available.");
String algo = (String)algos.getSelectedItem();
Signature signature = Signature.getInstance(algo);
String selectedInputMode = (String)inputMode.getSelectedItem();
String selectedOutputMode = (String)outputMode.getSelectedItem();
if( selectedInputMode.equals("Hex") )
input = Hex.decode(input);
if( selectedInputMode.equals("Base64") )
input = Base64.decode(input);
signature.initSign(this.selectedEntry.getPrivateKey());
signature.update(input);
byte[] result = signature.sign();
if( selectedOutputMode.equals("Hex") )
result = Hex.encode(result);
if( selectedOutputMode.equals("Base64") )
result = Base64.encode(result);
return result;
}
/**
* queueEncrypt / queueDecryt works only for marshaled object.
*
* @param data
* @param publicKey
* @return
* @throws IntegrationModuleException
*/
public String queueDecrypt(byte[] data, PublicKey publicKey) throws IntegrationModuleException {
try {
LOG.debug("**************** SIZE BYTES ********** " + data.length);
byte[] decodeData = Base64.decode(data);
String key = publicKey.toString().substring(0, 16);
final SecretKeySpec symKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, symKey);
byte[] cipherData = cipher.doFinal(decodeData);
LOG.debug("************** cipherData ************* " + Arrays.toString(cipherData));
String s = new String(cipherData);// , "UTF-8");
LOG.debug("******************** GOING OUT: " + s + " **********************");
// int c = s.indexOf(">") +1;
//
// s = s.replace(s.substring(0, c),"");
// System.out.println("******************** GOING OUT SUBSTRING: " +
// s + " **********************");
//
int i = s.lastIndexOf(encryptionSignature);
// int i = s.lastIndexOf(">") + 1;
s = s.substring(0, i);
LOG.debug("******************** GOING OUT SUBSTRING2: " + s + " **********************");
return s;
} catch (Throwable t) {
Exceptionutils.errorHandler(t);
}
return null;
}
/**
* @return -
*/
public String toBase64() {
byte[] sigData = new byte[65]; // 1 header + 32 bytes for R + 32 bytes for S
sigData[0] = v;
System.arraycopy(ByteUtil.bigIntegerToBytes(this.r, 32), 0, sigData, 1, 32);
System.arraycopy(ByteUtil.bigIntegerToBytes(this.s, 32), 0, sigData, 33, 32);
return new String(Base64.encode(sigData), Charset.forName("UTF-8"));
}
/**
* CSR中获取公钥
* @return
*/
public static byte[] getPublicKey(String csr) throws IOException {
PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(Base64.decode(csr));
byte[] publicKeyBytes = p10.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
return publicKeyBytes;
}