├── .asf.yaml
├── .gitattributes
├── .github
├── GH-ROBOTS.txt
├── dependabot.yml
├── pull_request_template.md
└── workflows
│ ├── adhoctest.yml
│ ├── benchmarkadhoc.yml
│ ├── codeql-analysis.yml
│ ├── dependency-review.yml
│ ├── docker_images.yml
│ ├── maven.yml
│ ├── maven_adhoc.yml
│ ├── maven_crosstest.yml
│ └── scorecards-analysis.yml
├── .gitignore
├── BUILDING.txt
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LIBRARY_NAMES.txt
├── LICENSE.txt
├── Makefile
├── Makefile.common
├── NOTICE.txt
├── PROPOSAL.html
├── README.md
├── RELEASE-NOTES.txt
├── SECURITY.md
├── build_dist.sh
├── lib
└── include
│ └── config.h
├── pom.xml
└── src
├── assembly
├── bin.xml
└── src.xml
├── changes
├── changes.xml
└── release-notes.vm
├── conf
├── checkstyle
│ ├── checkstyle-suppressions.xml
│ └── checkstyle.xml
├── pmd
│ └── pmd-ruleset.xml
└── spotbugs
│ └── spotbugs-exclude-filter.xml
├── docker
├── Dockerfile
├── Dockerfile.aarch64
├── Dockerfile.riscv64
├── README.md
├── build-aarch64.sh
├── build-x86_64.sh
├── build_linux32.sh
├── docker-compose-gh.yaml
├── docker-compose.yaml
├── test_cross.sh
└── tests.sh
├── main
├── java
│ └── org
│ │ └── apache
│ │ └── commons
│ │ └── crypto
│ │ ├── Crypto.java
│ │ ├── NativeCodeLoader.java
│ │ ├── OpenSslInfoNative.java
│ │ ├── OsInfo.java
│ │ ├── cipher
│ │ ├── AbstractOpenSslFeedbackCipher.java
│ │ ├── CryptoCipher.java
│ │ ├── CryptoCipherFactory.java
│ │ ├── JceCipher.java
│ │ ├── OpenSsl.java
│ │ ├── OpenSslCipher.java
│ │ ├── OpenSslCommonMode.java
│ │ ├── OpenSslEvpCtrlValues.java
│ │ ├── OpenSslGaloisCounterMode.java
│ │ ├── OpenSslNative.java
│ │ └── package-info.java
│ │ ├── jna
│ │ ├── LibreSsl20XNativeJna.java
│ │ ├── OpenSsl11XNativeJna.java
│ │ ├── OpenSsl30XNativeJna.java
│ │ ├── OpenSslInterfaceNativeJna.java
│ │ ├── OpenSslJna.java
│ │ ├── OpenSslJnaCipher.java
│ │ ├── OpenSslJnaCryptoRandom.java
│ │ ├── OpenSslMacOS.java
│ │ ├── OpenSslNativeJna.java
│ │ └── package-info.java
│ │ ├── package-info.java
│ │ ├── random
│ │ ├── CryptoRandom.java
│ │ ├── CryptoRandomFactory.java
│ │ ├── JavaCryptoRandom.java
│ │ ├── OpenSslCryptoRandom.java
│ │ ├── OpenSslCryptoRandomNative.java
│ │ ├── OsCryptoRandom.java
│ │ └── package-info.java
│ │ ├── stream
│ │ ├── CryptoInputStream.java
│ │ ├── CryptoOutputStream.java
│ │ ├── CtrCryptoInputStream.java
│ │ ├── CtrCryptoOutputStream.java
│ │ ├── PositionedCryptoInputStream.java
│ │ ├── input
│ │ │ ├── ChannelInput.java
│ │ │ ├── Input.java
│ │ │ ├── StreamInput.java
│ │ │ └── package-info.java
│ │ ├── output
│ │ │ ├── ChannelOutput.java
│ │ │ ├── Output.java
│ │ │ ├── StreamOutput.java
│ │ │ └── package-info.java
│ │ └── package-info.java
│ │ └── utils
│ │ ├── AES.java
│ │ ├── IoUtils.java
│ │ ├── Padding.java
│ │ ├── ReflectionUtils.java
│ │ ├── Transformation.java
│ │ ├── Utils.java
│ │ └── package-info.java
├── native
│ └── org
│ │ └── apache
│ │ └── commons
│ │ └── crypto
│ │ ├── DynamicLoader.c
│ │ ├── OpenSslInfoNative.c
│ │ ├── cipher
│ │ └── OpenSslNative.c
│ │ ├── org_apache_commons_crypto.h
│ │ └── random
│ │ ├── OpenSslCryptoRandomNative.c
│ │ └── org_apache_commons_crypto_random.h
└── resources
│ └── org
│ └── apache
│ └── commons
│ └── crypto
│ └── component.properties
├── site
├── resources
│ ├── download_crypto.cgi
│ ├── images
│ │ └── logo.png
│ └── profile.jacoco
├── site.xml
└── xdoc
│ ├── download_crypto.xml
│ ├── faq.xml
│ ├── index.xml
│ ├── issue-tracking.xml
│ ├── mail-lists.xml
│ ├── proposal.xml
│ ├── security.xml
│ └── userguide.xml
└── test
└── java
└── org
└── apache
└── commons
└── crypto
├── AbstractBenchmark.java
├── CryptoBenchmark.java
├── CryptoTest.java
├── NativeCodeLoaderTest.java
├── OsInfoTest.java
├── cipher
├── AbstractCipherTest.java
├── CryptoCipherFactoryTest.java
├── CryptoCipherTest.java
├── DefaultCryptoCipher.java
├── GcmCipherTest.java
├── JceCipherTest.java
├── OpenSslCipherTest.java
├── OpenSslCommonModeTest.java
└── TestData.java
├── examples
├── CipherByteArrayExample.java
├── CipherByteBufferExample.java
├── RandomExample.java
├── StreamExample.java
└── package-info.java
├── jna
├── AbstractCipherJnaStreamTest.java
├── CbcNoPaddingCipherJnaStreamTest.java
├── CbcPkcs5PaddingCipherJnaStreamTest.java
├── CryptoJnaBenchmark.java
├── CtrCryptoJnaStreamTest.java
├── CtrNoPaddingCipherJnaStreamTest.java
├── OpenSslJnaCipherTest.java
├── OpenSslJnaCryptoRandomTest.java
├── OpenSslJnaTest.java
├── OpenSslNativeJnaTest.java
└── PositionedCryptoInputStreamJnaTest.java
├── random
├── AbstractRandom.java
├── AbstractRandomTest.java
├── CryptoRandomFactoryTest.java
├── ExceptionInInitializerErrorRandom.java
├── FailingRandom.java
├── JavaCryptoRandomTest.java
├── MissingPropertyCtrRandom.java
├── OpenSslCryptoRandomTest.java
└── OsCryptoRandomTest.java
├── stream
├── AbstractCipherStreamTest.java
├── CbcNoPaddingCipherStreamTest.java
├── CbcPkcs5PaddingCipherStreamTest.java
├── CtrCryptoStreamTest.java
├── CtrNoPaddingCipherStreamTest.java
├── PositionedCryptoInputStreamTest.java
├── input
│ └── ChannelInputTest.java
└── output
│ └── StreamOutputTest.java
└── utils
├── EnumTest.java
└── UtilsTest.java
/.asf.yaml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | github:
17 | description: "Apache Commons Crypto"
18 | homepage: https://commons.apache.org/crypto/
19 |
20 | notifications:
21 | commits: commits@commons.apache.org
22 | issues: issues@commons.apache.org
23 | pullrequests: issues@commons.apache.org
24 | jira_options: link label
25 | jobs: notifications@commons.apache.org
26 | issues_bot_dependabot: notifications@commons.apache.org
27 | pullrequests_bot_dependabot: notifications@commons.apache.org
28 | issues_bot_codecov-commenter: notifications@commons.apache.org
29 | pullrequests_bot_codecov-commenter: notifications@commons.apache.org
30 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | #
16 |
17 | # Auto detect text files and perform LF normalization
18 | * text=auto
19 |
20 | *.java text diff=java
21 | *.html text diff=html
22 | *.css text
23 | *.js text
24 | *.sql text
25 |
--------------------------------------------------------------------------------
/.github/GH-ROBOTS.txt:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | # Keeps on creating FUD PRs in test code
17 | # Does not follow Apache disclosure policies
18 | User-agent: JLLeitschuh/security-research
19 | Disallow: *
20 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | version: 2
17 | updates:
18 | - package-ecosystem: "maven"
19 | directory: "/"
20 | schedule:
21 | interval: "weekly"
22 | day: "friday"
23 | - package-ecosystem: "github-actions"
24 | directory: "/"
25 | schedule:
26 | interval: "weekly"
27 | day: "friday"
28 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 |
19 |
20 | Thanks for your contribution to [Apache Commons](https://commons.apache.org/)! Your help is appreciated!
21 |
22 | Before you push a pull request, review this list:
23 |
24 | - [ ] Read the [contribution guidelines](CONTRIBUTING.md) for this project.
25 | - [ ] Run a successful build using the default [Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command line by itself.
26 | - [ ] Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible but is a best-practice.
27 | - [ ] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
28 | - [ ] Each commit in the pull request should have a meaningful subject line and body. Note that commits might be squashed by a maintainer on merge.
29 |
--------------------------------------------------------------------------------
/.github/workflows/adhoctest.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | name: Java AdHoc
17 |
18 | # Check for openssl and crypto installs
19 |
20 | on:
21 | # allow direct trigger
22 | workflow_dispatch:
23 | # and self-trigger
24 | push:
25 | paths:
26 | - '**/workflows/adhoctest.yml'
27 |
28 | permissions:
29 | contents: read
30 |
31 | jobs:
32 | build:
33 |
34 | runs-on: ${{ matrix.os }}
35 | strategy:
36 | matrix:
37 | os: [macos-13,macos-14]
38 | # os: [macos-11, macos-12, macos-13, ubuntu-20.04, ubuntu-22.04]
39 | fail-fast: false
40 |
41 | steps:
42 | - name: OpenSSL version
43 | run: openssl version -a
44 | - name: Find libcrypto on Windows
45 | if: ${{ runner.os == 'Windows' }}
46 | run: |
47 | dir "C:\Program Files\OpenSSL*\*"
48 | dir "C:\Program Files\OpenSSL*\lib\*"
49 | - name: Find aes.h on !Windows
50 | if: ${{ runner.os != 'Windows' }}
51 | run: |
52 | set +e # want everything to run
53 | find /usr -name aes.h -ls || true
54 | find /usr -type d -name openssl -ls || true
55 | find /opt -name aes.h -ls || true
56 | find /opt -type d -name openssl -ls || true
57 | ls -l /usr/local/include /usr/local/opt/openssl/include || true # is this where macos12-13 find aes.h?
58 | ls -l /opt/local/include || true # Try this for macos-14
59 | find /usr -type l -name openssl -ls 2>/dev/null
60 | find /opt -type l -name openssl -ls 2>/dev/null
61 | which -a openssl | while read a ;do echo "$a" ; "$a" version -a; echo '======='; done
62 |
--------------------------------------------------------------------------------
/.github/workflows/benchmarkadhoc.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | name: Benchmark adhoc
17 |
18 | on:
19 | # allow direct trigger
20 | workflow_dispatch:
21 |
22 | permissions:
23 | contents: read
24 |
25 | jobs:
26 | build:
27 |
28 | runs-on: ${{ matrix.os }}
29 | continue-on-error: ${{ matrix.experimental }}
30 | strategy:
31 | matrix:
32 | # macos-latest and ubuntu-latest uses OpenSSL 3 which breaks tests
33 | os: [macos-11, ubuntu-20.04, windows-latest]
34 | # Run lowest and highest Java versions only
35 | java: [ 8, 21 ]
36 | experimental: [false]
37 | fail-fast: false
38 |
39 | steps:
40 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
41 | with:
42 | persist-credentials: false
43 | - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
44 | with:
45 | path: ~/.m2/repository
46 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
47 | restore-keys: |
48 | ${{ runner.os }}-maven-
49 | - name: Set up JDK ${{ matrix.java }}
50 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
51 | with:
52 | distribution: 'temurin'
53 | java-version: ${{ matrix.java }}
54 | - name: OpenSSL version
55 | run: openssl version -a
56 | # - name: Build with Maven
57 | # # OPENSSL_HOME is needed for Windows build; not used by other builds so can set unconditionally
58 | # # It's not clear how one is supposed to find the correct setting;
59 | # # The value below was found by searching for openssl files under C (warning: slow)
60 | # # Other possible values are:
61 | # # "C:\\Miniconda\\pkgs\\openssl-1.1.1n-h2bbff1b_0\\Library"
62 | # # "C:\\ProgramData\\chocolatey\\lib\\mingw\\tools\\install\\mingw64\\opt"
63 | # env:
64 | # OPENSSL_HOME: "C:\\Miniconda\\Library"
65 | # run: mvn --show-version --batch-mode --no-transfer-progress -DtrimStackTrace=false clean test-compile -Pbenchmark
66 | # # will fail on Windows...
67 | - name: Host details
68 | run: uname -a
69 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | name: "CodeQL"
17 |
18 | on:
19 | # allow direct trigger
20 | workflow_dispatch:
21 | push:
22 | paths-ignore:
23 | - '**/workflows/*.yml'
24 | - 'src/docker/*'
25 | branches: [ master ]
26 | pull_request:
27 | paths-ignore:
28 | - '**/workflows/*.yml'
29 | - 'src/docker/*'
30 | # The branches below must be a subset of the branches above
31 | branches: [ master ]
32 | # schedule:
33 | # - cron: '33 9 * * 4'
34 |
35 | permissions:
36 | contents: read
37 |
38 | jobs:
39 | analyze:
40 | name: Analyze
41 | runs-on: ubuntu-20.04
42 | permissions:
43 | actions: read
44 | contents: read
45 | security-events: write
46 |
47 | strategy:
48 | fail-fast: false
49 | matrix:
50 | language: [ 'cpp', 'java' ]
51 | java: [ 8 ]
52 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
53 | # Learn more about CodeQL language support at https://git.io/codeql-language-support
54 |
55 | steps:
56 | - name: Checkout repository
57 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
58 | with:
59 | persist-credentials: false
60 | - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
61 | with:
62 | path: ~/.m2/repository
63 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
64 | restore-keys: |
65 | ${{ runner.os }}-maven-
66 |
67 | # Override Java default
68 | # Java 11 complains about illegal access; drop this override when sorted
69 | # Also complains: "Corrupted channel by directly writing to native stream in forked JVM 1"
70 | - name: Set up JDK ${{ matrix.java }}
71 | if: ${{ matrix.language == 'java' }}
72 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
73 | with:
74 | distribution: 'temurin'
75 | java-version: ${{ matrix.java }}
76 |
77 | # Initializes the CodeQL tools for scanning.
78 | - name: Initialize CodeQL
79 | uses: github/codeql-action/init@ff0a06e83cb2de871e5a09832bc6a81e7276941f # 3.28.18
80 | with:
81 | languages: ${{ matrix.language }}
82 | # If you wish to specify custom queries, you can do so here or in a config file.
83 | # By default, queries listed here will override any specified in a config file.
84 | # Prefix the list here with "+" to use these queries and those in the config file.
85 | # queries: ./path/to/local/query, your-org/your-repo/queries@main
86 |
87 | - name: Build with Maven
88 | # -DargLine=--add-opens=java.base/sun.nio.ch=ALL-UNNAMED (not with Java 8)
89 | run: mvn -V package --no-transfer-progress -Drat.skip -Danimal.sniffer.skip
90 | # make bootstrap
91 | # make release
92 |
93 | - name: Perform CodeQL Analysis
94 | uses: github/codeql-action/analyze@ff0a06e83cb2de871e5a09832bc6a81e7276941f # 3.28.18
95 |
--------------------------------------------------------------------------------
/.github/workflows/dependency-review.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one
2 | # or more contributor license agreements. See the NOTICE file
3 | # distributed with this work for additional information
4 | # regarding copyright ownership. The ASF licenses this file
5 | # to you under the Apache License, Version 2.0 (the
6 | # "License"); you may not use this file except in compliance
7 | # with the License. You may obtain a copy of the License at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing,
12 | # software distributed under the License is distributed on an
13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 | # KIND, either express or implied. See the License for the
15 | # specific language governing permissions and limitations
16 | # under the License.
17 |
18 | name: 'Dependency Review'
19 | on: [pull_request]
20 |
21 | permissions:
22 | contents: read
23 |
24 | jobs:
25 | dependency-review:
26 | runs-on: ubuntu-latest
27 | steps:
28 | - name: 'Checkout Repository'
29 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
30 | - name: 'Dependency Review PR'
31 | uses: actions/dependency-review-action@da24556b548a50705dd671f47852072ea4c105d9 # v4.7.1
32 |
--------------------------------------------------------------------------------
/.github/workflows/docker_images.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | name: Docker images
17 | # This name is used by maven_crosstest.yml
18 |
19 | on:
20 | # allow direct trigger
21 | workflow_dispatch:
22 | # only rarely needs to run
23 | push:
24 | paths:
25 | - '**/docker_images.yml'
26 | - 'src/docker/Dockerfile*'
27 |
28 | env:
29 | REGISTRY: ghcr.io
30 |
31 | permissions:
32 | contents: read
33 |
34 | jobs:
35 | docker:
36 | runs-on: ubuntu-latest
37 | permissions:
38 | contents: read
39 | packages: write
40 | steps:
41 | - name: Image prefix (lower case)
42 | run: |
43 | echo "IMAGE_PREFIX=$(echo ${{ env.REGISTRY }}/${{ github.repository }} | tr '[A-Z]' '[a-z]')" >>$GITHUB_ENV
44 | - name: Checkout
45 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
46 | - name: Set up QEMU
47 | uses: docker/setup-qemu-action@5964de0df58d5ad28b04d8fe2e6b80ad47105b91 # v3.5.0
48 | - name: Set up Docker Buildx
49 | uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
50 | - name: Login to Docker Hub
51 | uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # 3.4.0
52 | with:
53 | registry: ${{ env.REGISTRY }}
54 | username: ${{ github.actor }}
55 | password: ${{ secrets.GITHUB_TOKEN }}
56 | - name: Build and push main image
57 | uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
58 | with:
59 | context: src/docker
60 | file: src/docker/Dockerfile
61 | push: true
62 | tags: ${{ env.IMAGE_PREFIX }}:latest
63 | - name: Build and push aarch64
64 | uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
65 | with:
66 | context: src/docker
67 | file: src/docker/Dockerfile.aarch64
68 | platforms: linux/aarch64
69 | push: true
70 | tags: ${{ env.IMAGE_PREFIX }}-aarch64:latest
71 | - name: Build and push riscv64
72 | uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
73 | with:
74 | context: src/docker
75 | file: src/docker/Dockerfile.riscv64
76 | platforms: linux/riscv64
77 | push: true
78 | tags: ${{ env.IMAGE_PREFIX }}-riscv64:latest
79 |
--------------------------------------------------------------------------------
/.github/workflows/maven_adhoc.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | name: Maven adhoc
17 |
18 | on:
19 | # allow direct trigger
20 | workflow_dispatch:
21 | # self-trigger
22 | push:
23 | paths:
24 | - '**/maven_adhoc.yml'
25 |
26 | permissions:
27 | contents: read
28 |
29 | jobs:
30 | build:
31 | runs-on: ${{ matrix.os }}
32 | continue-on-error: ${{ matrix.experimental }}
33 | strategy:
34 | fail-fast: false
35 | matrix:
36 | # macos-latest and ubuntu-latest uses OpenSSL 3 which breaks tests
37 | # os: [macos-11, ubuntu-20.04, windows-latest]
38 | os: [ macos-latest, ubuntu-latest, windows-latest ]
39 | # These names are used in conditional statements below.
40 | # java: [ 8, 11, 17, 21 ]
41 | java: [ 21 ]
42 | experimental: [false]
43 |
44 | steps:
45 | - name: OpenSSL version
46 | run: openssl version -a
47 | - name: Checkout
48 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
49 | with:
50 | persist-credentials: false
51 | - name: Set up JDK ${{ matrix.java }}
52 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
53 | with:
54 | distribution: 'temurin'
55 | java-version: ${{ matrix.java }}
56 | - name: Build only
57 | env:
58 | OPENSSL_HOME: "C:\\Miniconda\\Library"
59 | run: |
60 | mvn clean test -B -V -ntp -DskipTests
61 | - name: JNI test default
62 | run: |
63 | mvn -q exec:java -D"exec.mainClass=org.apache.commons.crypto.Crypto" -D"commons.crypto.debug=true"
64 | - name: JNA test default
65 | if: always()
66 | run: |
67 | mvn -q exec:java -D"jna.debug_load=true" -D"exec.mainClass=org.apache.commons.crypto.jna.OpenSslJna" -D"commons.crypto.debug=true"
68 | - name: Maven test default
69 | if: always()
70 | run: |
71 | mvn surefire:test -B -V -ntp -D"jna.debug_load=true" -DtrimStackTrace=false -D"commons.crypto.debug=true"
72 |
--------------------------------------------------------------------------------
/.github/workflows/scorecards-analysis.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache license, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the license for the specific language governing permissions and
14 | # limitations under the license.
15 |
16 | name: "Scorecards supply-chain security"
17 |
18 | on:
19 | branch_protection_rule:
20 | # schedule:
21 | # - cron: "30 1 * * 6" # Weekly on Saturdays
22 | push:
23 | branches: [ "master" ]
24 | paths-ignore:
25 | - '**/workflows/*.yml'
26 | - 'src/docker/*'
27 |
28 | permissions: read-all
29 |
30 | jobs:
31 |
32 | analysis:
33 |
34 | name: "Scorecards analysis"
35 | runs-on: ubuntu-20.04
36 | permissions:
37 | # Needed to upload the results to the code-scanning dashboard.
38 | security-events: write
39 | actions: read
40 | id-token: write # This is required for requesting the JWT
41 | contents: read # This is required for actions/checkout
42 |
43 | steps:
44 |
45 | - name: "Checkout code"
46 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
47 | with:
48 | persist-credentials: false
49 |
50 | - name: "Run analysis"
51 | uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # 2.4.1
52 | with:
53 | results_file: results.sarif
54 | results_format: sarif
55 | # A read-only PAT token, which is sufficient for the action to function.
56 | # The relevant discussion: https://github.com/ossf/scorecard-action/issues/188
57 | repo_token: ${{ secrets.GITHUB_TOKEN }}
58 | # Publish the results for public repositories to enable scorecard badges.
59 | # For more details: https://github.com/ossf/scorecard-action#publishing-results
60 | publish_results: true
61 |
62 | - name: "Upload artifact"
63 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
64 | with:
65 | name: SARIF file
66 | path: results.sarif
67 | retention-days: 5
68 |
69 | - name: "Upload to code-scanning"
70 | uses: github/codeql-action/upload-sarif@ff0a06e83cb2de871e5a09832bc6a81e7276941f # 3.28.18
71 | with:
72 | sarif_file: results.sarif
73 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *~
2 | *.#*
3 | *#*#
4 | *.swp
5 | *.ipr
6 | *.iml
7 | *.iws
8 | *.pyc
9 | .idea/
10 | .idea_modules/
11 | .idea/*
12 | build/*.jar
13 | .settings
14 | .cache
15 | cache
16 | .generated-mima*
17 | out/
18 | .DS_Store
19 | target/
20 | target/*
21 | reports/
22 | .project
23 | .classpath
24 | project/boot/
25 | project/plugins/project/build.properties
26 | project/build/target/
27 | project/plugins/target/
28 | .ensime
29 | .ensime_lucene
30 | checkpoint
31 | derby.log
32 | dist/
33 | unit-tests.log
34 | src/main/resources/com/intel/chimera/native/
35 | src/main/resources/com/intel/chimera/native/*
36 | .externalToolBuilders/*
37 | maven-eclipse.xml
38 | /libcrypto.dylib
39 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
17 | The Apache code of conduct page is [https://www.apache.org/foundation/policies/conduct.html](https://www.apache.org/foundation/policies/conduct.html).
18 |
--------------------------------------------------------------------------------
/LIBRARY_NAMES.txt:
--------------------------------------------------------------------------------
1 |
17 |
18 | Notes on Library names
19 | ======================
20 |
21 | If the default SSL Cryptography library is not suitable for use, it may be
22 | necessary to override the path or name.
23 |
24 | The way to do this depends on the OS.
25 |
26 | On Linux/macOS, each library version is generally installed in a separate directory.
27 | The following properties can be used to override the JNI and JNA locations respectively:
28 | jni.library.path
29 | jna.library.path
30 |
31 | On Windows, multiple library versions may be installed in the system directory under a different name.
32 | The following properties can be used to override the JNI and JNA file names respectively:
33 | commons.crypto.OpenSslNativeJni
34 | commons.crypto.OpenSslNativeJna
35 |
36 | For testing with Maven, these properties can be defined on the command-line:
37 |
38 | Linux/macOs:
39 | $ mvn ... -Djni.library.path=/usr/local/lib -Djna.library.path=/usr/local/lib ...
40 |
41 | Windows:
42 |
43 | > mvn ... -D"commons.crypto.OpenSslNativeJni=libcrypto-1_1-x64" -D"commons.crypto.OpenSslNativeJna=libcrypto-1_1-x64" ...
44 |
45 | Library override is needed on macOS
46 | -----------------------------------
47 | Attempts to load the default library on macOS cause the application to crash with a message of the form:
48 | ".../bin/java is loading libcrypto in an unsafe way"
49 |
50 | To fix this, he properties jni.library.path and/or jna.library.path need to be set to the appropriate path,
51 | for example /usr/local/lib.
52 |
53 | An alternative is to ensure that there is a copy of the library in the application launch directory.
54 | This can be a soft link to the actual library. This only works for unrestricted processes.
55 |
56 | It does not appear to be possible to use any of the DYLIB_ environment variables.
57 | These are removed as part of System Integrity Protection, so are not seen by the application and dlopen().
58 |
--------------------------------------------------------------------------------
/NOTICE.txt:
--------------------------------------------------------------------------------
1 | Apache Commons Crypto
2 | Copyright 2016-2025 The Apache Software Foundation
3 |
4 | This product includes software developed at
5 | The Apache Software Foundation (https://www.apache.org/).
6 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 |
17 | The Apache Commons security page is [https://commons.apache.org/security.html](https://commons.apache.org/security.html).
18 |
--------------------------------------------------------------------------------
/build_dist.sh:
--------------------------------------------------------------------------------
1 | # Licensed under the Apache License, Version 2.0 (the "License");
2 | # you may not use this file except in compliance with the License.
3 | # You may obtain a copy of the License at
4 | #
5 | # http://www.apache.org/licenses/LICENSE-2.0
6 | #
7 | # Unless required by applicable law or agreed to in writing, software
8 | # distributed under the License is distributed on an "AS IS" BASIS,
9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 | # See the License for the specific language governing permissions and
11 | # limitations under the License. See accompanying LICENSE file.
12 |
13 | # script to build native libraries
14 | # requires Docker and macOS
15 |
16 | set -ex
17 |
18 | mvn clean
19 |
20 | # build linux 64 bit libraries
21 | docker compose -f src/docker/docker-compose.yaml run --quiet-pull crypto src/docker/build-x86_64
22 |
23 | # build linux 32 bit libraries
24 | docker compose -f src/docker/docker-compose.yaml run crypto src/docker/build_linux32.sh
25 |
26 | # Speed up builds by disabling unnecessary plugins
27 | # Note: spdx.skip requires version 0.7.1+
28 | MAVEN_ARGS="-V -B -ntp -Drat.skip -Djacoco.skip -DbuildNumber.skip -Danimal.sniffer.skip -Dcyclonedx.skip -Dspdx.skip"
29 | # requires Maven 3.9.0+ to be automatically read
30 |
31 | # build 64 bit macOS libraries
32 | mvn process-classes -Dtarget.name=mac64 ${MAVEN_ARGS}
33 | mvn process-classes -Dtarget.name=macArm64 ${MAVEN_ARGS}
34 | mvn process-classes -Dtarget.name=mac-aarch64 ${MAVEN_ARGS}
35 |
36 | # package it all up
37 | mvn package -DskipTests ${MAVEN_ARGS}
38 |
--------------------------------------------------------------------------------
/lib/include/config.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | #ifndef __CONFIG_H
20 | #define __CONFIG_H
21 |
22 | #if defined(WINDOWS)
23 | #define COMMONS_CRYPTO_OPENSSL_LIBRARY "libcrypto.dll"
24 | #elif defined(MAC_OS)
25 | #define COMMONS_CRYPTO_OPENSSL_LIBRARY "libcrypto.dylib"
26 | #else
27 | #define COMMONS_CRYPTO_OPENSSL_LIBRARY "libcrypto.so"
28 | #endif
29 |
30 | #endif // __CONFIG_H
31 |
--------------------------------------------------------------------------------
/src/assembly/bin.xml:
--------------------------------------------------------------------------------
1 |
18 |
21 | bin
22 |
23 | tar.gz
24 | zip
25 |
26 | false
27 |
28 |
29 |
30 | LICENSE.txt
31 | NOTICE.txt
32 | README.md
33 | RELEASE-NOTES.txt
34 | CONTRIBUTING.md
35 |
36 |
37 |
38 | target
39 |
40 |
41 | ${artifactId}-${version}.jar
42 |
43 | 644
44 |
45 |
46 | target/site/apidocs
47 | apidocs
48 |
49 | **/*
50 |
51 |
52 |
53 | target
54 |
55 |
56 | ${artifactId}-${version}-sources.jar
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/src/assembly/src.xml:
--------------------------------------------------------------------------------
1 |
18 |
21 | src
22 |
23 | tar.gz
24 | zip
25 |
26 | ${project.artifactId}-${project.version}-src
27 |
28 |
29 |
30 | BUILDING.txt
31 | checkstyle.xml
32 | CONTRIBUTING.md
33 | LICENSE.txt
34 | Makefile
35 | Makefile.common
36 | NOTICE.txt
37 | pom.xml
38 | README.md
39 | RELEASE-NOTES.txt
40 |
41 |
42 |
43 | src
44 |
45 |
46 | lib
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/src/conf/checkstyle/checkstyle-suppressions.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/src/conf/checkstyle/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/src/conf/pmd/pmd-ruleset.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
22 |
23 | This ruleset checks the code for discouraged programming constructs.
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/src/conf/spotbugs/spotbugs-exclude-filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/src/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | # This file creates a Docker image for use in building various native binaries
17 | # for Linux 64-bit and 32-bit, and Windows 64-bit and 32-bit.
18 | # See the README for further details.
19 |
20 | FROM amd64/ubuntu:20.04
21 | # macOS M1 defaults to aarch64, which does not support all the 32bit dependencies
22 | # So force the use of amd64 as per Ubuntu
23 | # This also works on macOS M1 (Sonoma)
24 |
25 | ENV JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
26 | ENV MAVEN_HOME=/opt/maven
27 | ENV PATH=${MAVEN_HOME}/bin:${PATH}
28 | # Install 64-bit dependencies and tooling.
29 | RUN apt-get update && apt-get --assume-yes install software-properties-common \
30 | && add-apt-repository ppa:openjdk-r/ppa && apt-get update \
31 | && apt-get --assume-yes install openjdk-8-jdk \
32 | && apt-get --assume-yes install build-essential \
33 | && apt-get --assume-yes install libssl-dev \
34 | && apt-get --assume-yes install gcc-aarch64-linux-gnu \
35 | && apt-get --assume-yes install g++-aarch64-linux-gnu \
36 | && apt-get --assume-yes install gcc-riscv64-linux-gnu \
37 | && apt-get --assume-yes install g++-riscv64-linux-gnu \
38 | && apt-get --assume-yes install mingw-w64 \
39 | && apt-get --assume-yes install curl \
40 | && apt-get --assume-yes install dos2unix \
41 | # Bug workaround see https://github.com/docker-library/openjdk/issues/19.
42 | && /var/lib/dpkg/info/ca-certificates-java.postinst configure
43 |
44 | # Install 32-bit dependencies and tooling.
45 | RUN dpkg --add-architecture i386 && apt-get update \
46 | && apt-get --assume-yes install libssl-dev:i386 \
47 | && apt-get --assume-yes install gcc-arm-linux-gnueabi \
48 | && apt-get --assume-yes install g++-arm-linux-gnueabi \
49 | && apt-get --assume-yes install gcc-arm-linux-gnueabihf \
50 | && apt-get --assume-yes install g++-arm-linux-gnueabihf
51 |
52 | # Do this separately to make upgrades easier
53 | RUN curl -sL https://dlcdn.apache.org/maven/maven-3/3.9.9/binaries/apache-maven-3.9.9-bin.tar.gz \
54 | | tar xzf - -C /opt && ln -s /opt/apache-maven-3.9.9 /opt/maven
55 |
56 | # Ensure we are in the correct directory (this will be overlaid by the virtual mount)
57 | WORKDIR /home/crypto
58 |
59 | CMD ["/bin/bash"]
60 |
--------------------------------------------------------------------------------
/src/docker/Dockerfile.aarch64:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | # This file creates a Docker image for use in testing linux-aarch64 on CI
17 |
18 | FROM ubuntu:20.04
19 |
20 | ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-arm64
21 | ENV MAVEN_HOME=/opt/maven
22 | ENV PATH=${MAVEN_HOME}/bin:${PATH}
23 | # Install 64-bit dependencies and tooling.
24 | RUN apt-get update -qq && apt-get -y -qq install \
25 | openjdk-17-jdk-headless \
26 | libssl-dev \
27 | curl dos2unix gcc g++ make gcc-riscv64-linux-gnu g++-riscv64-linux-gnu gcc-mingw-w64-x86-64 g++-mingw-w64-x86-64 \
28 | # Bug workaround see https://github.com/docker-library/openjdk/issues/19.
29 | && /var/lib/dpkg/info/ca-certificates-java.postinst configure
30 |
31 | # Do this separately to make upgrades easier
32 | RUN curl -sL https://dlcdn.apache.org/maven/maven-3/3.9.9/binaries/apache-maven-3.9.9-bin.tar.gz \
33 | | tar xzf - -C /opt && ln -s /opt/apache-maven-3.9.9 /opt/maven
34 |
35 | # Ensure we are in the correct directory (this will be overlaid by the virtual mount)
36 | WORKDIR /home/crypto
37 |
38 | CMD ["/bin/bash"]
39 |
--------------------------------------------------------------------------------
/src/docker/Dockerfile.riscv64:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | # This file creates a Docker image for use in testing linux-riscv64 on CI
17 |
18 | FROM riscv64/ubuntu:20.04
19 |
20 | ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-riscv64
21 | ENV MAVEN_HOME=/opt/maven
22 | ENV PATH=${MAVEN_HOME}/bin:${PATH}
23 | # Install 64-bit dependencies and tooling.
24 | RUN apt-get update -qq && apt-get -y -qq install \
25 | openjdk-17-jdk-headless \
26 | libssl-dev \
27 | curl make dos2unix \
28 | # Bug workaround see https://github.com/docker-library/openjdk/issues/19.
29 | && /var/lib/dpkg/info/ca-certificates-java.postinst configure
30 |
31 | # Do this separately to make upgrades easier
32 | RUN curl -sL https://dlcdn.apache.org/maven/maven-3/3.9.9/binaries/apache-maven-3.9.9-bin.tar.gz \
33 | | tar xzf - -C /opt && ln -s /opt/apache-maven-3.9.9 /opt/maven
34 |
35 | # Ensure we are in the correct directory (this will be overlaid by the virtual mount)
36 | WORKDIR /home/crypto
37 |
38 | CMD ["/bin/bash"]
39 |
--------------------------------------------------------------------------------
/src/docker/README.md:
--------------------------------------------------------------------------------
1 |
18 |
19 | # About
20 |
21 | This directory contains scripts needed to build Crypto native code using a Docker image.
22 |
23 | The Docker image runs on Ubuntu and includes Maven and cross-compilation tools
24 | which are used to build Linux and Windows native code files (see build-*.sh for the list).
25 | The image uses virtual mounts for the source code and Maven repository, so the output
26 | of the build is available on the host system and can be included in a subsequent release
27 | build.
28 |
29 | The binary jar is built from the contents of target/classes, so any additional native objects can be added to the build by copying them to the appropriate directory under
30 | target/classes/org/apache/commons/crypto/native before creating the release.
31 | For example, the macOS object can be added as
32 | target/classes/org/apache/commons/crypto/native/Mac/x86_64/libcommons-crypto.jnilib
33 |
34 | # Building the Docker image
35 |
36 | ```
37 | cd src/docker
38 | docker compose build crypto
39 | ```
40 |
41 | # Running the Docker image
42 |
43 | ```
44 | cd src/docker
45 | docker compose run crypto # run shell; can then use Maven to do builds
46 | OR
47 | docker compose run --entrypoint src/docker/build-x86_64.sh crypto # run full build
48 | docker compose run --entrypoint src/docker/build_linux32.sh crypto # optionally run linux32 build
49 | # The linux32 build needs an additional install, but that causes linux 64 bit builds to fail.
50 | ```
51 |
52 | # Creating a release candidate using macOS
53 |
54 | This is the easiest if the release manager has access to a macOS host.
55 |
56 | The steps are:
57 |
58 | - mvn clean
59 | - cd src/docker
60 | - docker compose run --entrypoint src/docker/build-x86_64.sh crypto
61 | - docker compose run --entrypoint src/docker/build_linux32.sh crypto # optional
62 | - cd ../..
63 |
64 | Now perform the release (don't run mvn clean!)
65 | - mvn release ...
66 |
67 | # Creating a release candidate using another OS
68 |
69 | If the Release Manager (RM) does not have access to a macOS system, they will need to obtain a copy
70 | of the macOS native binary from another Commons developer.
71 |
72 | The process starts as above, but just before using the host system to build the release,
73 | add the macOS binary to the workspace at:
74 |
75 | ```target/classes/org/apache/commons/crypto/native/Mac/x86_64/libcommons-crypto.jnilib```
76 |
77 | The release can then be created in the normal way.
78 |
--------------------------------------------------------------------------------
/src/docker/build-aarch64.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Licensed to the Apache Software Foundation (ASF) under one or more
4 | # contributor license agreements. See the NOTICE file distributed with
5 | # this work for additional information regarding copyright ownership.
6 | # The ASF licenses this file to You under the Apache License, Version 2.0
7 | # (the "License"); you may not use this file except in compliance with
8 | # the License. You may obtain a copy of the License at
9 | #
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 |
18 | # Script to build native files under Docker
19 |
20 | set -ex
21 |
22 | cd /home/crypto # must agree with virtual mount in docker-compose.yaml
23 |
24 | # Ensure the correct config file is installed
25 | cp /usr/include/aarch64-linux-gnu/openssl/opensslconf.h /usr/include/openssl
26 |
27 | # Speed up builds by disabling unnecessary plugins
28 | # Note: spdx.skip requires version 0.7.1+
29 | MAVEN_ARGS="-V -B -ntp -Drat.skip -Djacoco.skip -DbuildNumber.skip -Danimal.sniffer.skip -Dcyclonedx.skip -Dspdx.skip"
30 | # requires Maven 3.9.0+ to be automatically read
31 |
32 | # Run the 64-bit builds (no test)
33 | mvn clean test -DskipTests ${MAVEN_ARGS}
34 |
35 | # use process-classes rather than package to speed up builds
36 | mvn process-classes -Dtarget.name=linux-aarch64 ${MAVEN_ARGS}
37 | mvn process-classes -Dtarget.name=linux-riscv64 ${MAVEN_ARGS}
38 | mvn process-classes -Dtarget.name=win64 ${MAVEN_ARGS}
39 | mvn process-classes -Dtarget.name=linux64 ${MAVEN_ARGS}
40 |
41 | # Ensure the correct config file is installed
42 | cp /usr/include/i386-linux-gnu/openssl/opensslconf.h /usr/include/openssl
43 |
44 | # Run the 32-bit builds.
45 | mvn process-classes -Dtarget.name=linux-armhf ${MAVEN_ARGS}
46 | mvn process-classes -Dtarget.name=linux-arm ${MAVEN_ARGS}
47 | mvn process-classes -Dtarget.name=win32 ${MAVEN_ARGS}
48 |
49 | # see separate script for optional linux32 build
50 |
51 | # Show generated files
52 | find target/classes/org/apache/commons/crypto/native -type f -ls
53 |
--------------------------------------------------------------------------------
/src/docker/build-x86_64.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Licensed to the Apache Software Foundation (ASF) under one or more
4 | # contributor license agreements. See the NOTICE file distributed with
5 | # this work for additional information regarding copyright ownership.
6 | # The ASF licenses this file to You under the Apache License, Version 2.0
7 | # (the "License"); you may not use this file except in compliance with
8 | # the License. You may obtain a copy of the License at
9 | #
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 |
18 | # Script to build native files under Docker
19 |
20 | set -ex
21 |
22 | cd /home/crypto # must agree with virtual mount in docker-compose.yaml
23 |
24 | # Ensure the correct config file is installed
25 | cp /usr/include/x86_64-linux-gnu/openssl/opensslconf.h /usr/include/openssl
26 |
27 | # Speed up builds by disabling unnecessary plugins
28 | # Note: spdx.skip requires version 0.7.1+
29 | MAVEN_ARGS="-V -B -ntp -Drat.skip -Djacoco.skip -DbuildNumber.skip -Danimal.sniffer.skip -Dcyclonedx.skip -Dspdx.skip"
30 | # requires Maven 3.9.0+ to be automatically read
31 |
32 | # Run the 64-bit builds (no test)
33 | mvn clean test -DskipTests ${MAVEN_ARGS}
34 |
35 | # use process-classes rather than package to speed up builds
36 | mvn process-classes -Dtarget.name=linux-aarch64 ${MAVEN_ARGS}
37 | mvn process-classes -Dtarget.name=linux-riscv64 ${MAVEN_ARGS}
38 | mvn process-classes -Dtarget.name=win64 ${MAVEN_ARGS}
39 | mvn process-classes -Dtarget.name=linux64 ${MAVEN_ARGS}
40 |
41 | # Ensure the correct config file is installed
42 | cp /usr/include/i386-linux-gnu/openssl/opensslconf.h /usr/include/openssl
43 |
44 | # Run the 32-bit builds.
45 | mvn process-classes -Dtarget.name=linux-armhf ${MAVEN_ARGS}
46 | mvn process-classes -Dtarget.name=linux-arm ${MAVEN_ARGS}
47 | mvn process-classes -Dtarget.name=win32 ${MAVEN_ARGS}
48 |
49 | # see separate script for optional linux32 build
50 |
51 | # Show generated files
52 | find target/classes/org/apache/commons/crypto/native -type f -ls
53 |
--------------------------------------------------------------------------------
/src/docker/build_linux32.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Licensed to the Apache Software Foundation (ASF) under one or more
4 | # contributor license agreements. See the NOTICE file distributed with
5 | # this work for additional information regarding copyright ownership.
6 | # The ASF licenses this file to You under the Apache License, Version 2.0
7 | # (the "License"); you may not use this file except in compliance with
8 | # the License. You may obtain a copy of the License at
9 | #
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 |
18 | # Script to build linux32 native file under Docker
19 |
20 | # MUST not be run before build-x86_64
21 |
22 | set -ex
23 |
24 | cd /home/crypto # must agree with virtual mount in docker-compose.yaml
25 |
26 | # Ensure the correct config file is installed
27 | cp /usr/include/i386-linux-gnu/openssl/opensslconf.h /usr/include/openssl
28 |
29 | # ensure apt database is updated before a new install
30 | apt-get update
31 |
32 | # Needed for linux32, but causes linux 64 builds to fail
33 | apt-get --assume-yes -qq install g++-multilib >/dev/null
34 |
35 | # Speed up builds by disabling unnecessary plugins
36 | # Note: spdx.skip requires version 0.7.1+
37 | MAVEN_ARGS="-V -B -ntp -Drat.skip -Djacoco.skip -DbuildNumber.skip -Danimal.sniffer.skip -Dcyclonedx.skip -Dspdx.skip"
38 | # requires Maven 3.9.0+ to be automatically read
39 |
40 | mvn process-classes -Dtarget.name=linux32 ${MAVEN_ARGS}
41 |
42 | # Show generated files
43 | find target/classes/org/apache/commons/crypto/native -type f -ls
44 |
--------------------------------------------------------------------------------
/src/docker/docker-compose-gh.yaml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | # Version of docker-compose for use with Github actions
17 | # References remote images and excludes build info
18 |
19 | services:
20 | crypto-gh:
21 | image: ${IMAGE_PREFIX}:latest
22 | # mount the source and Maven repo
23 | volumes:
24 | - ../..:/home/crypto
25 | - ~/.m2/repository:/root/.m2/repository
26 |
27 | crypto-aarch64-gh:
28 | image: ${IMAGE_PREFIX}-aarch64:latest
29 | platform: linux/arm64/v8
30 | # mount the source and Maven repo
31 | volumes:
32 | - ../..:/home/crypto
33 | - ~/.m2/repository:/root/.m2/repository
34 |
35 | crypto-riscv64-gh:
36 | image: ${IMAGE_PREFIX}-riscv64:latest
37 | platform: linux/riscv64
38 | # mount the source and Maven repo
39 | volumes:
40 | - ../..:/home/crypto
41 | - ~/.m2/repository:/root/.m2/repository
42 |
--------------------------------------------------------------------------------
/src/docker/docker-compose.yaml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | # This file is used for building and testing the images locally
17 |
18 | # See also docker-compose-gh.yml, which uses the images built by the docker_images.yml workflow
19 |
20 | services:
21 | crypto:
22 | image: commons-crypto
23 | build:
24 | context: .
25 | dockerfile: Dockerfile
26 | # mount the source and Maven repo
27 | volumes:
28 | - ../..:/home/crypto
29 | - ~/.m2/repository:/root/.m2/repository
30 |
31 | crypto-aarch64: &crypto-aarch64
32 | image: commons-crypto:aarch64
33 | platform: linux/arm64/v8
34 | build:
35 | context: .
36 | dockerfile: Dockerfile.aarch64
37 | # mount the source and Maven repo
38 | volumes:
39 | - ../..:/home/crypto
40 | - ~/.m2/repository:/root/.m2/repository
41 |
42 | crypto-riscv64: &crypto-riscv64
43 | image: commons-crypto:riscv64
44 | platform: linux/riscv64
45 | build:
46 | context: .
47 | dockerfile: Dockerfile.riscv64
48 | # mount the source and Maven repo
49 | volumes:
50 | - ../..:/home/crypto
51 | - ~/.m2/repository:/root/.m2/repository
52 |
--------------------------------------------------------------------------------
/src/docker/test_cross.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Licensed to the Apache Software Foundation (ASF) under one or more
4 | # contributor license agreements. See the NOTICE file distributed with
5 | # this work for additional information regarding copyright ownership.
6 | # The ASF licenses this file to You under the Apache License, Version 2.0
7 | # (the "License"); you may not use this file except in compliance with
8 | # the License. You may obtain a copy of the License at
9 | #
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 |
18 | # Script to test aarch64 and riscv64 under Docker
19 |
20 | set -ex
21 |
22 | cd /home/crypto # must agree with virtual mount in docker-compose.yaml
23 |
24 | mvn -V -B -ntp surefire:test "$@"
25 |
26 | # Show generated files
27 | find target/classes/org/apache/commons/crypto/native -type f -ls
28 |
--------------------------------------------------------------------------------
/src/docker/tests.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Licensed to the Apache Software Foundation (ASF) under one or more
4 | # contributor license agreements. See the NOTICE file distributed with
5 | # this work for additional information regarding copyright ownership.
6 | # The ASF licenses this file to You under the Apache License, Version 2.0
7 | # (the "License"); you may not use this file except in compliance with
8 | # the License. You may obtain a copy of the License at
9 | #
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 |
18 | # Run some additional tests
19 |
20 | crypto() {
21 | CLASS=$1
22 | echo crypto $CLASS
23 | # This adds the necessary libraries
24 | mvn -q exec:java -Dexec.mainClass=org.apache.commons.crypto.$CLASS
25 | echo ""
26 | }
27 |
28 | example() {
29 | CLASS=$1
30 | echo example $CLASS
31 | mvn -q exec:java -Dexec.classpathScope=test -Dexec.mainClass=org.apache.commons.crypto.examples.$CLASS
32 | echo ""
33 | }
34 |
35 | java -cp target/classes org.apache.commons.crypto.Crypto
36 |
37 | example CipherByteArrayExample
38 |
39 | example RandomExample
40 |
41 | example StreamExample
42 |
43 | crypto jna.OpenSslJna
44 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/OpenSslInfoNative.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto;
19 |
20 | import org.apache.commons.crypto.random.CryptoRandom;
21 |
22 | /**
23 | * JNI interface of {@link CryptoRandom} implementation for OpenSSL.
24 | * The native method in this class is defined in
25 | * OpenSslCryptoRandomNative.h (generated at build time by javah)
26 | * and implemented in the file
27 | * src/main/native/org/apache/commons/crypto/random/OpenSslCryptoRandomNative.c
28 | */
29 | final class OpenSslInfoNative {
30 |
31 | /**
32 | * Return the name used to load the dynamic linked library.
33 | *
34 | * @return the name used to load the library (e.g. crypto.dll)
35 | */
36 | public static native String DLLName();
37 |
38 | /**
39 | * Return the path to the loaded dynamic linked library.
40 | * [Currently not implemented on Windows]
41 | * @return the path to the library that was loaded; may be {@code null}.
42 | */
43 | public static native String DLLPath();
44 |
45 | /**
46 | * @return name of native
47 | */
48 | public static native String NativeName();
49 |
50 | /**
51 | * @return timestamp of native
52 | */
53 | public static native String NativeTimeStamp();
54 |
55 | /**
56 | * @return version of native
57 | */
58 | public static native String NativeVersion();
59 |
60 | /**
61 | * @return the value of OPENSSL_VERSION_NUMBER.
62 | */
63 | public static native long OpenSSL();
64 |
65 | /**
66 | * Returns OpenSSL_version according the version type.
67 | *
68 | * @param type The version type
69 | * @return The text variant of the version number and the release date.
70 | */
71 | public static native String OpenSSLVersion(int type);
72 |
73 | /**
74 | * @return version of OPENSSL_VERSION_TEXT from the header file used to compile the code
75 | */
76 | public static native String HeaderVersionText();
77 |
78 | /**
79 | * @return the value of OPENSSL_VERSION_NUMBER from the header file used to compile the code
80 | */
81 | public static native long HeaderVersionNumber();
82 |
83 | /**
84 | * Makes the constructor private.
85 | */
86 | private OpenSslInfoNative() {
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/cipher/AbstractOpenSslFeedbackCipher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.cipher;
19 |
20 | import java.nio.ByteBuffer;
21 | import java.security.InvalidAlgorithmParameterException;
22 | import java.security.spec.AlgorithmParameterSpec;
23 |
24 | import javax.crypto.BadPaddingException;
25 | import javax.crypto.IllegalBlockSizeException;
26 | import javax.crypto.ShortBufferException;
27 |
28 | import org.apache.commons.crypto.utils.Utils;
29 |
30 | /**
31 | * This class represents a block cipher in one of its modes.
32 | */
33 | abstract class AbstractOpenSslFeedbackCipher {
34 |
35 | protected long context;
36 | protected final int algorithmMode;
37 | protected final int padding;
38 |
39 | protected int cipherMode = OpenSsl.DECRYPT_MODE;
40 |
41 | AbstractOpenSslFeedbackCipher(final long context, final int algorithmMode, final int padding) {
42 | this.context = context;
43 | this.algorithmMode = algorithmMode;
44 | this.padding = padding;
45 | }
46 |
47 | public void checkState() {
48 | Utils.checkState(context != 0, "Cipher context is invalid.");
49 | }
50 |
51 | public void clean() {
52 | if (context != 0) {
53 | OpenSslNative.clean(context);
54 | context = 0;
55 | }
56 | }
57 |
58 | abstract int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
59 | throws ShortBufferException, IllegalBlockSizeException, BadPaddingException;
60 |
61 | abstract int doFinal(ByteBuffer input, ByteBuffer output) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException;
62 |
63 | abstract void init(int mode, byte[] key, AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException;
64 |
65 | abstract int update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException;
66 |
67 | abstract int update(ByteBuffer input, ByteBuffer output) throws ShortBufferException;
68 |
69 | abstract void updateAAD(byte[] aad);
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/cipher/OpenSslEvpCtrlValues.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.cipher;
19 |
20 | /**
21 | * This enum is defined for OpenSslNative.ctrl() to allow various cipher
22 | * specific parameters to be determined and set.
23 | * see the macro definitions in openssl/evp.h
24 | */
25 | enum OpenSslEvpCtrlValues {
26 | INIT(0x00),
27 | SET_KEY_LENGTH(0x01),
28 | GET_RC2_KEY_BITS(0x02),
29 | SET_RC2_KEY_BITS(0x03),
30 | GET_RC5_ROUNDS(0x04),
31 | SET_RC5_ROUNDS(0x05),
32 | RAND_KEY(0x06),
33 | PBE_PRF_NID(0x07),
34 | COPY(0x08),
35 | AEAD_SET_IVLEN(0x09),
36 | AEAD_GET_TAG(0x10),
37 | AEAD_SET_TAG(0x11),
38 | AEAD_SET_IV_FIXED(0x12),
39 | GCM_IV_GEN(0x13),
40 | CCM_SET_L(0x14),
41 | CCM_SET_MSGLEN(0x15);
42 |
43 | private final int value;
44 |
45 | OpenSslEvpCtrlValues(final int value) {
46 | this.value = value;
47 | }
48 |
49 | int getValue() {
50 | return value;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/cipher/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * CryptoCipher classes
21 | */
22 | package org.apache.commons.crypto.cipher;
23 |
24 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/jna/OpenSslInterfaceNativeJna.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.jna;
20 |
21 | import java.nio.ByteBuffer;
22 |
23 | import com.sun.jna.NativeLong;
24 | import com.sun.jna.ptr.PointerByReference;
25 |
26 | /**
27 | * This interface defines the API for the native code.
28 | *
29 | * All methods are listed here; individual implementations may not support them all.
30 | *
31 | */
32 | interface OpenSslInterfaceNativeJna {
33 |
34 | PointerByReference _ENGINE_by_id(final String string);
35 |
36 | /**
37 | * TODO Appears to be deprecated as of OpenSSL 1.1.0.
38 | *
39 | * @return See OpenSSL.
40 | */
41 | int _ENGINE_cleanup();
42 |
43 | int _ENGINE_finish(final PointerByReference rdrandEngine);
44 |
45 | int _ENGINE_free(final PointerByReference rdrandEngine);
46 |
47 | int _ENGINE_init(final PointerByReference rdrandEngine);
48 |
49 | void _ENGINE_load_rdrand();
50 |
51 | int _ENGINE_set_default(final PointerByReference rdrandEngine, final int flags);
52 |
53 | String _ERR_error_string(final NativeLong err, final char[] buff);
54 |
55 | NativeLong _ERR_peek_error();
56 |
57 | PointerByReference _EVP_aes_128_cbc();
58 |
59 | PointerByReference _EVP_aes_128_ctr();
60 |
61 | PointerByReference _EVP_aes_192_cbc();
62 |
63 | PointerByReference _EVP_aes_192_ctr();
64 |
65 | PointerByReference _EVP_aes_256_cbc();
66 |
67 | PointerByReference _EVP_aes_256_ctr();
68 |
69 | void _EVP_CIPHER_CTX_cleanup(final PointerByReference context);
70 |
71 | void _EVP_CIPHER_CTX_free(final PointerByReference context);
72 |
73 | PointerByReference _EVP_CIPHER_CTX_new();
74 |
75 | int _EVP_CIPHER_CTX_set_padding(final PointerByReference context, final int padding);
76 |
77 | int _EVP_CipherFinal_ex(final PointerByReference context, final ByteBuffer outBuffer,
78 | final int[] outlen);
79 |
80 | int _EVP_CipherInit_ex(final PointerByReference context, final PointerByReference algo,
81 | final PointerByReference impl, final byte[] encoded, final byte[] iv, final int cipherMode);
82 |
83 | int _EVP_CipherUpdate(final PointerByReference context, final ByteBuffer outBuffer,
84 | final int[] outlen, final ByteBuffer inBuffer, final int remaining);
85 |
86 | Throwable _INIT_ERROR();
87 |
88 | boolean _INIT_OK();
89 |
90 | String _OpenSSL_version(final int i);
91 |
92 | long _OpenSSL_version_num();
93 |
94 | int _RAND_bytes(final ByteBuffer buf, final int length);
95 |
96 | PointerByReference _RAND_get_rand_method();
97 |
98 | PointerByReference _RAND_SSLeay();
99 | }
100 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/jna/OpenSslMacOS.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.jna;
20 |
21 | import com.sun.jna.Native;
22 |
23 | /*
24 | * Get access to dlopen_preflight from JNA code
25 | * For use on macOS only - CRYPTO-179
26 | */
27 | class OpenSslMacOS {
28 |
29 | /*
30 | * The method is declared as 'bool dlopen_preflight(const char* path)', which is not a standard
31 | * JNA type, see:
32 | * https://java-native-access.github.io/jna/5.13.0/javadoc/overview-summary.html#marshalling
33 | * bool appears to be closest to a byte, where non-zero is true and zero is false
34 | */
35 | static native byte dlopen_preflight(String path);
36 |
37 | static native String dlerror();
38 |
39 | static {
40 | Native.register((String)null);
41 | }
42 |
43 | /**
44 | * Check if can load library OK
45 | * @param path
46 | * @return null if OK, else error message
47 | */
48 | public static String checkLibrary(final String path) {
49 | final boolean loadedOK = dlopen_preflight(path) != 0;
50 | final String dlerror = dlerror(); // fetch error, and clear for next call
51 | return loadedOK ? null : dlerror;
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/jna/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * JNA classes
21 | */
22 | package org.apache.commons.crypto.jna;
23 |
24 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * Crypto classes
21 | */
22 | package org.apache.commons.crypto;
23 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/random/CryptoRandom.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.random;
19 |
20 | import java.io.Closeable;
21 |
22 | /**
23 | * Generates random bytes.
24 | *
25 | * Note that implementations must provide a constructor that takes a Properties instance.
26 | *
27 | */
28 | public interface CryptoRandom extends Closeable {
29 |
30 | /**
31 | * Generates random bytes and places them into a user-supplied byte array.
32 | * The number of random bytes produced is equal to the length of the byte
33 | * array.
34 | *
35 | * @param bytes the byte array to fill with random bytes
36 | */
37 | void nextBytes(byte[] bytes);
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/random/JavaCryptoRandom.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.random;
19 |
20 | import java.security.NoSuchAlgorithmException;
21 | import java.security.SecureRandom;
22 | import java.util.Properties;
23 |
24 | import org.apache.commons.crypto.utils.Utils;
25 |
26 | /**
27 | * A CryptoRandom of Java implementation.
28 | *
29 | * This class is not public/protected so does not appear in the main Javadoc Please ensure that property use is documented in the enum
30 | * CryptoRandomFactory.RandomProvider
31 | *
32 | */
33 | final class JavaCryptoRandom implements CryptoRandom {
34 |
35 | private static final int BUFFER_SIZE = 8;
36 |
37 | private static SecureRandom createSecureRandom(final Properties properties) {
38 | try {
39 | return SecureRandom.getInstance(getAlgorithm(properties));
40 | } catch (final NoSuchAlgorithmException e) {
41 | return new SecureRandom();
42 | }
43 | }
44 |
45 | private static String getAlgorithm(final Properties properties) {
46 | return properties.getProperty(CryptoRandomFactory.JAVA_ALGORITHM_KEY, CryptoRandomFactory.JAVA_ALGORITHM_DEFAULT);
47 | }
48 |
49 | private static SecureRandom seed(final SecureRandom secureRandom) {
50 | // Seed the SecureRandom by calling nextBytes(byte[])
51 | secureRandom.nextBytes(new byte[BUFFER_SIZE]);
52 | return secureRandom;
53 | }
54 |
55 | private final SecureRandom instance;
56 |
57 | /**
58 | * Constructs a {@link JavaCryptoRandom}.
59 | *
60 | * @param properties the configuration properties. Uses the key {@link CryptoRandomFactory#JAVA_ALGORITHM_KEY} to get the name of the algorithm, with a
61 | * default of {@link CryptoRandomFactory#JAVA_ALGORITHM_DEFAULT}
62 | */
63 | public JavaCryptoRandom(final Properties properties) {
64 | instance = seed(createSecureRandom(properties));
65 | }
66 |
67 | /**
68 | * Overrides {@link AutoCloseable#close()}. For {@link JavaCryptoRandom}, we don't need to recycle resource.
69 | */
70 | @Override
71 | public void close() {
72 | // do nothing
73 | }
74 |
75 | /**
76 | * Overrides Random#next(). Generates an integer containing the user-specified number of random bits(right justified, with leading zeros).
77 | *
78 | * @param numBits number of random bits to be generated, where 0 {@literal <=} {@code numBits} {@literal <=} 32.
79 | * @return int an {@code int} containing the user-specified number of random bits (right justified, with leading zeros).
80 | */
81 | protected int next(final int numBits) {
82 | Utils.checkArgument(numBits >= 0 && numBits <= Integer.SIZE);
83 | // Can't simply invoke instance.next(bits) here, because that is package protected.
84 | // But, this should do.
85 | return instance.nextInt() >>> Integer.SIZE - numBits;
86 | }
87 |
88 | /**
89 | * Overrides {@link CryptoRandom#nextBytes(byte[])}. Generates random bytes and places them into a user-supplied byte array. The number of random bytes
90 | * produced is equal to the length of the byte array.
91 | *
92 | * @param bytes the array to be filled in with random bytes.
93 | */
94 | @Override
95 | public void nextBytes(final byte[] bytes) {
96 | instance.nextBytes(bytes);
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/random/OpenSslCryptoRandomNative.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.random;
19 |
20 | /**
21 | * JNI interface of {@link CryptoRandom} implementation for OpenSSL.
22 | * The native method in this class is defined in
23 | * OpenSslCryptoRandomNative.h (generated at build time by javah)
24 | * and implemented in the file
25 | * src/main/native/org/apache/commons/crypto/random/OpenSslCryptoRandomNative.c
26 | */
27 | final class OpenSslCryptoRandomNative {
28 |
29 | /**
30 | * Declares a native method to initialize SR.
31 | */
32 | public static native void initSR();
33 |
34 | /**
35 | * Judges whether to use {@link OpenSslCryptoRandomNative} to generate the
36 | * user-specified number of random bits.
37 | *
38 | * @param bytes the array to be filled in with random bytes.
39 | * @return {@code true} if use {@link OpenSslCryptoRandomNative} to generate the
40 | * user-specified number of random bits.
41 | */
42 | public static native boolean nextRandBytes(byte[] bytes);
43 |
44 | /**
45 | * The private constructor of {@link OpenSslCryptoRandomNative}.
46 | */
47 | private OpenSslCryptoRandomNative() {
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/random/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * Random classes
21 | */
22 | package org.apache.commons.crypto.random;
23 |
24 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/stream/input/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * Input classes
21 | */
22 | package org.apache.commons.crypto.stream.input;
23 |
24 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/stream/output/ChannelOutput.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.stream.output;
19 |
20 | import java.io.IOException;
21 | import java.nio.ByteBuffer;
22 | import java.nio.channels.WritableByteChannel;
23 | import java.util.Objects;
24 |
25 | import org.apache.commons.crypto.stream.CryptoOutputStream;
26 |
27 | /**
28 | * The ChannelOutput class takes a {@link WritableByteChannel} object and
29 | * wraps it as {@code Output} object acceptable by
30 | * {@link CryptoOutputStream} as the output target.
31 | */
32 | public class ChannelOutput implements Output {
33 |
34 | private final WritableByteChannel channel;
35 |
36 | /**
37 | * Constructs a
38 | * {@link org.apache.commons.crypto.stream.output.ChannelOutput}.
39 | *
40 | * @param channel the WritableByteChannel object.
41 | * @throws NullPointerException if channel is null.
42 | */
43 | public ChannelOutput(final WritableByteChannel channel) {
44 | this.channel = Objects.requireNonNull(channel, "channel");
45 | }
46 |
47 | /**
48 | * Overrides the {@link Output#close()}. Closes this output and releases any
49 | * system resources associated with the under layer output.
50 | *
51 | * @throws IOException if an I/O error occurs.
52 | */
53 | @Override
54 | public void close() throws IOException {
55 | channel.close();
56 | }
57 |
58 | /**
59 | * Overrides the {@link Output#flush()}. Flushes this output and forces any
60 | * buffered output bytes to be written out if the under layer output method
61 | * support.
62 | *
63 | * @throws IOException if an I/O error occurs.
64 | */
65 | @Override
66 | public void flush() throws IOException {
67 | // noop
68 | }
69 |
70 | /**
71 | * Overrides the
72 | * {@link org.apache.commons.crypto.stream.output.Output#write(ByteBuffer)}.
73 | * Writes a sequence of bytes to this output from the given buffer.
74 | *
75 | * @param src The buffer from which bytes are to be retrieved.
76 | * @return The number of bytes written, possibly zero.
77 | * @throws IOException if an I/O error occurs.
78 | */
79 | @Override
80 | public int write(final ByteBuffer src) throws IOException {
81 | return channel.write(src);
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/stream/output/Output.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.stream.output;
19 |
20 | import java.io.Closeable;
21 | import java.io.IOException;
22 | import java.io.OutputStream;
23 | import java.nio.ByteBuffer;
24 | import java.nio.channels.WritableByteChannel;
25 |
26 | import org.apache.commons.crypto.stream.CryptoOutputStream;
27 |
28 | /**
29 | * The Output interface abstract the output target of
30 | * {@link CryptoOutputStream} so that different implementation of output
31 | * can be used. The implementation Output interface will usually wrap an output
32 | * mechanism such as {@link OutputStream} or
33 | * {@link WritableByteChannel}.
34 | */
35 | public interface Output extends Closeable {
36 |
37 | /**
38 | * Closes this output and releases any system resources associated with the
39 | * under layer output.
40 | *
41 | * @throws IOException if an I/O error occurs.
42 | */
43 | @Override
44 | void close() throws IOException;
45 |
46 | /**
47 | * Flushes this output and forces any buffered output bytes to be written
48 | * out if the under layer output method support. The general contract of
49 | * {@code flush} is that calling it is an indication that, if any bytes
50 | * previously written have been buffered by the implementation of the output
51 | * stream, such bytes should immediately be written to their intended
52 | * destination.
53 | *
54 | * @throws IOException if an I/O error occurs.
55 | */
56 | void flush() throws IOException;
57 |
58 | /**
59 | * Writes a sequence of bytes to this output from the given buffer.
60 | *
61 | *
62 | * An attempt is made to write up to r bytes to the channel, where
63 | * r is the number of bytes remaining in the buffer, that is,
64 | * {@code src.remaining()}, at the moment this method is invoked.
65 | *
66 | *
67 | * Suppose that a byte sequence of length n is written, where
68 | * {@code 0} {@code <=} n {@code <=}
69 | * r. This byte sequence will be transferred from the buffer
70 | * starting at index p, where p is the buffer's position at
71 | * the moment this method is invoked; the index of the last byte written
72 | * will be p {@code +} n {@code -}
73 | * {@code 1}. Upon return the buffer's position will be equal to
74 | * p {@code +} n; its limit will not have changed.
75 | *
76 | * @param src The buffer from which bytes are to be retrieved.
77 | * @return The number of bytes written, possibly zero.
78 | * @throws IOException If some other I/O error occurs.
79 | */
80 | int write(ByteBuffer src) throws IOException;
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/stream/output/StreamOutput.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.stream.output;
19 |
20 | import java.io.IOException;
21 | import java.io.OutputStream;
22 | import java.nio.ByteBuffer;
23 | import java.util.Objects;
24 |
25 | import org.apache.commons.crypto.stream.CryptoOutputStream;
26 |
27 | /**
28 | * The StreamOutput class takes a {@link OutputStream} object and wraps it
29 | * as {@link Output} object acceptable by {@link CryptoOutputStream}
30 | * as the output target.
31 | */
32 | public class StreamOutput implements Output {
33 | private final byte[] buf;
34 | private final int bufferSize;
35 | private final OutputStream out;
36 |
37 | /**
38 | * Constructs a new instance.
39 | *
40 | * @param out the OutputStream object.
41 | * @param bufferSize the buffer size.
42 | * @throws NullPointerException if channel is null.
43 | */
44 | public StreamOutput(final OutputStream out, final int bufferSize) {
45 | this.out = Objects.requireNonNull(out, "out");
46 | this.bufferSize = bufferSize;
47 | this.buf = new byte[bufferSize];
48 | }
49 |
50 | /**
51 | * Overrides the {@link Output#close()}. Closes this output and releases any
52 | * system resources associated with the under layer output.
53 | *
54 | * @throws IOException if an I/O error occurs.
55 | */
56 | @Override
57 | public void close() throws IOException {
58 | out.close();
59 | }
60 |
61 | /**
62 | * Overrides the {@link Output#flush()}. Flushes this output and forces any
63 | * buffered output bytes to be written out if the under layer output method
64 | * support.
65 | *
66 | * @throws IOException if an I/O error occurs.
67 | */
68 | @Override
69 | public void flush() throws IOException {
70 | out.flush();
71 | }
72 |
73 | /**
74 | * Gets the output stream.
75 | *
76 | * @return the output stream.
77 | */
78 | protected OutputStream getOut() {
79 | return out;
80 | }
81 |
82 | /**
83 | * Overrides the
84 | * {@link org.apache.commons.crypto.stream.output.Output#write(ByteBuffer)}.
85 | * Writes a sequence of bytes to this output from the given buffer.
86 | *
87 | * @param src The buffer from which bytes are to be retrieved.
88 | * @return The number of bytes written, possibly zero.
89 | * @throws IOException if an I/O error occurs.
90 | */
91 | @Override
92 | public int write(final ByteBuffer src) throws IOException {
93 | final int len = src.remaining();
94 |
95 | int remaining = len;
96 | while (remaining > 0) {
97 | final int n = Math.min(remaining, bufferSize);
98 | src.get(buf, 0, n);
99 | out.write(buf, 0, n);
100 | remaining = src.remaining();
101 | }
102 |
103 | return len;
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/stream/output/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * Output classes
21 | */
22 | package org.apache.commons.crypto.stream.output;
23 |
24 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/stream/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * Stream classes
21 | */
22 | package org.apache.commons.crypto.stream;
23 |
24 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/utils/AES.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.utils;
19 |
20 | import javax.crypto.spec.SecretKeySpec;
21 |
22 | /**
23 | * Creates AES objects
24 | *
25 | * @since 1.2.0
26 | */
27 | public class AES {
28 |
29 | /** The AES algorithm name. */
30 | public static final String ALGORITHM = "AES";
31 |
32 | /**
33 | * Defines {@value}.
34 | */
35 | public static final String CBC_NO_PADDING = "AES/CBC/NoPadding";
36 |
37 | /**
38 | * Defines {@value}.
39 | */
40 | public static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
41 |
42 | /**
43 | * Defines {@value}.
44 | */
45 | public static final String CTR_NO_PADDING = "AES/CTR/NoPadding";
46 |
47 | /**
48 | * Defines {@value}.
49 | */
50 | public static final String GCM_NO_PADDING = "AES/GCM/NoPadding";
51 |
52 | /**
53 | * Creates a new SecretKeySpec for the given key and {@link #ALGORITHM}.
54 | *
55 | * @param key a key.
56 | * @return a new SecretKeySpec.
57 | */
58 | public static SecretKeySpec newSecretKeySpec(final byte[] key) {
59 | return new SecretKeySpec(key, ALGORITHM);
60 | }
61 |
62 | /**
63 | * Constructs a new instance.
64 | *
65 | * @deprecated Will be private in the next major release.
66 | */
67 | @Deprecated
68 | public AES() {
69 | // empty
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/utils/IoUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.utils;
19 |
20 | import java.io.Closeable;
21 | import java.io.IOException;
22 | import java.io.InputStream;
23 |
24 | import org.apache.commons.crypto.stream.input.Input;
25 | import org.apache.commons.io.IOUtils;
26 |
27 | /**
28 | * General utility methods for working with IO.
29 | */
30 | public final class IoUtils {
31 |
32 | /**
33 | * Closes the Closeable objects and ignore any {@link IOException} or
34 | * null pointers. Must only be used for cleanup in exception handlers.
35 | *
36 | * @param closeables the objects to close.
37 | */
38 | public static void cleanup(final Closeable... closeables) {
39 | if (closeables != null) {
40 | for (final Closeable c : closeables) {
41 | closeQuietly(c);
42 | }
43 | }
44 | }
45 |
46 | /**
47 | * Closes the given {@link Closeable} quietly by ignoring IOException.
48 | *
49 | * @param closeable The resource to close.
50 | * @since 1.1.0
51 | */
52 | public static void closeQuietly(final Closeable closeable) {
53 | IOUtils.closeQuietly(closeable);
54 | }
55 |
56 | /**
57 | * Does the readFully based on Input's positioned read. This does not change
58 | * the current offset of the stream and is thread-safe.
59 | *
60 | * @param in the input source.
61 | * @param position the given position.
62 | * @param buffer the buffer to be read.
63 | * @param length the maximum number of bytes to read.
64 | * @param offset the start offset in array buffer.
65 | * @throws IOException if an I/O error occurs.
66 | */
67 | public static void readFully(final Input in, final long position, final byte[] buffer,
68 | final int offset, final int length) throws IOException {
69 | int nread = 0;
70 | while (nread < length) {
71 | final int nbytes = in.read(position + nread, buffer, offset + nread,
72 | length - nread);
73 | if (nbytes < 0) {
74 | throw new IOException(
75 | "End of stream reached before reading fully.");
76 | }
77 | nread += nbytes;
78 | }
79 | }
80 |
81 | /**
82 | * Does the readFully based on the Input read.
83 | *
84 | * @param in the input stream of bytes.
85 | * @param buf the buffer to be read.
86 | * @param off the start offset in array buffer.
87 | * @param len the maximum number of bytes to read.
88 | * @throws IOException if an I/O error occurs.
89 | */
90 | public static void readFully(final InputStream in, final byte[] buf, int off, final int len)
91 | throws IOException {
92 | int toRead = len;
93 | while (toRead > 0) {
94 | final int ret = in.read(buf, off, toRead);
95 | if (ret < 0) {
96 | throw new IOException("Premature EOF from inputStream");
97 | }
98 | toRead -= ret;
99 | off += ret;
100 | }
101 | }
102 |
103 | /**
104 | * The private constructor of {@link IoUtils}.
105 | */
106 | private IoUtils() {
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/utils/Padding.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.utils;
20 |
21 | import javax.crypto.NoSuchPaddingException;
22 |
23 | /**
24 | * Padding types.
25 | */
26 | public enum Padding {
27 |
28 | /** Don't change the order of this enum value. */
29 | NoPadding,
30 |
31 | /** Don't change the order of this enum value. */
32 | PKCS5Padding;
33 |
34 | /**
35 | * Gets a Padding.
36 | *
37 | * @param padding the padding name.
38 | * @return a Padding instance.
39 | * @throws NoSuchPaddingException if the algorithm is not supported.
40 | */
41 | public static Padding get(final String padding) throws NoSuchPaddingException {
42 | try {
43 | return Padding.valueOf(padding);
44 | } catch (final Exception e) {
45 | throw new NoSuchPaddingException("Algorithm not supported: " + padding);
46 | }
47 | }
48 |
49 | }
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/utils/Transformation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.utils;
20 |
21 | import java.security.NoSuchAlgorithmException;
22 |
23 | import javax.crypto.NoSuchPaddingException;
24 |
25 | /**
26 | * Transformation algorithm, mode and padding, in the format "Algorithm/Mode/Padding", for example "AES/CBC/NoPadding".
27 | *
28 | * @since 1.2.0
29 | */
30 | public class Transformation {
31 |
32 | private static final int T_DELIM_PARTS = 3;
33 | private static final String T_DELIM_REGEX = "/";
34 |
35 | /**
36 | * Parses a transformation.
37 | *
38 | * @param transformation current transformation
39 | * @return the Transformation
40 | * @throws NoSuchAlgorithmException if the algorithm is not supported
41 | * @throws NoSuchPaddingException Thrown when the padding is unsupported.
42 | */
43 | public static Transformation parse(final String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException {
44 | if (transformation == null) {
45 | throw new NoSuchAlgorithmException("No transformation given.");
46 | }
47 |
48 | //
49 | // Array containing the components of a Cipher transformation: index 0:
50 | // algorithm (e.g., AES) index 1: mode (e.g., CTR) index 2: padding (e.g.,
51 | // NoPadding)
52 | //
53 | final String[] parts = transformation.split(T_DELIM_REGEX, T_DELIM_PARTS + 1);
54 | if (parts.length != T_DELIM_PARTS) {
55 | throw new NoSuchAlgorithmException("Invalid transformation format: " + transformation);
56 | }
57 | return new Transformation(parts[0], parts[1], parts[2]);
58 | }
59 |
60 | private final String algorithm;
61 | private final String mode;
62 | private final Padding padding;
63 |
64 | /**
65 | * Constructs a new instance.
66 | *
67 | * @param algorithm the algorithm name
68 | * @param mode the mode name
69 | * @param padding the padding name
70 | */
71 | private Transformation(final String algorithm, final String mode, final Padding padding) {
72 | this.algorithm = algorithm;
73 | this.mode = mode;
74 | this.padding = padding;
75 | }
76 |
77 | /**
78 | * Constructs a new instance.
79 | *
80 | * @param algorithm the algorithm name
81 | * @param mode the mode name
82 | * @param padding the padding name
83 | * @throws NoSuchPaddingException Thrown when the padding is unsupported.
84 | */
85 | private Transformation(final String algorithm, final String mode, final String padding) throws NoSuchPaddingException {
86 | this(algorithm, mode, Padding.get(padding));
87 | }
88 |
89 | /**
90 | * Gets the algorithm.
91 | *
92 | * @return the algorithm.
93 | */
94 | public String getAlgorithm() {
95 | return algorithm;
96 | }
97 |
98 | /**
99 | * Gets the mode.
100 | *
101 | * @return the mode.
102 | */
103 | public String getMode() {
104 | return mode;
105 | }
106 |
107 | /**
108 | * Gets the padding.
109 | *
110 | * @return the padding.
111 | */
112 | public Padding getPadding() {
113 | return padding;
114 | }
115 | }
--------------------------------------------------------------------------------
/src/main/java/org/apache/commons/crypto/utils/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * Utils classes
21 | */
22 | package org.apache.commons.crypto.utils;
23 |
--------------------------------------------------------------------------------
/src/main/native/org/apache/commons/crypto/DynamicLoader.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /*
20 | Shared code to load and unload the library.
21 | */
22 |
23 | #include "org_apache_commons_crypto.h"
24 |
25 | static HMODULE openssl; // the cached pointer
26 | HMODULE open_library(JNIEnv *env)
27 |
28 | {
29 | if (!openssl) {
30 | const char *libraryPath = COMMONS_CRYPTO_OPENSSL_LIBRARY;
31 | jclass clazz = (*env)->FindClass(env, "org/apache/commons/crypto/utils/Utils");
32 | if (clazz) {
33 | jmethodID libraryPathFunc = (*env)->GetStaticMethodID(env, clazz, "libraryPath", "(Ljava/lang/String;)Ljava/lang/String;");
34 | if (libraryPathFunc) {
35 | jstring defaultLibrary = (*env)->NewStringUTF(env, COMMONS_CRYPTO_OPENSSL_LIBRARY);
36 | jstring result = (jstring) (*env)->CallStaticObjectMethod(env, clazz, libraryPathFunc, defaultLibrary);
37 | if (result) {
38 | libraryPath = (*env)->GetStringUTFChars(env, result, NULL);
39 | }
40 | }
41 | }
42 | #ifdef MAC_OS
43 | #include
44 | if (0 == strncmp(COMMONS_CRYPTO_OPENSSL_LIBRARY,libraryPath, sizeof(COMMONS_CRYPTO_OPENSSL_LIBRARY))) {
45 | bool ret = dlopen_preflight(libraryPath);
46 | if (!ret) {
47 | char msg[1000];
48 | snprintf(msg, sizeof(msg), "Cannot load default library '%s'; please define jni.library.path! (%s)", libraryPath, dlerror());
49 | THROW(env, "java/lang/UnsatisfiedLinkError", msg);
50 | return 0;
51 | }
52 | }
53 | #endif
54 | #ifdef UNIX
55 | openssl = dlopen(libraryPath, RTLD_LAZY | RTLD_GLOBAL);
56 | #endif
57 |
58 | #ifdef WINDOWS
59 | openssl = LoadLibraryA(libraryPath); // use the non-generic method; assume libraryPath is suitable
60 | #endif
61 |
62 | // Did we succeed?
63 | if (!openssl)
64 | {
65 | char msg[1000];
66 | #ifdef UNIX
67 | snprintf(msg, sizeof(msg), "Cannot load '%s' (%s)!", libraryPath, dlerror()); // returns char*
68 | #endif
69 | #ifdef WINDOWS
70 | // Crude method to convert most likely errors to string
71 | DWORD lastError = GetLastError();
72 | char *lastmsg;
73 | if (lastError == 126)
74 | {
75 | lastmsg = "specified module cannot be found";
76 | }
77 | else if (lastError == 193)
78 | {
79 | lastmsg = "module is not a valid Win32 application";
80 | }
81 | else
82 | {
83 | lastmsg = "unknown error - check online Windows documentation";
84 | }
85 | snprintf(msg, sizeof(msg), "Cannot load '%s' (%d: %s)!", libraryPath, lastError, lastmsg);
86 | #endif
87 | THROW(env, "java/lang/UnsatisfiedLinkError", msg);
88 | return 0;
89 | }
90 | }
91 | return openssl;
92 | }
93 |
94 | void close_library() {
95 | openssl = NULL;
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/native/org/apache/commons/crypto/random/org_apache_commons_crypto_random.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | #ifndef ORG_APACHE_COMMONS_CRYPTO_RANDOM_H
20 | #define ORG_APACHE_COMMONS_CRYPTO_RANDOM_H
21 |
22 | #include "org_apache_commons_crypto.h"
23 |
24 | #include
25 | #include
26 | #include
27 |
28 | #endif //ORG_APACHE_COMMONS_CRYPTO_RANDOM_H
29 |
--------------------------------------------------------------------------------
/src/main/resources/org/apache/commons/crypto/component.properties:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | #
16 |
17 | # This file gives access to the component string from Java
18 |
19 | VERSION=${project.version}
20 | NAME=${project.name}
--------------------------------------------------------------------------------
/src/site/resources/download_crypto.cgi:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # Just call the standard mirrors.cgi script. It will use download.html
3 | # as the input template.
4 | exec /www/www.apache.org/dyn/mirrors/mirrors.cgi $*
5 |
6 |
--------------------------------------------------------------------------------
/src/site/resources/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apache/commons-crypto/d28437a1ba6b0b20d65f69fd88c68da55e9f8301/src/site/resources/images/logo.png
--------------------------------------------------------------------------------
/src/site/resources/profile.jacoco:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | # -----------------------------------------------------------------------------
16 | #
17 | # Empty file used to automatically trigger JaCoCo profile from commons parent pom
18 |
--------------------------------------------------------------------------------
/src/site/site.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
20 | Apache Commons Crypto
21 | /images/logo.png
22 | /index.html
23 | Commons Crypto™ logo
24 |
25 |
26 |
35 |
36 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/src/site/xdoc/faq.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
20 |
21 | Apache Commons Crypto: FAQ
22 |
23 |
24 |
25 |
26 |
Frequently asked questions
27 |
28 |
29 | Commons Crypto provides the CryptoRandom interface for defining secret generators.
30 | The RandomProvider enum in the CryptoRandomFactory defines some sensible default
31 | implementations:
32 |
33 |
34 |
OPENSSL
OpenSSL based JNI implementation shipped with Commons Crypto.
35 |
JAVA
The SecureRandom implementation from the JVM.
36 |
OS
The OS random device implementation. May not be available on some operating systems.
37 |
38 |
39 | When calling CryptoRandomFactory.getCryptoRandom(), Commons Crypto tries to use the OpenSSL
40 | CryptoRandom implementation first. If this fails, the Java implementation is used.
41 | In order use a different CryptoRandom implementation (e.g. OS), the
42 | CryptoRandomFactory.getCryptoRandom(Properties) method can be used, passing in the desired
43 | implementation class names:
44 |
45 |
46 | Properties props = new Properties();
47 | props.setProperty(CryptoRandomFactory.CLASSES_KEY, CryptoRandomFactory.RandomProvider.OS.getClassName());
48 | CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/src/site/xdoc/security.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 | Apache Commons Crypto Security Reports
12 | Commons Team
13 |
14 |
15 |
16 |
17 | For information about reporting or asking questions about
18 | security, please see the
19 | security page
20 | of the Apache Commons project.
21 |
22 |
23 | This page lists all security vulnerabilities fixed in released versions of this component.
24 |
25 |
26 |
27 | Please note that binary patches are never provided. If you need to apply a source code patch, use the
28 | building instructions for the component version that you are using.
29 |
30 |
31 |
32 | If you need help on building this component or other help on following the instructions to
33 | mitigate the known vulnerabilities listed here, please send your questions to the public
34 | user mailing list.
35 |
36 |
37 |
38 | If you have encountered an unlisted security vulnerability or other unexpected behavior that has security
39 | impact, or if the descriptions here are incomplete, please report them privately to the Apache Security
40 | Team. Thank you.
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/AbstractBenchmark.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.commons.crypto;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 |
22 | import java.nio.ByteBuffer;
23 | import java.util.Properties;
24 |
25 | import javax.crypto.Cipher;
26 | import javax.crypto.spec.IvParameterSpec;
27 | import javax.crypto.spec.SecretKeySpec;
28 |
29 | import org.apache.commons.crypto.cipher.CryptoCipher;
30 | import org.apache.commons.crypto.cipher.CryptoCipherFactory;
31 | import org.apache.commons.crypto.random.CryptoRandom;
32 | import org.apache.commons.crypto.random.CryptoRandomFactory;
33 | import org.apache.commons.crypto.utils.AES;
34 |
35 | public abstract class AbstractBenchmark {
36 |
37 | private static final byte[] KEY = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
38 | 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
39 | private static final byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
40 | 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
41 | private static final SecretKeySpec keySpec = AES.newSecretKeySpec(KEY);
42 | private static final IvParameterSpec ivSpec = new IvParameterSpec(IV);
43 | private static final byte[] BUFFER = new byte[1000];
44 |
45 | public AbstractBenchmark() {
46 | super();
47 | }
48 |
49 | protected void encipher(final String cipherClass) throws Exception {
50 | final CryptoCipher enCipher = getCipher(cipherClass);
51 | enCipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
52 | final int bufferSize = 1024;
53 | final ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
54 | final ByteBuffer outBuffer = ByteBuffer.allocateDirect(bufferSize);
55 | inBuffer.put(BUFFER);
56 | inBuffer.flip();
57 | enCipher.doFinal(inBuffer, outBuffer);
58 | enCipher.close();
59 | }
60 |
61 | protected CryptoCipher getCipher(final String className) throws Exception {
62 | final Properties properties = new Properties();
63 | properties.setProperty(CryptoCipherFactory.CLASSES_KEY, className);
64 | final CryptoCipher cipher = CryptoCipherFactory.getCryptoCipher(AES.CTR_NO_PADDING, properties);
65 | assertEquals(className, cipher.getClass().getCanonicalName());
66 | return cipher;
67 | }
68 |
69 | protected CryptoRandom getRandom(final String className) throws Exception {
70 | final Properties props = new Properties();
71 | props.setProperty(CryptoRandomFactory.CLASSES_KEY, className);
72 | final CryptoRandom cryptoRandom = CryptoRandomFactory.getCryptoRandom(props);
73 | assertEquals(className, cryptoRandom.getClass().getCanonicalName());
74 | return cryptoRandom;
75 | }
76 |
77 | protected void random(final String cipherClass) throws Exception {
78 | final CryptoRandom random = getRandom(cipherClass);
79 | random.nextBytes(new byte[1000]);
80 | random.nextBytes(new byte[1000]);
81 | random.close();
82 | }
83 |
84 | }
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/CryptoBenchmark.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.commons.crypto;
19 |
20 | import java.util.concurrent.TimeUnit;
21 |
22 | import org.apache.commons.crypto.cipher.CryptoCipherFactory;
23 | import org.apache.commons.crypto.random.CryptoRandomFactory;
24 | import org.openjdk.jmh.annotations.Benchmark;
25 | import org.openjdk.jmh.annotations.BenchmarkMode;
26 | import org.openjdk.jmh.annotations.Fork;
27 | import org.openjdk.jmh.annotations.Measurement;
28 | import org.openjdk.jmh.annotations.OutputTimeUnit;
29 | import org.openjdk.jmh.annotations.Threads;
30 | import org.openjdk.jmh.annotations.Warmup;
31 | import org.openjdk.jmh.annotations.Mode;
32 |
33 | /**
34 | * Basic Benchmark to compare creation and runtimes for the different implementations.
35 | * Needs work to improve how well the tests mirror real-world use.
36 | */
37 | @BenchmarkMode(Mode.AverageTime)
38 | @Fork(value = 1, jvmArgs = "-server")
39 | @Threads(1)
40 | @Warmup(iterations = 10)
41 | @Measurement(iterations = 20)
42 | @OutputTimeUnit(TimeUnit.MILLISECONDS)
43 | public class CryptoBenchmark extends AbstractBenchmark {
44 |
45 | private static final String RANDOM_JAVA = CryptoRandomFactory.RandomProvider.JAVA.getClassName();
46 | private static final String RANDOM_OS = CryptoRandomFactory.RandomProvider.OS.getClassName();
47 | private static final String RANDOM_OPENSSL = CryptoRandomFactory.RandomProvider.OPENSSL.getClassName();
48 |
49 | private static final String CIPHER_OPENSSL = CryptoCipherFactory.CipherProvider.OPENSSL.getClassName();
50 | private static final String CIPHER_JCE = CryptoCipherFactory.CipherProvider.JCE.getClassName();
51 |
52 | @Benchmark
53 | public void CipherCreateJce() throws Exception {
54 | getCipher(CIPHER_JCE);
55 | }
56 |
57 | @Benchmark
58 | public void CipherCreateOpenssl() throws Exception {
59 | getCipher(CIPHER_OPENSSL);
60 | }
61 |
62 | @Benchmark
63 | public void CipherTestJce() throws Exception {
64 | encipher(CIPHER_JCE);
65 | }
66 |
67 | @Benchmark
68 | public void CipherTestOpenssl() throws Exception {
69 | encipher(CIPHER_OPENSSL);
70 | }
71 |
72 | @Benchmark
73 | public void RandomCreateJava() throws Exception {
74 | getRandom(RANDOM_JAVA);
75 | }
76 |
77 | @Benchmark
78 | public void RandomCreateOpenssl() throws Exception {
79 | getRandom(RANDOM_OPENSSL);
80 | }
81 |
82 | @Benchmark
83 | public void RandomCreateOS() throws Exception {
84 | getRandom(RANDOM_OS);
85 | }
86 |
87 | @Benchmark
88 | public void RandomTestJava() throws Exception {
89 | random(RANDOM_JAVA);
90 | }
91 |
92 | @Benchmark
93 | public void RandomTestOpenssl() throws Exception {
94 | random(RANDOM_OPENSSL);
95 | }
96 |
97 | @Benchmark
98 | public void RandomTestOS() throws Exception {
99 | random(RANDOM_OS);
100 | }
101 |
102 | }
103 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/CryptoTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package org.apache.commons.crypto;
18 |
19 | import static org.junit.jupiter.api.Assertions.assertEquals;
20 | import static org.junit.jupiter.api.Assertions.assertNotNull;
21 | import static org.junit.jupiter.api.Assertions.assertTrue;
22 |
23 | import org.junit.jupiter.api.Test;
24 |
25 | public class CryptoTest {
26 |
27 | // If defined, then fail if the version does not match major/minor bits
28 | private static final String EXPECTED_VERSION_PROPERTY = "CryptoTest.expectedVersion";
29 |
30 | /**
31 | * This test may fail unless the code was built by Maven, as it relies on the VERSION file being set up correctly
32 | */
33 | @Test
34 | public void testGetComponentName() {
35 | final String version = Crypto.getComponentName();
36 | assertNotNull("Should not be null", version);
37 | assertTrue(version.matches("^Apache Commons Crypto.*"), version);
38 | }
39 |
40 | /**
41 | * This test may fail unless the code was built by Maven, as it relies on the VERSION file being set up correctly.
42 | */
43 | @Test
44 | public void testGetComponentVersion() {
45 | final String version = Crypto.getComponentVersion();
46 | assertNotNull("Should not be null", version);
47 | assertTrue(version.matches("^\\d+\\.\\d+.*"), version);
48 | }
49 |
50 | @Test
51 | public void testLoadingError() throws Throwable {
52 | final Throwable loadingError = Crypto.getLoadingError();
53 | if (loadingError != null) {
54 | throw loadingError;
55 | }
56 | assertTrue(true, "Completed OK");
57 | }
58 |
59 | @Test
60 | public void testMain() throws Throwable {
61 | // Check that Crypto.main will actually run tests
62 | assertTrue(Crypto.isNativeCodeLoaded(), "Native code loaded OK");
63 | Crypto.main(new String[] { }); // show the JNI library details
64 | assertTrue(Crypto.isNativeCodeLoaded(), "Completed OK");
65 | final String expectedVersion = System.getProperty(EXPECTED_VERSION_PROPERTY, "");
66 | if (expectedVersion.isEmpty()) {
67 | System.out.println("OpenSSL version was not checked");
68 | } else {
69 | assertEquals(expectedVersion, Long.toHexString(OpenSslInfoNative.OpenSSL() & 0xFFFF0000));
70 | System.out.println("OpenSSL version is as expected");
71 | }
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/NativeCodeLoaderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto;
20 |
21 | import static org.junit.jupiter.api.Assertions.assertInstanceOf;
22 | import static org.junit.jupiter.api.Assertions.assertNotNull;
23 | import static org.junit.jupiter.api.Assertions.assertNull;
24 | import static org.junit.jupiter.api.Assertions.assertTrue;
25 | import static org.junit.jupiter.api.Assumptions.assumeTrue;
26 |
27 | import java.nio.file.Files;
28 | import java.nio.file.Path;
29 |
30 | import org.junit.jupiter.api.Disabled;
31 | import org.junit.jupiter.api.Test;
32 |
33 | public class NativeCodeLoaderTest {
34 |
35 | @Test
36 | public void test() {
37 | assertTrue(NativeCodeLoader.isNativeCodeLoaded(), "Native (JNI) code loaded successfully");
38 | }
39 |
40 | @Test
41 | @Disabled("Causes crash on Ubuntu when compiled with Java 17")
42 | // Also failed on:
43 | // macos-11:java 11,17,21
44 | // ubuntu-20.04:java 17,21 (11 was OK)
45 | // windows-latest:java 17 (11,21 OK)
46 | // The following error is reported:
47 | // "Corrupted channel by directly writing to native stream in forked JVM 1"
48 | // Note that this appears during a subsequent test, and does not
49 | // happen every time.
50 | // At this point it is not known where the native stream is written.
51 | public void testCanLoadIfPresent() {
52 | assumeTrue(NativeCodeLoader.isNativeCodeLoaded());
53 | // This will try to reload the library, so should work
54 | assertNull(NativeCodeLoader.loadLibrary());
55 | }
56 |
57 | @Test
58 | public void testNativeNotPresent() {
59 | assumeTrue(!NativeCodeLoader.isNativeCodeLoaded());
60 | assertNotNull(NativeCodeLoader.getLoadingError());
61 | }
62 |
63 | @Test
64 | public void testNativePresent() {
65 | assumeTrue(NativeCodeLoader.isNativeCodeLoaded());
66 | assertNull(NativeCodeLoader.getLoadingError());
67 | }
68 |
69 | @Test
70 | @Disabled("Seems to cause issues with other tests on Linux; disable for now")
71 | // It causes problems because the system properties are temporarily changed.
72 | // However, properties are only fetched once, thus the test either corrupts the settings
73 | // or does not work, depending on the order of tests.
74 | public void testUnSuccessfulLoad() throws Exception {
75 | final String nameKey = System.getProperty(Crypto.LIB_NAME_KEY);
76 | final String pathKey = System.getProperty(Crypto.LIB_PATH_KEY);
77 | // An empty file should cause UnsatisfiedLinkError
78 | final Path empty = Files.createTempFile("NativeCodeLoaderTest", "tmp");
79 | try {
80 | System.setProperty(Crypto.LIB_PATH_KEY, empty.getParent().toString());
81 | System.setProperty(Crypto.LIB_NAME_KEY, empty.getFileName().toString());
82 | final Throwable result = NativeCodeLoader.loadLibrary();
83 | assertNotNull(result);
84 | assertInstanceOf(UnsatisfiedLinkError.class, result);
85 | } finally {
86 | Files.delete(empty);
87 | if (nameKey != null) {
88 | System.setProperty(Crypto.LIB_NAME_KEY, nameKey);
89 | }
90 | if (pathKey != null) {
91 | System.setProperty(Crypto.LIB_PATH_KEY, pathKey);
92 | }
93 | }
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/OsInfoTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 |
22 | import org.junit.jupiter.api.Test;
23 |
24 | public class OsInfoTest {
25 |
26 | private static final String EXPECTED_PATH_PROPERTY = "OsInfoTest.expectedPath";
27 | @Test
28 | public void testMain() {
29 | OsInfo.main(new String[0]);
30 | OsInfo.main(new String[] { "--os" });
31 | OsInfo.main(new String[] { "--arch" });
32 |
33 | final String expectedPath = System.getProperty(EXPECTED_PATH_PROPERTY, "");
34 | if (expectedPath.isEmpty()) {
35 | System.out.println("Path was not checked");
36 | } else {
37 | assertEquals(expectedPath, OsInfo.getNativeLibFolderPathForCurrentOS(),"Path does not equal property" + EXPECTED_PATH_PROPERTY);
38 | System.out.println("Path is as expected");
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.cipher;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 | import static org.junit.jupiter.api.Assertions.assertThrows;
22 |
23 | import java.io.IOException;
24 | import java.security.GeneralSecurityException;
25 | import java.util.Properties;
26 |
27 | import org.apache.commons.crypto.utils.AES;
28 | import org.junit.jupiter.api.Test;
29 |
30 | public class CryptoCipherFactoryTest {
31 |
32 | @Test
33 | public void testDefaultCipher() throws GeneralSecurityException, IOException {
34 | try (CryptoCipher defaultCipher = CryptoCipherFactory.getCryptoCipher(AES.CTR_NO_PADDING)) {
35 | final String name = defaultCipher.getClass().getName();
36 | if (OpenSsl.getLoadingFailureReason() == null) {
37 | assertEquals(OpenSslCipher.class.getName(), name);
38 | } else {
39 | assertEquals(JceCipher.class.getName(), name);
40 | }
41 | }
42 | }
43 |
44 | @Test
45 | public void testEmptyCipher() throws GeneralSecurityException, IOException {
46 | final Properties properties = new Properties();
47 | properties.setProperty(CryptoCipherFactory.CLASSES_KEY, ""); // TODO should this really mean use the default?
48 | try (CryptoCipher defaultCipher = CryptoCipherFactory.getCryptoCipher(AES.CBC_NO_PADDING, properties)) {
49 | final String name = defaultCipher.getClass().getName();
50 | if (OpenSsl.getLoadingFailureReason() == null) {
51 | assertEquals(OpenSslCipher.class.getName(), name);
52 | } else {
53 | assertEquals(JceCipher.class.getName(), name);
54 | }
55 | }
56 | }
57 |
58 | @Test
59 | public void testInvalidCipher() {
60 | final Properties properties = new Properties();
61 | properties.setProperty(CryptoCipherFactory.CLASSES_KEY, "InvalidCipherName");
62 | assertThrows(GeneralSecurityException.class, () -> CryptoCipherFactory.getCryptoCipher(AES.CBC_NO_PADDING, properties));
63 |
64 | }
65 |
66 | @Test
67 | public void testInvalidTransformation() {
68 | final Properties properties = new Properties();
69 | assertThrows(GeneralSecurityException.class, () -> CryptoCipherFactory.getCryptoCipher("AES/Invalid/NoPadding", properties));
70 |
71 | }
72 |
73 | @Test
74 | public void testNoCipher() {
75 | final Properties properties = new Properties();
76 | // An empty string currently means use the default
77 | // However the splitter drops empty fields
78 | properties.setProperty(CryptoCipherFactory.CLASSES_KEY, ",");
79 | assertThrows(IllegalArgumentException.class, () -> CryptoCipherFactory.getCryptoCipher(AES.CBC_NO_PADDING, properties));
80 |
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.cipher;
20 |
21 | import static org.junit.jupiter.api.Assertions.assertThrows;
22 |
23 | import java.nio.ByteBuffer;
24 |
25 | import org.junit.jupiter.api.Test;
26 |
27 | /**
28 | * Tests default methods.
29 | */
30 | public class CryptoCipherTest {
31 |
32 | @Test
33 | public void testUpdateAADByteArray() {
34 | assertThrows(UnsupportedOperationException.class, () -> new DefaultCryptoCipher().updateAAD((byte[]) null));
35 | }
36 |
37 | @Test
38 | public void testUpdateAADByteBuffer() {
39 | assertThrows(UnsupportedOperationException.class, () -> new DefaultCryptoCipher().updateAAD((ByteBuffer) null));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/cipher/DefaultCryptoCipher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.cipher;
20 |
21 | import java.io.IOException;
22 | import java.nio.ByteBuffer;
23 | import java.security.InvalidAlgorithmParameterException;
24 | import java.security.InvalidKeyException;
25 | import java.security.Key;
26 | import java.security.spec.AlgorithmParameterSpec;
27 |
28 | import javax.crypto.BadPaddingException;
29 | import javax.crypto.IllegalBlockSizeException;
30 | import javax.crypto.ShortBufferException;
31 |
32 | /**
33 | * Tests default methods.
34 | */
35 | public class DefaultCryptoCipher implements CryptoCipher {
36 |
37 | @Override
38 | public void close() throws IOException {
39 | // Simplest
40 |
41 | }
42 |
43 | @Override
44 | public int doFinal(final byte[] input, final int inputOffset, final int inputLen, final byte[] output, final int outputOffset)
45 | throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
46 | // Simplest
47 | return 0;
48 | }
49 |
50 | @Override
51 | public int doFinal(final ByteBuffer inBuffer, final ByteBuffer outBuffer) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
52 | // Simplest
53 | return 0;
54 | }
55 |
56 | @Override
57 | public String getAlgorithm() {
58 | // Simplest
59 | return null;
60 | }
61 |
62 | @Override
63 | public int getBlockSize() {
64 | // Simplest
65 | return 0;
66 | }
67 |
68 | @Override
69 | public void init(final int mode, final Key key, final AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
70 | // Simplest
71 |
72 | }
73 |
74 | @Override
75 | public int update(final byte[] input, final int inputOffset, final int inputLen, final byte[] output, final int outputOffset) throws ShortBufferException {
76 | // Simplest
77 | return 0;
78 | }
79 |
80 | @Override
81 | public int update(final ByteBuffer inBuffer, final ByteBuffer outBuffer) throws ShortBufferException {
82 | // Simplest
83 | return 0;
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/cipher/JceCipherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.cipher;
20 |
21 | import static org.junit.jupiter.api.Assertions.assertTrue;
22 |
23 | import java.security.NoSuchAlgorithmException;
24 |
25 | import javax.crypto.Cipher;
26 |
27 | import org.apache.commons.crypto.utils.AES;
28 | import org.junit.jupiter.api.BeforeAll;
29 |
30 | public class JceCipherTest extends AbstractCipherTest {
31 |
32 | private static final int MAX_KEY_LEN_LOWER_BOUND = 256;
33 |
34 | @BeforeAll
35 | public static void checkJceUnlimitedStrength() throws NoSuchAlgorithmException {
36 | final int maxKeyLen = Cipher.getMaxAllowedKeyLength(AES.ALGORITHM);
37 | assertTrue(maxKeyLen >= MAX_KEY_LEN_LOWER_BOUND,
38 | String.format(
39 | "Testing requires support for an AES key length of %d, but " +
40 | "the detected maximum key length is %d. This may indicate " +
41 | "that the test environment is missing the JCE Unlimited " +
42 | "Strength Jurisdiction Policy Files.",
43 | MAX_KEY_LEN_LOWER_BOUND, maxKeyLen));
44 | }
45 |
46 | @Override
47 | public void init() {
48 | cipherClass = JCE_CIPHER_CLASSNAME;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/cipher/OpenSslCommonModeTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.cipher;
20 |
21 | import static org.junit.jupiter.api.Assertions.assertThrows;
22 |
23 | import org.junit.jupiter.api.Test;
24 |
25 | public class OpenSslCommonModeTest {
26 |
27 | @Test
28 | public void testUpdateAAD() {
29 | assertThrows(UnsupportedOperationException.class, () -> new OpenSslCommonMode(0, 0, 0).updateAAD(null));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/examples/RandomExample.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.examples;
19 |
20 | import java.io.IOException;
21 | import java.security.GeneralSecurityException;
22 | import java.util.Arrays;
23 | import java.util.Properties;
24 |
25 | import org.apache.commons.crypto.random.CryptoRandom;
26 | import org.apache.commons.crypto.random.CryptoRandomFactory;
27 |
28 | /**
29 | * Example showing use of the CryptoRandom API
30 | */
31 | public class RandomExample {
32 |
33 | public static void main(final String []args) throws GeneralSecurityException, IOException {
34 | // Constructs a byte array to store random data.
35 | final byte[] key = new byte[16];
36 | final byte[] iv = new byte[32];
37 |
38 | final Properties properties = new Properties();
39 | properties.put(CryptoRandomFactory.CLASSES_KEY,
40 | CryptoRandomFactory.RandomProvider.OPENSSL.getClassName());
41 |
42 | // Gets the 'CryptoRandom' instance.
43 | try (CryptoRandom random = CryptoRandomFactory.getCryptoRandom(properties)) {
44 |
45 | // Show the actual class (may be different from the one requested)
46 | System.out.println(random.getClass().getCanonicalName());
47 |
48 | // Generate random bytes and places them into the byte arrays.
49 | random.nextBytes(key);
50 | random.nextBytes(iv);
51 |
52 | }
53 |
54 | // Show the generated output
55 | System.out.println(Arrays.toString(key));
56 | System.out.println(Arrays.toString(iv));
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/examples/StreamExample.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.examples;
19 |
20 | import java.io.ByteArrayInputStream;
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.IOException;
23 | import java.io.InputStream;
24 | import java.nio.charset.StandardCharsets;
25 | import java.util.Arrays;
26 | import java.util.Properties;
27 |
28 | import javax.crypto.spec.IvParameterSpec;
29 | import javax.crypto.spec.SecretKeySpec;
30 |
31 | import org.apache.commons.crypto.stream.CryptoInputStream;
32 | import org.apache.commons.crypto.stream.CryptoOutputStream;
33 | import org.apache.commons.crypto.utils.AES;
34 |
35 | /**
36 | * Example showing how to use stream encryption and decryption.
37 | */
38 | public class StreamExample {
39 |
40 | /**
41 | * Converts String to UTF8 bytes
42 | *
43 | * @param input the input string
44 | * @return UTF8 bytes
45 | */
46 | private static byte[] getUTF8Bytes(final String input) {
47 | return input.getBytes(StandardCharsets.UTF_8);
48 | }
49 |
50 | public static void main(final String []args) throws IOException {
51 | final SecretKeySpec key = AES.newSecretKeySpec(getUTF8Bytes("1234567890123456"));
52 | final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
53 | final Properties properties = new Properties();
54 | final String transform = AES.CBC_PKCS5_PADDING;
55 |
56 | final String input = "hello world!";
57 | //Encryption with CryptoOutputStream.
58 |
59 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
60 |
61 | try (CryptoOutputStream cos = new CryptoOutputStream(transform, properties, outputStream, key, iv)) {
62 | cos.write(getUTF8Bytes(input));
63 | cos.flush();
64 | }
65 |
66 | // The encrypted data:
67 | System.out.println("Encrypted: "+Arrays.toString(outputStream.toByteArray()));
68 |
69 | // Decryption with CryptoInputStream.
70 | final InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
71 |
72 | try (CryptoInputStream cis = new CryptoInputStream(transform, properties, inputStream, key, iv)) {
73 | final byte[] decryptedData = new byte[1024];
74 | int decryptedLen = 0;
75 | int i;
76 | while ((i = cis.read(decryptedData, decryptedLen, decryptedData.length - decryptedLen)) > -1) {
77 | decryptedLen += i;
78 | }
79 | System.out.println("Decrypted: "+new String(decryptedData, 0, decryptedLen, StandardCharsets.UTF_8));
80 | }
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/examples/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | /**
20 | * Example classes
21 | */
22 | package org.apache.commons.crypto.examples;
23 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/CbcNoPaddingCipherJnaStreamTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.jna;
19 |
20 | import org.apache.commons.crypto.utils.AES;
21 |
22 | public class CbcNoPaddingCipherJnaStreamTest extends AbstractCipherJnaStreamTest {
23 |
24 | @Override
25 | public void setUp() {
26 | transformation = AES.CBC_NO_PADDING;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/CbcPkcs5PaddingCipherJnaStreamTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.jna;
19 |
20 | import org.apache.commons.crypto.utils.AES;
21 |
22 | public class CbcPkcs5PaddingCipherJnaStreamTest extends AbstractCipherJnaStreamTest {
23 |
24 | @Override
25 | public void setUp() {
26 | transformation = AES.CBC_PKCS5_PADDING;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/CryptoJnaBenchmark.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.commons.crypto.jna;
19 |
20 | import java.util.concurrent.TimeUnit;
21 |
22 | import org.apache.commons.crypto.AbstractBenchmark;
23 | import org.openjdk.jmh.annotations.Benchmark;
24 | import org.openjdk.jmh.annotations.BenchmarkMode;
25 | import org.openjdk.jmh.annotations.Fork;
26 | import org.openjdk.jmh.annotations.Measurement;
27 | import org.openjdk.jmh.annotations.OutputTimeUnit;
28 | import org.openjdk.jmh.annotations.Threads;
29 | import org.openjdk.jmh.annotations.Warmup;
30 | import org.openjdk.jmh.annotations.Mode;
31 |
32 | /**
33 | * Basic Benchmark to compare creation and runtimes for the different implementations.
34 | * Needs work to improve how well the tests mirror real-world use.
35 | */
36 | @BenchmarkMode(Mode.AverageTime)
37 | @Fork(value = 1, jvmArgs = "-server")
38 | @Threads(1)
39 | @Warmup(iterations = 10)
40 | @Measurement(iterations = 20)
41 | @OutputTimeUnit(TimeUnit.MILLISECONDS)
42 | public class CryptoJnaBenchmark extends AbstractBenchmark {
43 |
44 | private static final String RANDOM_OPENSSL_JNA = OpenSslJna.getRandomClass().getName();
45 |
46 | private static final String CIPHER_OPENSSL_JNA = OpenSslJna.getCipherClass().getName();
47 |
48 | @Benchmark
49 | public void CipherCreateOpensslJna() throws Exception {
50 | getCipher(CIPHER_OPENSSL_JNA);
51 | }
52 |
53 | @Benchmark
54 | public void CipherTestOpensslJna() throws Exception {
55 | encipher(CIPHER_OPENSSL_JNA);
56 | }
57 |
58 | @Benchmark
59 | public void RandomCreateOpensslJNA() throws Exception {
60 | getRandom(RANDOM_OPENSSL_JNA);
61 | }
62 |
63 | @Benchmark
64 | public void RandomTestOpensslJNA() throws Exception {
65 | random(RANDOM_OPENSSL_JNA);
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/CtrCryptoJnaStreamTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.jna;
19 |
20 | import org.apache.commons.crypto.utils.AES;
21 |
22 | public class CtrCryptoJnaStreamTest extends AbstractCipherJnaStreamTest {
23 |
24 | @Override
25 | public void setUp() {
26 | transformation = AES.CTR_NO_PADDING;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/CtrNoPaddingCipherJnaStreamTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.jna;
19 |
20 | import org.apache.commons.crypto.utils.AES;
21 |
22 | public class CtrNoPaddingCipherJnaStreamTest extends AbstractCipherJnaStreamTest {
23 |
24 | @Override
25 | public void setUp() {
26 | transformation = AES.CTR_NO_PADDING;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/OpenSslJnaCipherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.jna;
20 |
21 | import static org.junit.jupiter.api.Assumptions.assumeTrue;
22 |
23 | import org.apache.commons.crypto.cipher.AbstractCipherTest;
24 |
25 | public class OpenSslJnaCipherTest extends AbstractCipherTest {
26 |
27 | @Override
28 | public void init() {
29 | assumeTrue(OpenSslJna.isEnabled());
30 | cipherClass = OpenSslJnaCipher.class.getName();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/OpenSslJnaCryptoRandomTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.jna;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertInstanceOf;
21 |
22 | import java.security.GeneralSecurityException;
23 | import java.util.Properties;
24 |
25 | import org.apache.commons.crypto.random.AbstractRandomTest;
26 | import org.apache.commons.crypto.random.CryptoRandom;
27 | import org.apache.commons.crypto.random.CryptoRandomFactory;
28 | import org.junit.jupiter.api.Assumptions;
29 | import org.junit.jupiter.api.BeforeEach;
30 |
31 | public class OpenSslJnaCryptoRandomTest extends AbstractRandomTest {
32 |
33 | @Override
34 | public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
35 | final Properties props = new Properties();
36 | props.setProperty(CryptoRandomFactory.CLASSES_KEY, OpenSslJnaCryptoRandom.class.getName());
37 | final CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
38 | assertInstanceOf(OpenSslJnaCryptoRandom.class, random, "The CryptoRandom should be: " + OpenSslJnaCryptoRandom.class.getName());
39 | return random;
40 | }
41 |
42 | @BeforeEach
43 | public void init() {
44 | Assumptions.assumeTrue(OpenSslJna.isEnabled());
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/OpenSslJnaTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.jna;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 |
22 | import org.junit.jupiter.api.Test;
23 |
24 | public class OpenSslJnaTest {
25 |
26 | // If defined, then fail if the version does not match major/minor bits
27 | private static final String EXPECTED_VERSION_PROPERTY = "OpenSslJnaTest.expectedVersion";
28 |
29 | @Test
30 | public void testMain() throws Throwable {
31 | OpenSslJna.main(new String[0]);
32 | final String expectedVersion = System.getProperty(EXPECTED_VERSION_PROPERTY, "");
33 | if (expectedVersion.isEmpty()) {
34 | System.out.println("OpenSSL version was not checked");
35 | } else {
36 | assertEquals(expectedVersion, Long.toHexString(OpenSslNativeJna.OpenSSL_version_num() & 0xFFFF0000));
37 | System.out.println("OpenSSL version is as expected");
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/OpenSslNativeJnaTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.jna;
20 |
21 | import static org.junit.jupiter.api.Assertions.assertTrue;
22 |
23 | import org.junit.jupiter.api.Test;
24 | import org.junit.jupiter.api.TestReporter;
25 |
26 | public class OpenSslNativeJnaTest {
27 |
28 | @Test
29 | public void test(final TestReporter reporter) {
30 | if (OpenSslJna.isEnabled()) {
31 | reporter.publishEntry(String.format("JNA loaded OK for lib version 0x%x: ", OpenSslNativeJna.VERSION));
32 | } else {
33 | reporter.publishEntry(String.format("** ERROR: JNA NOT loaded OK for lib version 0x%x: ", OpenSslNativeJna.VERSION));
34 | }
35 | assertTrue(true, "Test OK"); // dummy for now
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/jna/PositionedCryptoInputStreamJnaTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package org.apache.commons.crypto.jna;
18 |
19 | import static org.junit.jupiter.api.Assumptions.assumeTrue;
20 |
21 | import org.apache.commons.crypto.stream.PositionedCryptoInputStreamTest;
22 | import org.junit.jupiter.api.BeforeEach;
23 | import org.junit.jupiter.api.Test;
24 |
25 | /**
26 | */
27 | public class PositionedCryptoInputStreamJnaTest extends PositionedCryptoInputStreamTest {
28 |
29 | @BeforeEach
30 | public void init() {
31 | assumeTrue(OpenSslJna.isEnabled());
32 | }
33 |
34 | @Test
35 | @Override // Don't load JNI!
36 | public void testJNI() throws Exception {
37 | }
38 |
39 | @Test
40 | public void testCipher() throws Exception {
41 | testCipher(OpenSslJnaCipher.class.getName());
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/random/AbstractRandom.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package org.apache.commons.crypto.random;
18 |
19 | import java.util.Properties;
20 |
21 | /**
22 | * Only provides a constructor.
23 | */
24 | abstract class AbstractRandom implements CryptoRandom {
25 |
26 | AbstractRandom(final Properties properties) {
27 | // empty
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/random/AbstractRandomTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.random;
19 |
20 | import java.lang.Thread.State;
21 | import java.security.GeneralSecurityException;
22 | import java.util.ArrayList;
23 | import java.util.Arrays;
24 | import java.util.List;
25 | import java.util.concurrent.TimeUnit;
26 |
27 | import org.junit.jupiter.api.Test;
28 | import org.junit.jupiter.api.Timeout;
29 |
30 | public abstract class AbstractRandomTest {
31 |
32 | /**
33 | * Test will timeout if secure random implementation always returns a constant value.
34 | */
35 | private void checkRandomBytes(final CryptoRandom random, final int len) {
36 | final byte[] bytes = new byte[len];
37 | final byte[] bytes1 = new byte[len];
38 | random.nextBytes(bytes);
39 | random.nextBytes(bytes1);
40 |
41 | while (Arrays.equals(bytes1, new byte[len]) || Arrays.equals(bytes, bytes1)) {
42 | random.nextBytes(bytes1);
43 | }
44 | }
45 |
46 | public abstract CryptoRandom getCryptoRandom() throws GeneralSecurityException;
47 |
48 | @Test
49 | @Timeout(value = 120000, unit = TimeUnit.MILLISECONDS)
50 | public void testRandomBytes() throws Exception {
51 | try (CryptoRandom random = getCryptoRandom()) {
52 | // len = 16
53 | checkRandomBytes(random, 16);
54 | // len = 32
55 | checkRandomBytes(random, 32);
56 | // len = 128
57 | checkRandomBytes(random, 128);
58 | // len = 256
59 | checkRandomBytes(random, 256);
60 | }
61 | }
62 |
63 | @Test
64 | @Timeout(value = 120000, unit = TimeUnit.MILLISECONDS)
65 | public void testRandomBytesMultiThreaded() throws Exception {
66 | final int threadCount = 100;
67 | try (final CryptoRandom random = getCryptoRandom()) {
68 | final List threads = new ArrayList<>(threadCount);
69 |
70 | for (int i = 0; i < threadCount; i++) {
71 | final Thread t = new Thread(() -> {
72 | checkRandomBytes(random, 10);
73 | checkRandomBytes(random, 1000);
74 | checkRandomBytes(random, 100000);
75 | });
76 | t.start();
77 | threads.add(t);
78 | }
79 |
80 | for (final Thread t : threads) {
81 | if (!t.getState().equals(State.NEW)) {
82 | t.join();
83 | }
84 | }
85 |
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/random/ExceptionInInitializerErrorRandom.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package org.apache.commons.crypto.random;
18 |
19 | import java.io.IOException;
20 | import java.security.GeneralSecurityException;
21 |
22 | /**
23 | * Simulates scenarios where {@link OpenSslCryptoRandom} fails in the static code block {@code checkNative()} or
24 | * {@code !OpenSslCryptoRandomNative.nextRandBytes(new byte[1])} is false.
25 | */
26 | public class ExceptionInInitializerErrorRandom implements CryptoRandom {
27 |
28 | static {
29 | try {
30 | check();
31 | } catch (final GeneralSecurityException e) {
32 | throw new IllegalStateException(e);
33 | }
34 | }
35 |
36 | private static void check() throws GeneralSecurityException {
37 | throw new GeneralSecurityException("ExceptionInInitializerErrorRandom init failed");
38 | }
39 |
40 | @Override
41 | public void close() throws IOException {
42 | // empty
43 | }
44 |
45 | @Override
46 | public void nextBytes(final byte[] bytes) {
47 | // empty
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/random/FailingRandom.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package org.apache.commons.crypto.random;
18 |
19 | import java.util.Properties;
20 |
21 | final class FailingRandom implements CryptoRandom {
22 |
23 | public static native void NoSuchMethod();
24 |
25 | /** Should fail with NoSuchMethodException. */
26 | FailingRandom(final Properties props) {
27 | NoSuchMethod();
28 | }
29 |
30 | @Override
31 | public void close() {
32 | // empty
33 | }
34 |
35 | @Override
36 | public void nextBytes(final byte[] bytes) {
37 | // empty
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/random/JavaCryptoRandomTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.random;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertInstanceOf;
21 |
22 | import java.security.GeneralSecurityException;
23 | import java.util.Properties;
24 |
25 | public class JavaCryptoRandomTest extends AbstractRandomTest {
26 |
27 | @Override
28 | public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
29 | final Properties props = new Properties();
30 | props.setProperty(CryptoRandomFactory.CLASSES_KEY, JavaCryptoRandom.class.getName());
31 | final CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
32 | assertInstanceOf(JavaCryptoRandom.class, random, "The CryptoRandom should be: " + JavaCryptoRandom.class.getName());
33 | return random;
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/random/MissingPropertyCtrRandom.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package org.apache.commons.crypto.random;
18 |
19 | final class MissingPropertyCtrRandom implements CryptoRandom {
20 |
21 | /** Should fail with NoSuchMethodException (has no constructor with a Properties argument). */
22 | MissingPropertyCtrRandom() {
23 | // empty
24 | }
25 |
26 | @Override
27 | public void close() {
28 | // empty
29 | }
30 |
31 | @Override
32 | public void nextBytes(final byte[] bytes) {
33 | // empty
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/random/OpenSslCryptoRandomTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.random;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertInstanceOf;
21 | import static org.junit.jupiter.api.Assumptions.assumeTrue;
22 |
23 | import java.security.GeneralSecurityException;
24 | import java.util.Properties;
25 |
26 | import org.apache.commons.crypto.Crypto;
27 | import org.junit.jupiter.api.BeforeAll;
28 |
29 | public class OpenSslCryptoRandomTest extends AbstractRandomTest {
30 |
31 | @BeforeAll
32 | public static void beforeAll() {
33 | assumeTrue(Crypto.isNativeCodeLoaded());
34 | assumeTrue(OpenSslCryptoRandom.isNativeCodeEnabled()); // should not throw
35 | }
36 |
37 | @Override
38 | public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
39 | final Properties props = new Properties();
40 | props.setProperty(CryptoRandomFactory.CLASSES_KEY, OpenSslCryptoRandom.class.getName());
41 | final CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
42 | assertInstanceOf(OpenSslCryptoRandom.class, random, "The CryptoRandom should be: " + OpenSslCryptoRandom.class.getName());
43 | return random;
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/random/OsCryptoRandomTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.random;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 | import static org.junit.jupiter.api.Assertions.assertInstanceOf;
22 | import static org.junit.jupiter.api.Assertions.assertThrows;
23 | import static org.junit.jupiter.api.Assumptions.assumeTrue;
24 |
25 | import java.io.FileNotFoundException;
26 | import java.lang.reflect.InvocationTargetException;
27 | import java.security.GeneralSecurityException;
28 | import java.util.Properties;
29 |
30 | import org.apache.commons.lang3.SystemProperties;
31 | import org.junit.jupiter.api.Test;
32 |
33 | public class OsCryptoRandomTest extends AbstractRandomTest {
34 |
35 | @Override
36 | public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
37 | // Windows does not have a /dev/random device
38 | assumeTrue(!SystemProperties.getOsName().contains("Windows"));
39 | final Properties props = new Properties();
40 | props.setProperty(CryptoRandomFactory.CLASSES_KEY, OsCryptoRandom.class.getName());
41 | final CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
42 | assertInstanceOf(OsCryptoRandom.class, random, "The CryptoRandom should be: " + OsCryptoRandom.class.getName());
43 | return random;
44 | }
45 |
46 | @Test
47 | public void testInvalidRandom() {
48 | final Properties props = new Properties();
49 | props.setProperty(CryptoRandomFactory.CLASSES_KEY, OsCryptoRandom.class.getName());
50 | // Invalid device
51 | props.setProperty(CryptoRandomFactory.DEVICE_FILE_PATH_KEY, "");
52 | final Exception e = assertThrows(GeneralSecurityException.class, () -> CryptoRandomFactory.getCryptoRandom(props));
53 | Throwable cause;
54 | cause = e.getCause();
55 | assertEquals(IllegalArgumentException.class, cause.getClass());
56 | cause = cause.getCause();
57 | assertEquals(InvocationTargetException.class, cause.getClass());
58 | cause = cause.getCause();
59 | assertEquals(IllegalArgumentException.class, cause.getClass());
60 | cause = cause.getCause();
61 | assertEquals(FileNotFoundException.class, cause.getClass());
62 |
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/stream/CbcNoPaddingCipherStreamTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.stream;
19 |
20 | import org.apache.commons.crypto.utils.AES;
21 |
22 | public class CbcNoPaddingCipherStreamTest extends AbstractCipherStreamTest {
23 |
24 | @Override
25 | public void setUp() {
26 | transformation = AES.CBC_NO_PADDING;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/stream/CbcPkcs5PaddingCipherStreamTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.stream;
19 |
20 | import org.apache.commons.crypto.utils.AES;
21 |
22 | public class CbcPkcs5PaddingCipherStreamTest extends AbstractCipherStreamTest {
23 |
24 | @Override
25 | public void setUp() {
26 | transformation = AES.CBC_PKCS5_PADDING;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/stream/CtrNoPaddingCipherStreamTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.stream;
19 |
20 | import org.apache.commons.crypto.utils.AES;
21 |
22 | public class CtrNoPaddingCipherStreamTest extends AbstractCipherStreamTest {
23 |
24 | @Override
25 | public void setUp() {
26 | transformation = AES.CTR_NO_PADDING;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/stream/input/ChannelInputTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.stream.input;
20 |
21 | import static org.junit.jupiter.api.Assertions.assertEquals;
22 |
23 | import java.io.ByteArrayInputStream;
24 | import java.io.IOException;
25 | import java.nio.channels.Channels;
26 |
27 | import org.junit.jupiter.api.Test;
28 |
29 | /**
30 | * Tests {@link ChannelInput}.
31 | */
32 | public class ChannelInputTest {
33 |
34 | @Test
35 | public void testSkipWithSkipBuffer() throws IOException {
36 | try (final ChannelInput channelInput = new ChannelInput(
37 | Channels.newChannel(new ByteArrayInputStream(new byte[10])))) {
38 | assertEquals(0, channelInput.skip(0));
39 | assertEquals(0, channelInput.skip(-1));
40 | assertEquals(1, channelInput.skip(1));
41 | assertEquals(1, channelInput.skip(1));
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/stream/output/StreamOutputTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | package org.apache.commons.crypto.stream.output;
20 |
21 | import static org.junit.jupiter.api.Assertions.assertEquals;
22 |
23 | import java.io.ByteArrayOutputStream;
24 | import java.io.IOException;
25 |
26 | import org.junit.jupiter.api.Test;
27 |
28 | /**
29 | * Tests {@link StreamOutput}.
30 | */
31 | public class StreamOutputTest {
32 |
33 | @Test
34 | public void testGetOut() throws IOException {
35 | final ByteArrayOutputStream baos = new ByteArrayOutputStream();
36 | try (StreamOutput streamOutput = new StreamOutput(baos, 1024)) {
37 | assertEquals(baos, streamOutput.getOut());
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/utils/EnumTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.utils;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 | import static org.junit.jupiter.api.Assertions.assertTrue;
22 |
23 | import org.apache.commons.crypto.cipher.CryptoCipher;
24 | import org.apache.commons.crypto.cipher.CryptoCipherFactory;
25 | import org.apache.commons.crypto.cipher.CryptoCipherFactory.CipherProvider;
26 | import org.apache.commons.crypto.random.CryptoRandom;
27 | import org.apache.commons.crypto.random.CryptoRandomFactory;
28 | import org.apache.commons.crypto.random.CryptoRandomFactory.RandomProvider;
29 | import org.junit.jupiter.api.Test;
30 |
31 | /**
32 | * Test the enums used to define the internal implementation classes
33 | */
34 | public class EnumTest {
35 |
36 | private void checkImplClass(final CipherProvider value) {
37 | final Class extends CryptoCipher> implClass = value.getImplClass();
38 | assertTrue(CryptoCipher.class.isAssignableFrom(implClass), implClass.toString());
39 | assertEquals(value.getClassName(), implClass.getName());
40 | }
41 |
42 | private void checkImplClass(final RandomProvider value) {
43 | final Class extends CryptoRandom> implClass = value.getImplClass();
44 | assertTrue(CryptoRandom.class.isAssignableFrom(implClass), implClass.toString());
45 | assertEquals(value.getClassName(), implClass.getName());
46 | }
47 |
48 | @Test
49 | public void testCipher() throws Exception {
50 | for (final CipherProvider value : CryptoCipherFactory.CipherProvider.values()) {
51 | ReflectionUtils.getClassByName(value.getClassName());
52 | checkImplClass(value);
53 | }
54 | }
55 |
56 | @Test
57 | public void testRandom() throws Exception {
58 | for (final RandomProvider value : CryptoRandomFactory.RandomProvider.values()) {
59 | ReflectionUtils.getClassByName(value.getClassName());
60 | checkImplClass(value);
61 | }
62 | }
63 |
64 | // TODO check if any implementations of CryptoRandom or CryptoCipher are missing from the values
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/src/test/java/org/apache/commons/crypto/utils/UtilsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | package org.apache.commons.crypto.utils;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 |
22 | import java.util.Arrays;
23 | import java.util.Collections;
24 | import java.util.List;
25 | import java.util.Properties;
26 |
27 | import org.junit.jupiter.api.Test;
28 |
29 | public class UtilsTest {
30 | @Test
31 | public void testGetProperties() {
32 | final Properties props = new Properties();
33 | props.setProperty(
34 | "garbage.in",
35 | "out");
36 | final Properties allprops = Utils.getProperties(props);
37 | assertEquals(allprops.getProperty("garbage.in"), "out");
38 | }
39 |
40 | @Test
41 | public void testSplitNull() {
42 | assertEquals(Collections. emptyList(), Utils.splitClassNames(null, ","));
43 | }
44 |
45 | @Test
46 | public void testSplitOmitEmptyLine() {
47 | List clazzNames = Utils.splitClassNames("", ",");
48 | assertEquals(Collections. emptyList(), clazzNames);
49 |
50 | clazzNames = Utils.splitClassNames("a,b", ",");
51 | assertEquals(Arrays.asList("a", "b"), clazzNames);
52 | clazzNames = Utils.splitClassNames("a,b,", ",");
53 | assertEquals(Arrays.asList("a", "b"), clazzNames);
54 | clazzNames = Utils.splitClassNames("a, b,", ",");
55 | assertEquals(Arrays.asList("a", "b"), clazzNames);
56 | }
57 | }
58 |
--------------------------------------------------------------------------------