org.bouncycastle.util.encoders.Base64 Java Examples

The following examples show how to use org.bouncycastle.util.encoders.Base64. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: SingleSignOnServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }

}
 
Example #3
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }

}
 
Example #4
Source File: PBKDF2.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
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;
	
}
 
Example #5
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: XadesBesSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }

}
 
Example #7
Source File: KeyPairGenerate.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: XadesBesSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }

}
 
Example #9
Source File: TrustAddressGeneratorTest.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
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();
}
 
Example #10
Source File: AbstractCrypto.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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});
   }
}
 
Example #11
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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)));
}
 
Example #12
Source File: MapperFactory.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }

}
 
Example #14
Source File: RsaDecryption.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
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;
	}
 
Example #15
Source File: MspValidateTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }

}
 
Example #17
Source File: AbstractCrypto.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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});
   }
}
 
Example #18
Source File: AbstractIntegrationModule.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #19
Source File: P7M.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #20
Source File: AbstractCrypto.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@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});
   }
}
 
Example #21
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #22
Source File: XMLSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #23
Source File: KgssServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public KeyResult getNewKey(GetNewKeyRequestContent request, byte[] kgssETK) throws TechnicalConnectorException {
   Credential encryptionCredential = Session.getInstance().getSession().getEncryptionCredential();
   Map<String, PrivateKey> decryptionKeys = Session.getInstance().getSession().getEncryptionPrivateKeys();
   GetNewKeyResponseContent response = this.getNewKey(request, encryptionCredential, decryptionKeys, kgssETK);
   byte[] keyResponse = response.getNewKey();
   String keyId = new String(Base64.encode(response.getNewKeyIdentifier()));
   return new KeyResult(new SecretKeySpec(keyResponse, "AES"), keyId);
}
 
Example #24
Source File: DocumentService.java    From webapp-hardware-bridge with MIT License 5 votes vote down vote up
public static void extract(String base64, String urlString) throws Exception {
    byte[] bytes = Base64.decode(base64);

    try (OutputStream stream = new FileOutputStream(getPathFromUrl(urlString))) {
        stream.write(bytes);
    }
}
 
Example #25
Source File: LogSignatureVerifierTest.java    From certificate-transparency-java with Apache License 2.0 5 votes vote down vote up
@Test
public void signatureOnEmbeddedSCTsInFinalCertificateVerifies()
    throws IOException, CertificateEncodingException {
  // Flow:
  // github-chain.txt contains leaf certificate signed by issuing CA.
  // Leafcert contains three embedded SCTs, we verify them all
  List<Certificate> certsChain = new ArrayList<>();
  certsChain.addAll(loadCertificates(TEST_GITHUB_CHAIN));

  // the leaf cert is the first one in this test data
  X509Certificate leafcert = (X509Certificate) certsChain.get(0);
  Certificate issuerCert = certsChain.get(1);
  assertTrue(
      "The test certificate does have embedded SCTs", CertificateInfo.hasEmbeddedSCT(leafcert));
  List<Ct.SignedCertificateTimestamp> scts = VerifySignature.parseSCTsFromCert(leafcert);
  assertEquals("Expected 3 SCTs in the test certificate", 3, scts.size());
  Map<String, LogInfo> logInfos = getLogInfosGitHub();
  for (Ct.SignedCertificateTimestamp sct : scts) {
    String id = Base64.toBase64String(sct.getId().getKeyId().toByteArray());
    LogInfo logInfo = logInfos.get(id);
    System.out.println(id);
    LogSignatureVerifier verifier = new LogSignatureVerifier(logInfo);

    assertTrue(
        "Expected signature to verify OK",
        verifier.verifySCTOverPreCertificate(
            sct,
            leafcert,
            LogSignatureVerifier.issuerInformationFromCertificateIssuer(issuerCert)));
    assertTrue("Expected PreCertificate to verify OK", verifier.verifySignature(sct, certsChain));
  }
}
 
Example #26
Source File: DebugUserAuthority.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
public Principal authenticate(String creds, String remoteAddr, String httpMethod, StringBuilder errMsg) {
    errMsg = errMsg == null ? new StringBuilder(512) : errMsg;

    // the HTTP Basic authorization format is: Basic base64(<username>:<password>)
    
    if (!creds.startsWith("Basic ")) {
        errMsg.append("UserAuthority:authenticate: credentials do not start with 'Basic '");
        LOG.error(errMsg.toString());
        return null;
    }
    
    // decode - need to skip the first 6 bytes for 'Basic '
    String decoded;
    try {
        decoded = new String(Base64.decode(creds.substring(6).getBytes(StandardCharsets.UTF_8)));
    } catch (Exception e) {
        errMsg.append("UserAuthority:authenticate: factory exc=");
        LOG.error(errMsg.toString());
        return null;
    }

    String[] userArray = decoded.split(":");
    String username = userArray[0];

    if (LOG.isDebugEnabled()) {
        LOG.debug("UserAuthority.authenticate: valid user=" + username);
    }

    // all the role members in Athenz are normalized to lower case so we need to make
    // sure our principal's name and domain are created with lower case as well

    long issueTime = 0;
    SimplePrincipal princ = (SimplePrincipal) SimplePrincipal.create(getDomain().toLowerCase(),
            userArray[0].toLowerCase(), creds, issueTime, this);
    princ.setUnsignedCreds(creds);
    return princ;
}
 
Example #27
Source File: BuilderUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void checkHash(byte[] blobHashValue, byte[] decompressedBlob) throws InvalidBlobContentConnectorException, TechnicalConnectorException {
   try {
      byte[] calculatedHashValue = buildHash(decompressedBlob);
      if (!Arrays.areEqual(blobHashValue, calculatedHashValue)) {
         String blobHashAsString = blobHashValue != null ? new String(Base64.encode(blobHashValue)) : "";
         String calculatedHashAsString = calculatedHashValue != null ? new String(Base64.encode(calculatedHashValue)) : "";
         throw new InvalidBlobContentConnectorException(InvalidBlobContentConnectorExceptionValues.HASH_VALUES_DIFFERENT, (Blob)null, decompressedBlob, new Object[]{blobHashAsString, calculatedHashAsString});
      }
   } catch (NoSuchAlgorithmException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #28
Source File: KgssServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public KeyResult getNewKey(GetNewKeyRequestContent request, UUID keystoreId, KeyStore keystore, String quality, String passPhrase, byte[] kgssETK) throws TechnicalConnectorException {
   Credential credential = new KeyStoreCredential(keystoreId, keystore, "authentication", passPhrase, quality);
   Map<String, PrivateKey> hokPrivateKeys = KeyManager.getDecryptionKeys(keystore, passPhrase.toCharArray());
   Crypto crypto = CryptoFactory.getCrypto(credential, hokPrivateKeys);

   GetNewKeyResponseContent response = this.getNewKey(request, crypto, credential, hokPrivateKeys, kgssETK);
   byte[] keyResponse = response.getNewKey();
   String keyId = new String(Base64.encode(response.getNewKeyIdentifier()));
   return new KeyResult(new SecretKeySpec(keyResponse, "AES"), keyId);
}
 
Example #29
Source File: KgssManager.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected KeyResult getKeyFromKgss(String keyId, byte[] myEtk) throws TechnicalConnectorException {
   LOG.debug("KeyIdentifier : " + keyId);
   GetKeyRequestContent req = new GetKeyRequestContent();
   req.setETK(myEtk);
   req.setKeyIdentifier(Base64.decode(keyId.getBytes()));
   SessionItem session = Session.getInstance().getSession();
   return this.service.getKey(req, getETKOfKGSS(), session);
}
 
Example #30
Source File: UnsecureKeyStore.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] decodeKey(String encoded) {
  if (null == encoded) {
    return null;
  }
  if (encoded.startsWith("hex:")) {
    return Hex.decode(encoded.substring(4));
  } else if (encoded.startsWith("base64:")) {
    return Base64.decode(encoded.substring(7));
  } else {
    return null;
  }
}