Java Code Examples for org.bouncycastle.util.encoders.Base64#decode()
The following examples show how to use
org.bouncycastle.util.encoders.Base64#decode() .
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: EncryptionUtils.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public Key generateSecretKey() throws IntegrationModuleException { try { if (this.propertyHandler.hasProperty("symmKey")) { String base64key = this.propertyHandler.getProperty("symmKey"); DESedeKeySpec keyspec = new DESedeKeySpec(Base64.decode(base64key)); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede"); SecretKey key = keyfactory.generateSecret(keyspec); return key; } else { KeyGenerator keyGen = KeyGenerator.getInstance("DESede"); return keyGen.generateKey(); } } catch (NoSuchAlgorithmException var5) { throw new IntegrationModuleException(var5); } catch (InvalidKeyException var6) { throw new IntegrationModuleException(var6); } catch (InvalidKeySpecException var7) { throw new IntegrationModuleException(var7); } }
Example 2
Source File: AbstractCrypto.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
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 3
Source File: P7M.java From document-management-software with GNU Lesser General Public License v3.0 | 6 votes |
/** * 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 4
Source File: ECKey.java From javasdk with GNU Lesser General Public License v3.0 | 6 votes |
/** * 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 5
Source File: OSSKeyStore.java From warp10-platform with Apache License 2.0 | 6 votes |
@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 if (encoded.startsWith("wrapped:")) { if (null == this.masterKey) { throw new RuntimeException("Master Key not retrieved from OSS, aborting."); } return CryptoHelper.unwrapBlob(this.masterKey, decodeKey(encoded.substring(8))); } else { return null; } }
Example 6
Source File: AbstractCrypto.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
@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 7
Source File: AbstractCrypto.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
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 8
Source File: AbstractIntegrationModule.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
static final KeyResult getKeyFromKgss_aroundBody6(AbstractIntegrationModule ajc$this, String keyId, byte[] myEtk, JoinPoint var3) { KeyResult keyResult = null; try { if (ajc$this.getPropertyHandler().hasProperty("test_kgss_key")) { String part1 = ajc$this.getPropertyHandler().getProperty("test_kgss_key").split(";")[0]; String part2 = ajc$this.getPropertyHandler().getProperty("test_kgss_key").split(";")[1]; byte[] keyResponse = Base64.decode(part2); return new KeyResult(new SecretKeySpec(keyResponse, "AES"), part1); } keyResult = ajc$this.kgssService.retrieveKeyFromKgss(keyId.getBytes(), myEtk, ((EncryptionToken)ajc$this.etkHelper.getKGSS_ETK().get(0)).getEncoded()); } catch (Throwable var11) { LOG.error("Exception in getKeyFromKgss abstractIntegrationModule: ", var11); Exceptionutils.errorHandler(var11); } return keyResult; }
Example 9
Source File: MspValidateTest.java From julongchain with Apache License 2.0 | 5 votes |
@Test public void base64() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, CryptoException, CspException { Security.addProvider(new BouncyCastleProvider()); String sk = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" + "8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" + "8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" + "C8r6EmyE"; KeyFactory keyf = keyf = KeyFactory.getInstance("EC"); PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(sk)); BCECPrivateKey priKey = (BCECPrivateKey) keyf.generatePrivate(priPKCS8); System.out.println("16进制私钥:" + priKey.getD().toString(16)); 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[] pb = certificate.getTBSCertificate().getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); System.out.println(certificate.getSubject()); System.out.println("tbs 公钥" + Hex.toHexString(pb)); System.out.println("公钥:" + Hex.toHexString(publickey)); System.out.println("公钥长度:" + publickey.length); SM2 sm2 = new SM2(); byte[] v = sm2.sign(priKey.getD().toByteArray(), "123".getBytes()); System.out.println(sm2.verify(publickey, v, "123".getBytes())); }
Example 10
Source File: ConnectorIOUtils.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
public static byte[] base64Decode(byte[] input, boolean recursive) throws TechnicalConnectorException { byte[] result = ArrayUtils.clone(input); String content = toString(result, Charset.UTF_8); if (content.matches("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$")) { result = Base64.decode(result); if (recursive) { result = base64Decode(result, recursive); } } return result; }
Example 11
Source File: FolderDecryptor.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
public static void decryptFolder(SOAPBody soapBody, Crypto crypto) throws TechnicalConnectorException { NodeList folderNodes = soapBody.getElementsByTagNameNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "Base64EncryptedData"); if (folderNodes.getLength() == 1) { Node base64EncryptedDataNode = folderNodes.item(0); Node base64EncryptedDataParentNode = base64EncryptedDataNode.getParentNode(); try { NodeList encryptedContent = ((Element)base64EncryptedDataNode).getElementsByTagNameNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "Base64EncryptedValue"); if (encryptedContent.getLength() == 0 || encryptedContent.getLength() > 1) { LOG.debug("Base64EncryptedValue is not a valid content. Nothing to decrypt."); return; } String encryptedData = encryptedContent.item(0).getTextContent(); byte[] b64decryptedData = Base64.decode(encryptedData.getBytes()); byte[] decryptedMessage = crypto.unseal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, b64decryptedData).getContentAsByte(); base64EncryptedDataParentNode.removeChild(base64EncryptedDataNode); ConnectorXmlUtils.dump(decryptedMessage); NodeList folders = getFolders(decryptedMessage); for(int i = 0; i < folders.getLength(); ++i) { Element folderElement = (Element)folders.item(i); Node folder = base64EncryptedDataParentNode.getOwnerDocument().importNode(folderElement, true); base64EncryptedDataParentNode.appendChild(folder); } } catch (SAXException var13) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SAX_EXCEPTION, new Object[]{"SAXException when decrypting the SOAP folder", var13}); } catch (IOException var14) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_IOEXCEPTION, new Object[]{"IOException when decrypting the SOAP folder", var14}); } } else if (folderNodes.getLength() == 0) { LOG.debug("No node with name Base64EncryptedDatafound to decrypt"); } else if (folderNodes.getLength() > 1) { LOG.debug("More then one node with name Base64EncryptedDatafound to decrypt"); } }
Example 12
Source File: DebugUserAuthority.java From athenz with Apache License 2.0 | 5 votes |
@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 13
Source File: FolderDecryptor.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
public static void decryptFolder(SOAPBody soapBody, Crypto crypto) throws TechnicalConnectorException { NodeList folderNodes = soapBody.getElementsByTagNameNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "Base64EncryptedData"); if (folderNodes.getLength() == 1) { Node base64EncryptedDataNode = folderNodes.item(0); Node base64EncryptedDataParentNode = base64EncryptedDataNode.getParentNode(); try { NodeList encryptedContent = ((Element)base64EncryptedDataNode).getElementsByTagNameNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "Base64EncryptedValue"); if (encryptedContent.getLength() == 0 || encryptedContent.getLength() > 1) { LOG.debug("Base64EncryptedValue is not a valid content. Nothing to decrypt."); return; } String encryptedData = encryptedContent.item(0).getTextContent(); byte[] b64decryptedData = Base64.decode(encryptedData.getBytes()); byte[] decryptedMessage = crypto.unseal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, b64decryptedData).getContentAsByte(); base64EncryptedDataParentNode.removeChild(base64EncryptedDataNode); ConnectorXmlUtils.dump(decryptedMessage); NodeList folders = getFolders(decryptedMessage); for(int i = 0; i < folders.getLength(); ++i) { Element folderElement = (Element)folders.item(i); Node folder = base64EncryptedDataParentNode.getOwnerDocument().importNode(folderElement, true); base64EncryptedDataParentNode.appendChild(folder); } } catch (SAXException var13) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SAX_EXCEPTION, new Object[]{"SAXException when decrypting the SOAP folder", var13}); } catch (IOException var14) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_IOEXCEPTION, new Object[]{"IOException when decrypting the SOAP folder", var14}); } } else if (folderNodes.getLength() == 0) { LOG.debug("No node with name Base64EncryptedDatafound to decrypt"); } else if (folderNodes.getLength() > 1) { LOG.debug("More then one node with name Base64EncryptedDatafound to decrypt"); } }
Example 14
Source File: PrescriberIntegrationModuleMock.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
/** * Compressed b64to string. * * @param s the s * @return the string */ private String compressedB64toString(String s){ byte[] bytes = Base64.decode( s.getBytes()); try { bytes = IOUtils.decompress(bytes); } catch (IOException e) { e.printStackTrace(); } return new String (bytes); }
Example 15
Source File: ExecutorIntegrationModuleMock.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
/** * Compressed b64to string. * * @param s the s * @return the string */ private String compressedB64toString(String s){ byte[] bytes = Base64.decode( s.getBytes()); try { bytes = IOUtils.decompress(bytes); } catch (IOException e) { e.printStackTrace(); } return new String (bytes); }
Example 16
Source File: ExecutorIntegrationModuleMock.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
/** * Compressed b64to string. * * @param s the s * @return the string */ private String compressedB64toString(String s){ byte[] bytes = Base64.decode( s.getBytes()); try { bytes = IOUtils.decompress(bytes); } catch (IOException e) { e.printStackTrace(); } return new String (bytes); }
Example 17
Source File: ExecutorIntegrationModuleMock.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private String compressedB64toString(String s) { byte[] bytes = Base64.decode(s.getBytes()); try { bytes = IOUtils.decompress(bytes); } catch (IOException var4) { var4.printStackTrace(); } return new String(bytes); }
Example 18
Source File: RootOfTrustTest.java From android-key-attestation with Apache License 2.0 | 4 votes |
private static ASN1Sequence getRootOfTrustSequence(String rootOfTrustB64) throws IOException { byte[] rootOfTrustBytes = Base64.decode(rootOfTrustB64); return (ASN1Sequence) ASN1Sequence.fromByteArray(rootOfTrustBytes); }
Example 19
Source File: TestVectorRunner.java From aws-encryption-sdk-java with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") private static Map<String, KeyEntry> parseKeyManifest(final Map<String, Object> keysManifest) throws GeneralSecurityException { // check our type final Map<String, Object> metaData = (Map<String, Object>) keysManifest.get("manifest"); if (!"keys".equals(metaData.get("type"))) { throw new IllegalArgumentException("Invalid manifest type: " + metaData.get("type")); } if (!Integer.valueOf(3).equals(metaData.get("version"))) { throw new IllegalArgumentException("Invalid manifest version: " + metaData.get("version")); } final Map<String, KeyEntry> result = new HashMap<>(); Map<String, Object> keys = (Map<String, Object>) keysManifest.get("keys"); for (Map.Entry<String, Object> entry : keys.entrySet()) { final String name = entry.getKey(); final Map<String, Object> data = (Map<String, Object>) entry.getValue(); final String keyType = (String) data.get("type"); final String encoding = (String) data.get("encoding"); final String keyId = (String) data.get("key-id"); final String material = (String) data.get("material"); // May be null final String algorithm = (String) data.get("algorithm"); // May be null final KeyEntry keyEntry; final KeyFactory kf; switch (keyType) { case "symmetric": if (!"base64".equals(encoding)) { throw new IllegalArgumentException(format("Key %s is symmetric but has encoding %s", keyId, encoding)); } keyEntry = new KeyEntry(name, keyId, keyType, new SecretKeySpec(Base64.decode(material), algorithm.toUpperCase())); break; case "private": kf = KeyFactory.getInstance(algorithm); if (!"pem".equals(encoding)) { throw new IllegalArgumentException(format("Key %s is private but has encoding %s", keyId, encoding)); } byte[] pkcs8Key = parsePem(material); keyEntry = new KeyEntry(name, keyId, keyType, kf.generatePrivate(new PKCS8EncodedKeySpec(pkcs8Key))); break; case "public": kf = KeyFactory.getInstance(algorithm); if (!"pem".equals(encoding)) { throw new IllegalArgumentException(format("Key %s is private but has encoding %s", keyId, encoding)); } byte[] x509Key = parsePem(material); keyEntry = new KeyEntry(name, keyId, keyType, kf.generatePublic(new X509EncodedKeySpec(x509Key))); break; case "aws-kms": keyEntry = new KeyEntry(name, keyId, keyType, null); break; default: throw new IllegalArgumentException("Unsupported key type: " + keyType); } result.put(name, keyEntry); } return result; }
Example 20
Source File: FolderDecryptor.java From freehealth-connector with GNU Affero General Public License v3.0 | 4 votes |
public static void decryptFolder(SOAPBody soapBody, Crypto crypto) throws TechnicalConnectorException { NodeList folderNodes = soapBody.getElementsByTagNameNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "Base64EncryptedData"); if (folderNodes.getLength() == 1) { Node base64EncryptedDataNode = folderNodes.item(0); Node base64EncryptedDataParentNode = base64EncryptedDataNode.getParentNode(); try { NodeList encryptedContent = ((Element)base64EncryptedDataNode).getElementsByTagNameNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "Base64EncryptedValue"); if (encryptedContent.getLength() == 0 || encryptedContent.getLength() > 1) { LOG.debug("Base64EncryptedValue is not a valid content. Nothing to decrypt."); return; } String encryptedData = encryptedContent.item(0).getTextContent(); byte[] b64decryptedData = Base64.decode(encryptedData.getBytes()); byte[] decryptedMessage = crypto.unseal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, b64decryptedData).getContentAsByte(); base64EncryptedDataParentNode.removeChild(base64EncryptedDataNode); ConnectorXmlUtils.dump(decryptedMessage); NodeList folders = getFolders(decryptedMessage); IntStream.range(0, folders.getLength()).mapToObj(folders::item).forEach((Node e) -> { Element folderElement = (Element) e; Element folder = base64EncryptedDataParentNode.getOwnerDocument().createElementNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "folder"); NodeList folderChildren = folderElement.getChildNodes(); IntStream.range(0, folderChildren.getLength()).mapToObj(folderChildren::item).forEach((Node fn) -> { folder.appendChild(base64EncryptedDataParentNode.getOwnerDocument().importNode(fn, true)); }); NamedNodeMap m = folderElement.getAttributes(); for (int ii = 0; ii < m.getLength(); ii++) { Node attr = m.item(ii); folder.setAttribute(attr.getNodeName(), attr.getNodeValue()); } base64EncryptedDataParentNode.appendChild(folder); }); } catch (SAXException var13) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SAX_EXCEPTION, "SAXException when decrypting the SOAP folder", var13); } catch (IOException var14) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_IOEXCEPTION, "IOException when decrypting the SOAP folder", var14); } } else if (folderNodes.getLength() == 0) { LOG.debug("No node with name Base64EncryptedDatafound to decrypt"); } else if (folderNodes.getLength() > 1) { LOG.debug("More then one node with name Base64EncryptedDatafound to decrypt"); } }